Lesson 9 - Simple CMS in Laravel - Article management
HTTP requirements
Before we get into developing new parts of the application, let's look back at our store()
method in the ArticleController.php
controller, which we defined in the last lesson. As the name suggests, this method should be used to insert a new record (in our case, an article) into the database. Among other things, it also contains validation of the received data, which in the case of larger forms may not be very practical. Therefore, we introduce the so-called Request
classes.
Request classes
Request
classes check whether the user is authorized to send the request and validate the sent data. We can move the set of rules of the given HTTP request to them and the controller method will then contain only the action logic. Let's create such a class now.
For the store()
action, we generate the StoreRequest
class using the Artisan make:request
command, which does not need any special options:
php artisan make:request Article/StoreRequest
Since we can have more than one request class for one controller, it is good practice to create a separate folder for each controller.
A new app/Http/Requests/
folder was automatically created for us, followed by the Article/
subfolder defined by us. In the folder we find the generated file StoreRequest.php
and the content of which is as follows:
<?php
namespace App\Http\Requests\Article;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
The newly generated StoreRequest
class that inherits from FormRequest
class contains only these two methods:
authorize()
- Checks if the user is authorized to send the request. This is one of the places where we can place this verification. Another of them may be middleware, but we will show this in the next lessons.rules()
- Returns a field with set validation rules.
Since we don't deal with permissions (and users) yet, we can completely remove the authorize()
method. If it is not defined, this verification is automatically considered successful. But what interests us more is the rules()
method, which we fill with rules from the store()
method of our controller. So it will look like this:
/**
* Return validation rules for the form responsible for creating articles.
*
* @return array
*/
public function rules()
{
return [
'title' => ['required', 'min:3', 'max:80'],
'url' => ['required', 'min:3', 'max:80', 'unique:articles,url'],
'description' => ['required', 'min:25', 'max:255'],
'content' => ['required', 'min:50'],
];
}