[Seri] - Website đồng hồ - Validate dữ liệu

Trước khi insert dữ liệu vào database thì mình sẽ phải validate nó để tránh các trường hợp lỗi xẩy ra

Hiện tại ở trên form thêm mới danh mục mình chỉ để một input name nên mình sẽ validate mỗi nó thôi nhé

Tạo Request và nội dung 

Đầu tien các bạn tạo file request để tạo điều kiện và messages khi có lỗi 

php artisan make:request AdminRequestCategory

Sau khi tạo xong các bạn vào thư mục app/Http/Request sẽ thấy file AdminRequestCategory và điền nội dung như sau 

public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'c_name' => 'required|max:190|min:3|unique:categories,c_name,'.$this->id
        ];
    }

    public function messages()
    {
        return [
            'c_name.required'   => 'Dữ liệu không được để trống',
            'c_name.unique'     => 'Dữ liệu đã tồn tại',
            'c_name.max'        => 'Dữ liệu không quá 190 ký tự',
            'c_name.min'        => 'Dữ liệu phải nhiều hơn 3 ký tự'
        ];
    }

Ý nghĩa nó như thế nào thì mình đã giải thích rồi nhé

 Còn ở phần Controller thì các bạn vào file AdminCategoryController thêm cho mình nội dung như sau 


namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\AdminRequestCategory;

class AdminCategoryController extends AdminController
{
    public function index()
    {
        return view('admin.category.index');
    }

    public function create()
    {
        return view('admin.category.create');
    }

    public function store(AdminRequestCategory $request)
    {
        dd($request->all());
    }
}

View

Ở ngoài view thì các bạn xem video để chỉnh sửa lại nhé 

Để lại comment của bạn nếu gặp khó khăn

Bài viết liên quan