Simplify Your Code with Single Action Controllers in Laravel

In the Laravel framework, controllers play a crucial role in organizing and handling the logic of your web application. Typically, a controller contains multiple actions, each responsible for handling a specific HTTP request. However, there are cases where a controller may only need to handle a single action, leading to the concept of Single Action Controllers.

Single Action Controllers provide a streamlined approach to organizing your application's code by dedicating a controller class to a single action. This architectural pattern promotes separation of concerns, improves code readability, and simplifies the maintenance of your Laravel application. In this article, we will delve into an advanced example of Single Action Controllers in Laravel to demonstrate their practical usage.

Prerequisites

Before we proceed, make sure you have a working Laravel installation along with its dependencies. You can refer to the official Laravel documentation for installation instructions.

Understanding Single Action Controllers

Traditionally, a Laravel controller consists of multiple methods, each representing a specific action that handles an incoming request. However, in certain scenarios, a controller might only require a single action. For instance, consider a simple API endpoint that fetches user details. In such cases, creating a dedicated controller with just one method becomes more intuitive and cleaner.

Setting Up the Project

Let's begin by setting up a new Laravel project. Open your terminal and navigate to the desired directory. Run the following command to create a new

laravel new single-action-example


Once the project is created, navigate to its directory:

cd single-action-example

 

Creating the Single Action Controller

To begin, generate a new Single Action Controller class using the make:controller Artisan command. Open your terminal and run the following command:

php artisan make:controller ContactFormController --invokable

 

This will create the ContactFormController class in the app/Http/Controllers directory.

Next, open the ContactFormController.php file and replace the code with the following:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class ContactFormController extends Controller
{
    public function __invoke(Request $request)
    {
        // Validate the form data
        $validatedData = $request->validate([
            'name' => 'required',
            'email' => 'required|email',
            'message' => 'required',
        ]);

        // Send an email with the form data
        Mail::to('[email protected]')->send(new \App\Mail\ContactFormMail($validatedData));

        return response()->json(['message' => 'Contact form submitted successfully']);
    }
}

 

In this example, the __invoke method handles the form submission. It first validates the form data using Laravel's validation rules. If the data is valid, it sends an email with the form data using the Mail facade. Finally, it returns a JSON response to indicate the successful submission.

Registering the Route

Now, let's define a route to access our Single Action Controller. Open the routes/web.php file and add the following route definition:

use App\Http\Controllers\ContactFormController;

Route::post('/contact', ContactFormController::class);

 

In this example, we're using the post method to define a route that matches the /contact URI pattern. When this route is accessed, it will invoke the ContactFormController class.

Testing the Single Action Controller

To test the contact form submission, you can create a simple HTML form in your view. Here's an example of how you can create a form in a Blade template:

<form action="/contact" method="POST">
    @csrf
    <label for="name">Name:</label>
    <input type="text" name="name" id="name">

    <label for="email">Email:</label>
    <input type="email" name="email" id="email">

    <label for="message">Message:</label>
    <textarea name="message" id="message"></textarea>

    <button type="submit">Submit</button>
</form>

 

Make sure to include the CSRF token by adding @csrf within the form. This is necessary to protect your application from cross-site request forgery attacks.

When the form is submitted, the data will be sent to the /contact route, which will invoke the ContactFormController and handle the form submission.

Remember to handle the email sending logic appropriately in your application. In this example, we used the Mail facade to send the email, assuming you have configured Laravel's mail settings correctly.

Conclusion

Single Action Controllers in Laravel provide a clean and focused approach to handling specific actions within your application. By dedicating a controller class to a single action, you can improve code organization, readability, and maintainability. Whether it's fetching user details or processing a contact form submission, Single Action Controllers offer a flexible and efficient way to structure your Laravel application.

Thank you for reading until the end! If you found this article valuable, we would appreciate it if you could share it with others.