Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a global validation for all requests in Laravel

I have to make validation of all of Date format only using class/request in Laravel. Can I make validation for all of the requests ? I think i do it in request.php abstract class.

like image 379
Pedram marandi Avatar asked Jan 31 '26 02:01

Pedram marandi


1 Answers

You may try something like this, at first create a BaseController like the following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class BaseController extends Controller {

    public function __construct(Request $request) {

        $this->request = $request;

        $this->hasValidDate();
    }

    protected function hasValidDate()
    {
        if($this->request->method() == 'POST') {
            // Adjust the rules as needed
            $this->validate($this->request, ['date' => 'required|date']);
        }
    }
}

Then in your other controllers, extend the BaseController like this example:

namespace App\Http\Controllers\User;

use App\Http\Controllers\BaseController;

class UserController extends BaseController {

    public function index()
    {
        // ...
    }

}

Hope you got the idea. Use it wisely.

like image 57
The Alpha Avatar answered Feb 01 '26 18:02

The Alpha