3. Validation error (ok)
https://viblo.asia/p/tap-13-blade-template-laravel-1VgZv1dRKAw
Ví dụ đã thực hiện thành công
C:\xampp\htdocs\blog\routes\web.php
Route::get('post/create', 'PostController@create');
Route::post('post', 'PostController@store');
C:\xampp\htdocs\blog\app\Http\Controllers\PostController.php
public function create() {
return view('create_post');
}
/**
* 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:10',
'body' => 'required|min:5',
]);
}
C:\xampp\htdocs\blog\resources\views\create_post.blade.php
@if ($errors->any())
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<h1>Create new post</h1>
<form action="/post" method="POST">
@csrf
<div>
<p>Title</p>
<input type="text" name="title">
</div>
<div>
<p>Body</p>
<textarea name="body" cols="30" rows="10"></textarea>
</div>
<br>
<div>
<button type="submit">Create</button>
</div>
</form>
Kết quả:

3. Validation error
Với cặp thẻ @error ... @enderror
ta có thể dễ dàng bắt bất kỳ thông báo nào khi request trả về lỗi. Về "Validation error message" ta sẽ tìm hiểu ở những tập sau nên phần này mình chỉ nó qua về cú pháp để kiểm tra có tồn tại lỗi được trả về tại blade template hay không.
// kiểm tra mặc định
@error('title')
{{ $message }}
@enderror
// Kiểm tra trong thuộc tính
<input id="title" type="text" class="@error('title') is-invalid @enderror">
@error
sẽ nhận tham số là tên lỗi mà chúng ta xử lý trước khi trả về cho blade view. Nếu true
thì nó sẽ thực thị lệnh trong cặp thẻ.
Last updated
Was this helpful?