How to make a request in laravel?

Member

by denis , in category: PHP Frameworks , 10 days ago

How to make a request in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 9 days ago

@denis 

In Laravel, you can make a request by creating a new Request class using artisan command. Here's how you can make a request in Laravel:

  1. Open your terminal or command prompt and run the following command to create a new Request class:
1
php artisan make:request MyRequest


Replace MyRequest with the desired name of your Request class.

  1. This will create a new Request class inside the app/Http/Requests directory with the name MyRequest.php.
  2. Open the newly created Request class and define the validation rules you want to apply to the incoming request data. For example, you can define the rules in the rules method like this:
1
2
3
4
5
6
7
public function rules()
{
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email',
    ];
}


  1. Now you can use this custom Request class in your controller methods for validating the incoming request. For example, to use MyRequest class in a controller method, you can do the following:
1
2
3
4
5
6
use AppHttpRequestsMyRequest;

public function store(MyRequest $request)
{
    // Your logic here
}


The incoming request data will automatically be validated against the rules defined in the MyRequest class, and if the validation fails, Laravel will throw a ValidationException with the errors.