- vừa được xem lúc

Laravel Request

0 0 5

Người đăng: Ngô Quốc Hùng

Theo Viblo Asia

Introduction

  • Laravel Illuminate\Http\Request class cung cấp một cách hướng đối tượng các phương thức để có thể tương tác với yêu cầu HTTP hiện tại đang được ứng dụng của bạn xử lý cũng như truy xuất dữ liệu đầu vào, cookie và tệp được gửi cùng request

Interacting With The Request (Tương tác với request)

Accessing The Request

  • Để truy cập vào phiên bản request hiện tại bạn nên type-hint một Illuminate\Http\Request class trong route closure hoặc method controller của bạn:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller
{ /** * Store a new user. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $name = $request->input('name'); // }
}
  • Trong route closure:
use Illuminate\Http\Request; Route::get('/', function (Request $request) { //
});

Dependency Injection & Route Parameters

  • Nếu method trong controller của bạn muốn truyền thêm tham số thì bạn nên thêm sau các dependencies, ví dụ route của bạn như sau:
use App\Http\Controllers\UserController; Route::put('/user/{id}', [UserController::class, 'update']);
  • Bạn vẫn có thể ty-hint dependencies của lớp Illuminate\Http\Request và truyền tham số id của route như sau:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserController extends Controller
{ /** * Update the specified user. * * @param \Illuminate\Http\Request $request * @param string $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // }
}

Request Path, Host, & Method

Retrieving The Request Path

  • Method path trên 1 phiên bản request sẽ return thông tin path hiện tại của request, để dễ hiểu 1 request đến http://example.com/foo/bar thì method path sẽ return về foo/bar:
$uri = $request->path();
//output foo/bar

Inspecting The Request Path / Route (Kiểm tra path/route hiện tại của request)

  • Method is cho phép bạn kiểm tra path hiện tại cần phải match với một pattern
  • Bạn có thể dùng ký tự đại diện * khi sử dụng method này
if ($request->is('admin/*')) { //
}
  • Sử dụng method routeIs để check tên route hiện tại (check theo name route):
if ($request->routeIs('admin.*')) { //
}

Retrieving The Request URL

  • Bạn có thể dùng method url hoặc fullUrl để lấy đầy đủ Url của request
  • Method url sẽ không trả về query string, còn fullUrl sẽ tra về đầy đủ query string như sau:

  • Nếu bạn muốn thêm query string vào Url hiện tại có thể dùng method fullUrlWithQuery:

Route:

Route::get('/user/{name?}', function (\Illuminate\Http\Request $request, $name = null) { dd($request->fullUrlWithQuery(['type' => 'phone']));
});
});

Kết quả:

Retrieving The Request Host

  • Để lấy thông tin về host của request bạn có thể sử dụng các method như sau host, httpHost, schemeAndHttpHost, sự khác biệt giữa các method có thể tham khảo kết quả dưới đây:

Retrieving The Request Method

  • Bạn có thể kiểm tra method của request hiện tại bằng cách sử dụng method method, ngoài ra bạn có thể verify method hiện tại khi dùng method isMethod (method này không phân biệt chữ hoa, thường)
$method = $request->method(); //output: GET, POST, PUT, PATCH, DELETE, OPTIONS if ($request->isMethod('post')) { //
}

Request Headers

  • Bạn có thể truy xuất request header thông qua instance của class Illuminate\Http\Request với method heaeder
  • Nếu header không tồn tại trong request thì null sẽ được trả về, tuy nhiên method header cung cấp 1 tham số thứ 2 là giá trị default sẽ được trả về trong trường hợp không tồn tại header cần check trong request
$value = $request->header('X-Header-Name'); $value = $request->header('X-Header-Name', 'default');
  • Chúng ta cũng có thể check sự tồn tại của header theo key bằng method hasHeader:
if ($request->hasHeader('X-Header-Name')) { //
}
  • Chúng ta có thể lấy 1 bearerToken từ Authorization header bằng method bearerToken, nếu không tồn tại bearerToken trong request thì method sẻ tra về một chuối string rỗng
$token = $request->bearerToken();

Request IP Address

  • Mehtod ip để truy xuất ip của client hiện đang gửi request:
$ipAddress = $request->ip();

Input

Retrieving Input

Retrieving All Input Data

  • Truy xuất data dưới dạng 1 array:
$input = $request->all();
  • Truy xuất data dưới dạng 1 collection:
$input = $request->collect();

Retrieving An Input Value

  • Truy xuất 1 input:
$name = $request->input('name');
  • Bạn có thể set default giá trị khi truy xuất 1 input không tồn tại:
$name = $request->input('name', 'Sally');
  • Truy xuất input là 1 mảng:
$name = $request->input('products.0.name'); $names = $request->input('products.*.name');
  • Truy xuất tất cả các input như 1 mảng:
$input = $request->input();

Retrieving Input From The Query String

  • Truy xuất query string theo tên:
$name = $request->query('name');
  • Truy xuất query string theo tên và gán giá trị default nếu không tồn tại query string theo tên:
$name = $request->query('name', 'Helen');
  • Truy xuất tất cả query string, trả về 1 mảng:
$query = $request->query();

Retrieving JSON Input Values

$name = $request->input('user.name');

Retrieving Stringable Input Values

$name = $request->string('name')->trim();

Retrieving Boolean Input Values

  • The boolean method returns true for 1, "1", true, "true", "on", and "yes". All other values will return false:
$archived = $request->boolean('archived');

Retrieving Date Input Values

  • Nếu không tồn tại theo tên thì sẽ trả về null
$birthday = $request->date('birthday');
  • Có thể chủ động format date như sau:
$elapsed = $request->date('elapsed', '!H:i', 'Europe/Madrid');

Retrieving Enum Input Values

use App\Enums\Status; $status = $request->enum('status', Status::class);

Retrieving Input Via Dynamic Properties

$name = $request->name;

Retrieving A Portion Of The Input Data

$input = $request->only(['username', 'password']); $input = $request->only('username', 'password'); $input = $request->except(['credit_card']); $input = $request->except('credit_card');

Determining If Input Is Present

  • Kiểm tra xem trong request có tồn tại giá trị được check hay không với has()
if ($request->has('name')) { //
}
if ($request->has(['name', 'email'])) { //
}
  • whenHas():
$request->whenHas('name', function ($input) { //
});
$request->whenHas('name', function ($input) { // The "name" value is present...
}, function () { // The "name" value is not present...
});
  • hasAny()
if ($request->hasAny(['name', 'email'])) { //
}
  • Kiểm tra sự tồn tại và khác chuỗi rỗng với filled():
if ($request->filled('name')) { //
}
  • whenFilled():
$request->whenFilled('name', function ($input) { //
});
$request->whenFilled('name', function ($input) { // The "name" value is filled...
}, function () { // The "name" value is not filled...
});
  • Kiểm tra giá trị request nếu không tồn tại:
if ($request->missing('name')) { //
} $request->whenMissing('name', function ($input) { // The "name" value is missing...
}, function () { // The "name" value is present...
});

Merging Additional Input

$request->merge(['votes' => 0]);
  • Kiểm tra missing và merge với key tương ứng:
$request->mergeIfMissing(['votes' => 0]);

Old Input

Flashing Input To The Session

$request->flash(); $request->flashOnly(['username', 'email']); $request->flashExcept('password');

Flashing Input Then Redirecting

return redirect('form')->withInput(); return redirect()->route('user.create')->withInput(); return redirect('form')->withInput( $request->except('password')
);

Retrieving Old Input

$username = $request->old('username');
  • Khi sử dụng trong blade
<input type="text" name="username" value="{{ old('username') }}">

Cookies

Retrieving Cookies From Requests

$value = $request->cookie('name');

Files

Retrieving Uploaded Files

$file = $request->file('photo'); $file = $request->photo;
  • Check tồn tại:
if ($request->hasFile('photo')) { //
}

Validating Successful Uploads

  • Kiểm tra xem việc upload file có xảy ra lỗi hay không:
if ($request->file('photo')->isValid()) { //
}

File Paths & Extensions

$path = $request->photo->path(); $extension = $request->photo->extension();

Storing Uploaded Files

$path = $request->photo->store('images'); $path = $request->photo->store('images', 's3'); $path = $request->photo->storeAs('images', 'filename.jpg'); $path = $request->photo->storeAs('images', 'filename.jpg', 's3'); 
  • Chúng ta sẽ tìm hiểu kỹ hơn trong phần filesystem.

Bình luận

Bài viết tương tự

- vừa được xem lúc

Tìm hiểu về Resource Controller trong Laravel

Giới thiệu. Trong laravel, việc sử dụng các route post, get, group để gọi đến 1 action của Controller đã là quá quen đối với các bạn sử dụng framework này.

0 0 350

- vừa được xem lúc

Phân quyền đơn giản với package Laravel permission

Như các bạn đã biết, phân quyền trong một ứng dụng là một phần không thể thiếu trong việc phát triển phần mềm, dù đó là ứng dụng web hay là mobile. Vậy nên, hôm nay mình sẽ giới thiệu một package có thể giúp các bạn phân quyền nhanh và đơn giản trong một website được viết bằng PHP với framework là L

0 0 440

- vừa được xem lúc

Sử dụng Swagger để xây dựng API documentation

Giới thiệu về Swagger. RESTful API là một tiêu chuẩn dùng trong việc thiết kế API cho các ứng dụng web (thiết kế Web services) để tiện cho việc quản lý các resource.

0 0 1k

- vừa được xem lúc

Ví dụ CRUD với Laravel và Vuejs.

1. Cài đặt Laravel. composer create-project --prefer-dist laravel/laravel vuelaravelcrud. .

0 0 151

- vừa được xem lúc

Một số tips khi dùng laravel (Part 1)

1. Show database query in raw SQL format. DB::enableQueryLog(); // Bật tính năng query logging. DB::table('users')->get(); // Chạy truy vấn bạn muốn ghi log.

0 0 79

- vừa được xem lúc

Inertiajs - Xây dựng Single Page App không cần API

Tiêu đề là mình lấy từ trang chủ của https://inertiajs.com/ chứ không phải mình tự nghĩ ra đâu nhé :v. Lâu lâu rồi chưa động tới Laravel (dự án cuối cùng mình code là ở ver 5.8), thế nên một ngày đẹp trời lượn vào đọc docs ver 8.

0 0 237