Welcome to this tutorial! Our goal is to understand and effectively use Form Requests in Laravel. Form Requests are a powerful feature in Laravel that allows us to encapsulate validation and authorization logic, keeping our controllers lean and our codebase organized.
By the end of this tutorial, you will be able to:
Prerequisites: You should have a basic understanding of PHP programming and some familiarity with Laravel.
Form Requests in Laravel are special classes that extend the base FormRequest
class. These classes are responsible for validating the incoming HTTP request data and also authorize the request.
To create a Form Request class, we use the following artisan command:
php artisan make:request StoreBlogPost
This will create a StoreBlogPost
class in the app/Http/Requests
directory.
Here's an example of a Form Request class:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreBlogPost extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true; // Change this based on your authorization logic
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'title' => 'required|max:255',
'body' => 'required',
];
}
}
In this example, authorize()
method is used to determine if the user is authorized to make this request, returning true means any user can make this request. Inside rules()
method we define our validation rules for the incoming request data.
To use this Form Request, we simply type-hint it on our controller method:
namespace App\Http\Controllers;
use App\Http\Requests\StoreBlogPost;
class PostController extends Controller
{
public function store(StoreBlogPost $request)
{
// The incoming request is valid...
// Retrieve the validated input data...
$validated = $request->validated();
}
}
In this tutorial, we delved into Form Requests in Laravel, a great feature that allows us to encapsulate validation and authorization logic. We learnt how to create and use Form Requests, and how they help in keeping our controllers lean and our codebase more maintainable.
Additional resources:
Create a Form Request for a UserRegistration
form with the fields: name
, email
, password
.
Extend the above exercise and add authorization logic to only allow guests (non-logged in users) to make the request.
Create a Form Request for a ProductCreation
form with fields: name
, description
, price
. Add custom validation messages for each validation rule.
Solutions and explanations for these exercises can be found in the Laravel documentation. Remember, practice is key to mastering any concept. So, keep practicing and happy coding!