Latest Tips & Tricks About Laravel Validation & Laravel Routing
Tags: laravel, vue, programming, php
Published: 2022-04-27 07:26:33

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 <code>:position</code> 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 <code>required_array_keys</code> 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 <code>Route::resources()</code> instead of many single <code>Route::resource()</code> 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 <code>Foo</code>. 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 <code>email</code> without a TLD domain (ie: <code>taylor@laravel</code>, <code>povilas@ldaily</code>)

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

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

#### Route view
You can use <code>Route::view($uri , $bladePage)</code> 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 follow us for more laravel & Vue js related news.

**Follow Us on Twitter:** 

- [https://twitter.com/iamSumyyaKhan](https://twitter.com/iamSumyyaKhan)
- [https://twitter.com/CodeBrisk](https://twitter.com/CodeBrisk)