Blog Detail

26

Apr
Some Awesome Tips About Laravel Validation and Routing cover image

arrow_back Some Awesome Tips About Laravel Validation and Routing

Laravel is an open-source PHP framework devised to make developing web apps easier and faster through built-in features. These features are part of what makes Laravel so widely used by web developers.
Laravel includes a wide variety of beneficial validation rules that you can apply to data, even providing the ability to validate if values are unique in a given database table. Routing in Laravel allows you to route all your application requests to their appropriate controller. In this article, I will show you some laravel validation and routing tips. Hopefully, you can use them to supercharge your Laravel applications. Here we go!

Position placeholder in the validation messages

In Laravel 9 you can use the :position placeholder in the validation messages if you’re working with arrays.

This will output: “Please provide an amount for price #2”

class CreateProductRequest extends FormRequest
{
    public function rules(): array
    {
        return  [
            'title' => ['required', 'string'];
            'description' => ['nullable', 'sometimes', 'string'],
            'prices' => ['required', 'array'],
            'prices.*.amount' => ['required', 'numeric'],
            'prices.*.expired_at' => ['required', 'date'],
        ];
    }
    
    public function messages(): array
    {
        'prices.*.amount.required' => 'Please provide an amount for price #:position'
    }
}

New array validation rule required_array_keys

Laravel 8.82 adds a required_array_keys validation rule. The rule checks that all of the specified keys exist in an array.

Valid data that would pass the validation:

$data = [
    'baz' => [
        'foo' => 'bar',
        'fee' => 'faa',
        'laa' => 'lee'
    ],
];

$rules = [
    'baz' => [
        'array',
        'required_array_keys:foo,fee,laa',
    ],
];

$validator = Validator::make($data, $rules);
$validator->passes(); // true

Invalid data that would fail the validation:

$data = [
    'baz' => [
        'foo' => 'bar',
        'fee' => 'faa',
    ],
];

$rules = [
    'baz' => [
        'array',
        'required_array_keys:foo,fee,laa',
    ],
];

$validator = Validator::make($data, $rules);
$validator->passes(); // false

Route resources grouping

If your routes have a lot of resource controllers, you can group them and call one Route::resources() instead of many single Route::resource() statements.

Route::resources([
    'photos' => PhotoController::class,
    'posts' => PostController::class,
]);

Custom route bindings

Did you know you can define custom route bindings in Laravel?

In this example, I need to resolve a portfolio by slug. But the slug is not unique, because multiple users can have a portfolio named Foo. So I define how Laravel should resolve them from a route parameter

class RouteServiceProvider extends ServiceProvider
{
    public const HOME = '/dashboard';
    
    public function boot()
    {
        Route::bind('portfolio', function (string $slug) {
            return Portfolio::query()
                ->whereBelongsto(request()->user())
                ->whereSlug($slug)
                ->firstOrFail();
        });
    }
}
Route::get('portfolios/{portfolio}', function (Portfolio $portfolio) {
    /*
     * The $portfolio will be the result of the query defined in the RouteServiceProvider
     */
})

Mac validation rule

New mac_address validation rule added in Laravel 8.77

$trans = $this->getIlluminateArrayTranslator();
$validator = new Validator($trans, ['mac' => '01-23-45-67-89-ab'], ['mac' => 'mac_address']);
$this->assertTrue($validator->passes());

Validate email with TLD domain required

By default, the email validation rule will accept an email without a TLD domain (ie: taylor@laravel, povilas@ldaily)

But if you want to make sure the email must have a TLD domain (ie: taylor@laravel.com, povilas@ldaily.com), use the email:filter rule.

[
    'email' => 'required|email', // before
    'email' => 'required|email:filter', // after
],

Route view

You can use Route::view($uri , $bladePage) to return a view directly, without having to use the controller function.

//this will return home.blade.php view
Route::view('/home', 'home');

These are some useful tips and tricks related to laravel Validation & Routing. I hope that by utilizing these tips, you will improve your code execution and usability. If you love them, then please share your views on our Facebook, Twitter, or Instagram.

Follow us:

Published at : 26-04-2022

Author : Rizwan Aslam
AUTHOR
Rizwan Aslam

I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.

Launch your project

Launch project