Best way to write a controller in Laravel

Best way to write a controller in Laravel

What is Controller?

Instead of defining all of your request-handling logic as closures in your route files, you may wish to organize this behavior using “controller” classes. Controllers can group related request-handling logic into a single class. For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the app/Http/Controllers directory.

Create your project from the beginning.

Writing Controller

You may run the make:controller Artisan command. By default, all of the controllers for your application are stored in the app/Http/Controllers directory:

php artisan make:controller UserController

The above command will create a UserController file in app/Http/Controller directory.

There is another command that auto-generates functions for resource routes. if you don`t need any remaining function you can remove or run the above command, it depends on your requirements.

php artisan make:controller UserController --resource

Here are the functions the resource will provide you.

  • index()
  • create()
  • store()
  • show()
  • edit()
  • update()
  • destroy()

Create functions in your controller with came-case names eg: yourFunctionName()

Use Exception Handling

The Best way to use error exception handling for avoiding unwanted errors with your request, the most common is a 500 error response. Here is an example:

<?php

namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\View\View;
 
class UserController extends Controller
{

    try {
        
        public function show(string $id): View
        {
            return view('user.profile', [
                'user' => User::findOrFail($id)
            ]);
        }

    } catch (\Throwable $th) {
        
        //throw $th; 
        //  Your can throw response or send message to client
    }
}

Once you have written a controller class and method, you may define a route to the controller method like so:

use App\Http\Controllers\UserController;
 
Route::get('/user/{id}', [UserController::class, 'show']);

Leverage Laravel validation

Laravel provides a robust validation system. Use it to validate incoming data from requests before processing it.

public function store(Request $request): RedirectResponse
{
    $validated = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);
 
    // The blog post is valid...
 
    return redirect('/posts');
}

Don’t worry – all available validation rules are documented. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Use Laravel’s response helpers

Laravel provides various helper methods for generating HTTP responses. These include response(), redirect(), and specialized methods like json(), view(), and download().

Keep your methods concise

  • Aim to keep your controller methods concise and focused on their specific tasks.
  • If a method becomes too long or complex, consider extracting parts of the logic into separate methods or classes to improve readability and maintainability.

Remember, these guidelines are general best practices, and you may need to adapt them based on your specific project requirements.

Reference document from Laravel official documentation.