Laravel 8.* using Backpack and validation of requests

Lyubomir Filipov
3 min readDec 24, 2020

--

In order to proceed you should have:
- Laravel installed + Backpack admin (teaching purposes)
- Tags CRUD created
- Articles CRUD created
- virtual host ready for you
- xampp setup or other web server
- composer installed

#STEP 1: Identify problem

Open tags page and try to create new item but leave all fields empty

If we try to submit we get the following error

Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 1048 Column ‘name’ cannot be null (SQL: insert into `tags` (`name`, `slug`, `updated_at`, `created_at`) values (?, ?, 2020–12–24 16:05:34, 2020–12–24 16:05:34))

Column cannot be null, this is expected because when we were creating the table we used

Schema::create(‘tags’, function (Blueprint $table) {
$table->id();
$table->string(‘name’)->unique();
$table->string(‘slug’)->unique();
$table->timestamps();
});

We did not specify that these columns are nullable and it is normal for them NOT to be nullable.

If we have a case where a column could be nullable we are doing this by specifying it — like we did with the images

Schema::table(‘articles’, function (Blueprint $table) {
$table->string(‘image’,255)->nullable();
});

#STEP 2: Add validation

In order to add validation we could do that using Requests file. Backpack is creating requests files for us.

More on Laravel 8.x and validation could be found here.

Requests are located in `App\Http\Requests` folder

We will update the rules() method in app/Http/Requests/TagRequest.php

public function rules()
{
return [
'name' => 'required|min:5|max:255',
'slug' => 'required|unique:tags'
];
}

All available rules could be found in here.

We have added a rule that name is required and it should have at least 5 chars and maximum up to 255 chars.
We have added a rule stating that slug is required as well but also we need to make sure that the slug is unique — we are stating that this should be valid against the tags table.

#STEP 3: Alter error messages

Error messages could be adjusted if we provide mapping for them in messages() method in app/Http/Requests/TagRequest.php

return [
'name.required' => 'Please provide valid name which is between 5 and 255 characters.',
'slug.required' => 'You should provide valid unique slug.',
'slug.unique' => 'The slug that you have provided has already been used by another tag.'
];

Adjusted code

Result of the changes

Error mapping is done in the following way: fieldName.Rule that’s why we have in our case name.required, slug.required and etc.

#STEP 4: Add error messages for Articles CRUD

Alter articles Request — app/Http/Requests/ArticleRequest.php

public function rules()
{
return [
'title' => 'required|min:5|max:255',
'content' => 'required'
];
}

Result

Video

--

--