Laravel have almost everything you need to work with validation for validate your user input data before insert it to the database. There variety ways to validation your request data, you can validate in your controller or validate using Laravel request. Which way you choose there no right or wrong but remember if you using Laravel request for validate your controller look clean also the request data will not enter controller as it will hit the request first.
Create request with artisan command
For example we want to validate article input so we named it ArticleRequest to create by type the command below
php artisan make:request ArticleRequest
Implementation
In your app/Http/Requests you will see ArticleRequest.php. Adjust the authorize function to return true due to we don’t care about authorization. To write any validation logic you can write it in the rules function. See the full example below.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ArticleRequest 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()
{
$rules = [
'title' => 'required|max:255|unique:articles,title',
'content' => 'required',
'category_id' => 'required|exists:categories,id',
'tag_ids' => 'array',
'tag_ids.*' => 'required|exists:tags,id|distinct',
];
return $rules;
}
}
Usage
In the controller where you want to validate replace the default Request class with new created Request validate.
public function store(ArticleRequest $request)
{
DB::beginTransaction();
try {
$article = Article::create($request->only('title', 'content', 'category_id'));
$article->tags()->sync($request->input('tag_ids'));
DB::commit();
return response()->json([ 'success' => true ]);
} catch (\Throwable $th) {
DB::rollback();
throw $th;
}
}
Don’t forget to use the namespace use App\Http\Requests\ArticleRequest;
Conclusion
After follow all the steps above you will have a validate with Laravel request to summary for validating with request:
- Create request by using php artisan make:request YourRequest.
- Write any validate logic in the rules function.
- To use it replace the default Request class with new created Request class.