Laravel Requests

Marickian
By -
28 minute read
0
Understanding Laravel Requests

Understanding Laravel Requests

Introduction

Laravel is a popular PHP framework for developing web applications. One of the key components of Laravel is its handling of HTTP requests. In this article, we will explore what Laravel requests are, how to use them, and how to validate requests. We will also cover custom request classes and their role in request validation.

HTTP Requests in Laravel 11

Laravel's Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application. This class allows you to retrieve input, cookies, and files that were submitted with the request.

Accessing the Request

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your route closure or controller method. The incoming request instance will automatically be injected by the Laravel service container.


                <?php

                namespace App\Http\Controllers;

                use Illuminate\Http\Request;

                class UserController extends Controller
                {
                    /**
                     * Store a new user.
                     */
                    public function store(Request $request)
                    {
                        $name = $request->input('name');
                        // Store the user...
                        return redirect('/users');
                    }
                }
            

You can also type-hint the Illuminate\Http\Request class on a route closure:


                use Illuminate\Http\Request;

                Route::get('/', function (Request $request) {
                    // ...
                });
            

Request Path, Host, and Method

The Illuminate\Http\Request instance provides various methods for examining the incoming HTTP request. Here are a few important methods:

  • Retrieving the Request Path: The path method returns the request's path information.
    $uri = $request->path();
  • Inspecting the Request Path / Route: The is method allows you to verify that the incoming request path matches a given pattern.
    
                            if ($request->is('admin/*')) {
                                // ...
                            }
                        
  • Retrieving the Request Method: The method method returns the HTTP verb of the request.
    $method = $request->method();

Retrieving Input

Laravel provides several methods for retrieving input from the request:

  • Retrieving All Input Data: The all method returns all input data as an array.
    $input = $request->all();
  • Retrieving a Specific Input Value: The input method retrieves a specific input value.
    $name = $request->input('name');
  • Retrieving Input with a Default Value: You can provide a default value if the input is not present.
    $name = $request->input('name', 'Guest');
  • Retrieving Input as an Array: The only method returns only the specified input values.
    $input = $request->only(['username', 'password']);
  • Retrieving Input Except for a Specified Value: The except method returns all input values except for the specified ones.
    $input = $request->except(['password']);

Files

Laravel makes it easy to handle file uploads:

  • Retrieving Uploaded Files: The file method retrieves an uploaded file.
    $file = $request->file('photo');
  • Storing Uploaded Files: You can store uploaded files using the store method.
    $path = $request->file('photo')->store('photos');

Configuring Trusted Proxies and Hosts

Laravel allows you to configure trusted proxies and hosts to ensure your application handles requests securely.

Custom Request Classes

Custom request classes in Laravel are used to encapsulate the validation logic for a specific request. They are created using the Artisan command php artisan make:request. This command generates a new class in the app/Http/Requests directory.

For example, to create a custom request for updating a survey, you can run the following command:

php artisan make:request SurveyUpdateRequest

This will create a new file SurveyUpdateRequest.php in the app/Http/Requests directory.

Using Custom Request Classes

Once you have created the custom request class, you can define the validation rules and authorization logic within it. Here is an example of a custom request class:


                <?php

                namespace App\Http\Requests;

                use Illuminate\Foundation\Http\FormRequest;

                class SurveyUpdateRequest extends FormRequest
                {
                    /**
                     * Determine if the user is authorized to make this request.
                     */
                    public function authorize(): bool
                    {
                        return true; // Implement authorization logic here
                    }

                    /**
                     * Get the validation rules that apply to the request.
                     */
                    public function rules(): array
                    {
                        return [
                            'title' => 'required|string|max:255',
                            'description' => 'nullable|string',
                            'questions' => 'required|array',
                            'questions.*.text' => 'required|string',
                            'questions.*.type' => 'required|in:multiple_choice,text,checkbox',
                        ];
                    }
                }
            

Using Custom Request Classes in Controllers

To use the custom request class in your controller, you simply type-hint the custom request class in your controller method. Laravel will automatically validate the request using the rules defined in the custom request class:


                <?php

                namespace App\Http\Controllers;

                use App\Http\Requests\SurveyUpdateRequest;
                use App\Models\Survey;

                class SurveyController extends Controller
                {
                    /**
                     * Update an existing survey.
                     */
                    public function update(SurveyUpdateRequest $request, Survey $survey)
                    {
                        // The validated data is available via $request->validated()
                        $validatedData = $request->validated();

                        // Update the survey with the validated data
                        $survey->update($validatedData);

                        // Return a JSON response with the updated survey
                        return response()->json(['survey' => $survey]);
                    }
                }
            

Example: Uploading and Validating a File

Let's create an example where we handle file uploads and validate the file in the custom request class.

Creating the Custom Request

First, create the custom request using the Artisan command:

php artisan make:request PhotoUploadRequest

Defining Validation Rules in Custom Request

Next, define the validation rules in the PhotoUploadRequest class:


                <?php

                namespace App\Http\Requests;

                use Illuminate\Foundation\Http\FormRequest;

                class PhotoUploadRequest extends FormRequest
                {
                    /**
                     * Determine if the user is authorized to make this request.
                     */
                    public function authorize(): bool
                    {
                        return true; // Implement authorization logic here
                    }

                    /**
                     * Get the validation rules that apply to the request.
                     */
                    public function rules(): array
                    {
                        return [
                            'photo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
                        ];
                    }
                }
            

Using the Custom Request in the Controller

Now, use the custom request in the controller method to handle file uploads and validation:


                <?php

                namespace App\Http\Controllers;

                use App\Http\Requests\PhotoUploadRequest;
                use Illuminate\Support\Facades\Storage;

                class PhotoController extends Controller
                {
                    /**
                     * Handle the file upload.
                     */
                    public function upload(PhotoUploadRequest $request)
                    {
                        // The validated file is available via $request->validated()
                        $validatedData = $request->validated();

                        // Store the validated file
                        $path = $request->file('photo')->store('photos');

                        // Return a JSON response with the stored file path
                        return response()->json(['path' => $path], 201);
                    }
                }
            

Defining the Route

Finally, define the route that handles the file upload in the routes/web.php file:


                use App\Http\Controllers\PhotoController;

                Route::post('/upload', [PhotoController::class, 'upload']);
            

Handling Middleware in Requests

Middleware is used to filter HTTP requests entering your application. Laravel includes several middleware, such as authentication, CORS, and CSRF protection. You can also create custom middleware for your application.

Assigning Middleware to Routes

You can assign middleware to routes by specifying it in the route definition:


                Route::get('/profile', function () {
                    // Only authenticated users may enter...
                })->middleware('auth');
            

Assigning Middleware to Controllers

You can also assign middleware to controllers by using the middleware method in the controller's constructor:


                <?php

                namespace App\Http\Controllers;

                use Illuminate\Http\Request;

                class ProfileController extends Controller
                {
                    /**
                     * Instantiate a new controller instance.
                     */
                    public function __construct()
                    {
                        $this->middleware('auth');
                    }
                }
            

Dependency Injection in Requests

Laravel allows you to automatically resolve dependencies from the service container by type-hinting the dependencies in the controller's constructor or methods. This helps make the code more modular and testable.

Example: Dependency Injection in Controller


                <?php

                namespace App\Http\Controllers;

                use App\Services\UserService;
                use Illuminate\Http\Request;

                class UserController extends Controller
                {
                    protected $userService;

                    /**
                     * Create a new controller instance.
                     */
                    public function __construct(UserService $userService)
                    {
                        $this->userService = $userService;
                    }

                    /**
                     * Show a user's profile.
                     */
                    public function show(string $id)
                    {
                        $user = $this->userService->find($id);
                        return response()->json($user);
                    }
                }
            

Conclusion

Laravel requests are a powerful tool for handling HTTP requests in your application. The Illuminate\Http\Request class provides methods for accessing input data, handling file uploads, and configuring trusted proxies and hosts. Custom request classes allow you to encapsulate validation logic and keep your controllers clean and focused on handling business logic. By using Laravel's request handling capabilities, you can create robust and maintainable web applications.

For more detailed information, you can refer to the official Laravel documentation on HTTP requests.

Post a Comment

0Comments

Post a Comment (0)