😇Tạo, Ủy quyền,Adding After Hooks (form request), validate dùng chung, Tùy chỉnh error Phần 1 (ok)

https://viblo.asia/p/tap-20-validation-laravel-GrLZDWAEKk0

Lệnh tạo request
php artisan make:request StorePost

Cách 1: Sử dụng thông thường

C:\xampp8\htdocs\plugindev\app\Http\Controllers\web.php

<?php
use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
  return view('welcome');
});
Route::get('post/create', [PostController::class, 'create']);
Route::post('/post', [PostController::class, 'store']);

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    $validatedData = $request->validate([
      'title' => 'required|max:100',
      'body' => 'required|min:50',
    ]);
  }
  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function show($id)
  {
    //
  }
  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    //
  }
  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    //
  }
  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    //
  }
}

C:\xampp8\htdocs\plugindev\resources\views\posts\create.blade.php

<style>
  .error {
    color: red;
  }
</style>
<h1>Create new post</h1>
<form action="/post" method="POST">
  @csrf
  <div>
    <p @error('title') class="error" @enderror>
      Title
      @error('title')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <input type="text" name="title">
  </div>
  <div>
    <p @error('body') class="error" @enderror>
      Body
      @error('body')
      : <span>{{ $message }}</span>
      @enderror
    </p>
    <textarea name="body" cols="30" rows="10"></textarea>
  </div>
  <br>
  <div>
    <button type="submit">Create</button>
  </div>
</form>

Cách 2: Tạo form request (Creating form request)

C:\xampp8\htdocs\plugindev\app\Http\Requests\StorePost.php

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePost extends FormRequest
{
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize()
  {
    return true;
  }
  /**
   * Get the validation rules that apply to the request.
   *
   * @return array<string, mixed>
   */
  public function rules()
  {
    return [
      'title' => 'required|max:100',
      'body' => 'required|min:50'
    ];
  }
}

C:\xampp8\htdocs\plugindev\app\Http\Controllers\PostController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\StorePost;
class PostController extends Controller
{
  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index()
  {
    //
  }
  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create()
  {
    return view('posts.create');
  }
  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(StorePost $request)
  {
    $validated = $request->validated();
  }
  /**
   * Display the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function show($id)
  {
    //
  }
  /**
   * Show the form for editing the specified resource.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function edit($id)
  {
    //
  }
  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, $id)
  {
    //
  }
  /**
   * Remove the specified resource from storage.
   *
   * @param  int  $id
   * @return \Illuminate\Http\Response
   */
  public function destroy($id)
  {
    //
  }
}

Ủy quyền form request (Authorizing form request) Chú ý: method authorize in C:\xampp8\htdocs\plugindev\app\Http\Requests\StorePost.php

Nếu return true; thì Thay vì mình nhận mã lỗi 422, thì bây giờ lại là 403 cùng với thông báo "This action is unauthorize".

method này sẽ quyết định rằng ta được quyền gửi form request đến controller hay là không với boolean true hoặc false.

Với method này, ta có thể ứng dụng để kiểm tra xem tài nguyên có thuộc về sở hữu của người dùng trong việc chỉnh sửa hoặc xóa tài nguyên. Chẳng hạn hệ thống sẽ kiểm tra ID bài viết có thuộc về quyền sở hữu của tác giả hay không để tiếp tục thực thi chỉnh sửa hoặc xóa bài viết.

Adding After Hooks To Form Requests

Tiêu đề này khó dịch sát nghĩa nên mình sẽ để nguyên như Laravel Docs. Việc này sẽ giống như bạn có thể đính kèm một callback sau khi việc validation hoàn tất. Để làm được nó, bạn chỉ cần khai báo method withValidator trong form request với nội dung sau:

Tùy chỉnh thông báo lỗi (Customizing the error message)

Bạn có thể tùy chỉnh thông báo lỗi bằng method messages trong form request. Method này sẽ trả về mảng thuộc tính/rule và các thông báo lỗi tương ứng. Chẳng hạn với ví dụ trên, mình sẽ định nghĩa thêm method messages cho form request StorePost.

C:\xampp8\htdocs\plugindev\app\Http\Requests\StorePost.php

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePost extends FormRequest
{
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize()
  {
    return true;
  }
  /**
   * Get the validation rules that apply to the request.
   *
   * @return array<string, mixed>
   */
  public function rules()
  {
    return [
      'title' => 'required|max:100',
      'body' => 'required|min:50'
    ];
  }
  public function withValidator($validator)
  {
    $validator->after(function ($validator) {
      $validator->errors()->add('field', 'Something is wrong with this field!');
    });
  }
  public function messages()
  {
    return [
      'title.required' => 'Tiêu đề bài viết không được bỏ trống',
      'body.required' => 'Nội dung bài viết không được bỏ trống'
    ];
  }
}

Tùy chỉnh thuộc tính validation (Customizing the validation attribute)

Nhìn kết quả trên khá ok nhưng các bạn sẽ cảm thấy không chuyên nghiệp cho lắm, vì :attribute mặc định sẽ lấy name của request được gửi đến để làm thông báo lỗi. Nhưng Laravel đã cung cấp cho chúng ta method attributes để thay đổi thiết lập đó.

C:\xampp8\htdocs\plugindev\app\Http\Requests\StorePost.php

Trước

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePost extends FormRequest
{
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize()
  {
    return true;
  }
  /**
   * Get the validation rules that apply to the request.
   *
   * @return array<string, mixed>
   */
  public function rules()
  {
    return [
      'title' => 'required|max:100',
      'body' => 'required|min:50'
    ];
  }
  public function withValidator($validator)
  {
    $validator->after(function ($validator) {
      $validator->errors()->add('field', 'Something is wrong with this field!');
    });
  }
  // public function attributes()
  // {
  //   return [
  //     'title' => 'Tiêu đề bài viết',
  //     'body' => 'Nội dung bài viết'
  //   ];
  // }
}

Sau

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePost extends FormRequest
{
  /**
   * Determine if the user is authorized to make this request.
   *
   * @return bool
   */
  public function authorize()
  {
    return true;
  }
  /**
   * Get the validation rules that apply to the request.
   *
   * @return array<string, mixed>
   */
  public function rules()
  {
    return [
      'title' => 'required|max:100',
      'body' => 'required|min:50'
    ];
  }
  public function withValidator($validator)
  {
    $validator->after(function ($validator) {
      $validator->errors()->add('field', 'Something is wrong with this field!');
    });
  }
  public function attributes()
  {
    return [
      'title' => 'Tiêu đề bài viết',
      'body' => 'Nội dung bài viết'
    ];
  }
}

Last updated