Create Custom Request
Sun May 16 2021 17:42:10 GMT+0000 (Coordinated Universal Time)
Saved by
@slendabilt
#laravel
/**
* Artisan Command
*/
php artisan make:request RequestName
/**
* Controller Code
*/
// inject filepath to custom request
use App\Http\Requests\RequestName;
// inject custom request as $request
// $request knows about validation and will automatically validate
public function store(RequestName $request)
{
Category::create([
'name' => $request->name
]);
session()->flash('success', 'Category Successfully Created');
return redirect(route('categories.index'));
}
/**
* Request File
*/
class CreateCategoryRequest 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
*/
public function rules()
{
// this is where validation rules are set
return [
'name' => 'required|unique:categories'
];
}
}
content_copyCOPY
create custom request class for more complex validation scenarios. Helps to keep controllers clean.
https://laravel.com/docs/8.x/validation#form-request-validation
Comments