Controllers

Updated on Jul 11, 2024

We have mentioned Controllers several times throughout this tutorial, and now we will actually look at how to create them. Since Controllers are just as important as Routes, we put them in the same part of our tutorial. While Routes define how the application responds to HTTP and URL requests and are its entry points for those requests, Controllers contain the logic to handle the requests. They often work together and collectively comprise how your application handles requests. Without them, your application would not have any functionality whatsoever. Because of that, it is essential to know how to create Routes and Controllers. 

This Section Includes:

section

Creating Controllers

Controllers are typically stored in the app/Http/Controllers directory of your Laravel application. A new installation will have a single file within it named Controller.php. Any new controller you create will have its own file in that directory. As for how to create controllers, you can use this command.

php artisan make:controller

Let’s create a Controller to fetch data, interact with a Model, and return a View as a task management application. That will showcase a different code and functionalities. To start, we need to create the model.

php artisan make:model Task -m

That will create the Task Model and a migration file. Before we edit the Model, we should update the migration file with the proper code. It will add functionalities for creating and rolling back a tasks table in the application's database. It will also create all the necessary columns in that database for the application to interact with. It is located in database/migrations, and the file's name will be time-stamped.

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTasksTable extends Migration
{
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description')->nullable();
            $table->unsignedBigInteger('category_id');
            $table->timestamps();
            $table->foreign('category_id')->references('id')->on('categories');
        });
    }
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

Let's break it down.

  • The use statements all import classes and facades from the necessary providers, which are needed for the Migration and, therefore, the application;
  • The class CreateTasksTable extends Migration line tells Laravel that this is a migration file;
  • public function up() and everything until public function down() works towards creating the necessary table and columns within it in the application's database;
  • Finally, the public function down() method is needed to allow the Migration to be rolled back in case of any issues.

We must run the migration to create the tables, columns, and functionality.

php artisan migrate

Once the process is done, it is time to create the Controller. Run this command.

php artisan make:controller TaskController

That will create the TaskController file in app/Http/Controllers. Place this code in it.

<?php
namespace App\Http\Controllers;
use App\Models\Task;
use App\Models\Category;
use Illuminate\Http\Request;
class TaskController extends Controller
{
    public function index()
    {
        $tasks = Task::all();
        return view('tasks.index', compact('tasks'));
    }
    public function show($id)
    {
        $task = Task::find($id);
        return view('tasks.show', compact('task'));
    }
    public function create()
    {
        $categories = Category::all();
        return view('tasks.create', compact('categories'));
    }
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'description' => 'nullable',
            'category_id' => 'required|exists:categories,id',
        ]);
        Task::create($request->all());
        return redirect()->route('tasks.index');
    }
}

This code contains all the methods necessary to handle the actions the application can perform:

  • Displaying all tasks or a specific one;
  • Displaying a form to create a new task;
  • Storing a new task.

The methods interact with the Task and Category models to work with the database, which they then send to the View so the user can see it on their screen.

The code starts the same as the previous one we used. The namespace, use, and class statements do the same thing. Then, you have the public function functions and their methods.

  • The index method handles showing all tasks in the View;
  • The show method afterward handles displaying a specific task by finding its ID and returning the View;
  • Similarly, the create method will display a form to create a new task;
  • Finally, the store method will store the new task. As you can see, it requires a name and an ID, but a description is unnecessary. The ID is the task number. Finally, it shows the user the necessary view when the task is created.

The last step is defining the routes for the task in routes/web.php. We will use this code block.

use App\Http\Controllers\TaskController;
Route::get('/tasks', [TaskController::class, 'index'])->name('tasks.index');
Route::get('/tasks/{id}', [TaskController::class, 'show'])->name('tasks.show');
Route::get('/tasks/create', [TaskController::class, 'create'])->name('tasks.create');
Route::post('/tasks', [TaskController::class, 'store'])->name('tasks.store');

As you can see, this sets up all the routes necessary for viewing all tasks, a specific task, displaying the task creation form, or storing a new task. We will not discuss creating a View for the application since we wanted to show you how to create a more complex Controller. Views are discussed in a different part of this tutorial.

We hope that Controller creation is more clear after this example. As you can see, it is the brain behind your application.

Section

Types of Controllers

In Laravel, there are two types of Controllers: Resource and Routing controllers. Let's take a look at each one and describe them! If you are unsure what a Controller is, please refer to the Important Terminology section of our tutorial.

Resource Controllers

Firstly, we will begin with Resource Controllers. This type of Controller is most commonly used for an application's more standard operations. For instance, resource controllers handle CRUD operations (Create, Read, Update, and Delete). Since CRUD operations are at the base of many web applications, it makes sense that the Resource Controller would handle them. Below are the other operations that the Resource Controller can handle.

  • RESTful Routing -  Because Resource Controllers follow RESTful conventions, they are used for mapping HTTP verbs (GET, POST, PUT/PATCH, DELETE) to controller methods;
  • Automatic Route Binding - Laravel automatically generates the corresponding routes for all standard CRUD operations when a Resource Controller is defined. That has helped keep Laravel applications' structure consistent;
  • Named Routes - Resource Controllers can also be used to create named routes. That can help with easy referencing in your application;

As with all controllers, Resource Controllers utilize a set of methods. We have outlined them below for you.

  • index - Display a listing of the resource;
  • create - Show the form for creating a new resource;
  • store - Store a newly created resource in storage;
  • show - Display the specified resource;
  • edit - Show the form for editing the specified resource;
  • update - Update the specified resource in storage;
  • destroy -  Remove the specified resource from storage.

You can create a Controller to be specifically a Resource one by adding --resource at the end of your command.

php artisan make:controller ExampleName --resource

Routing Controllers

Next are Routing Controllers. These Controllers are used for more flexible and custom routes. They are used to customize your application in a way that Resource Controllers cannot. For instance, they allow for your application to break out of the CRUD paradigm. Or give you greater control over how the paradigm functions. Below, we will list how a Routing Controller differs from a Resource one.

  • Your Own Rules - Routing Controllers allow you to write your own rules of how the controllers function;
  • Manual Routes - With these Controllers, you can specify how URLs are mapped within your application. While Laravel does typically make its own routes whenever necessary, you can manually specify the routes for these Controllers in the web.php and api.php files to allow yourself more flexibility;
  • Specific Methods - Finally, to round off the flexibility of Routing Controllers, you can create your own methods, with their own names, and map them to specific actions that are not part of the typical CRUD system. Not only that, but you don't even have to follow the typical index, store, and so on methods. Make your own, customize as much as you want.

The best part is that creating such a Controller is as easy as making any other. The command is the one we have mentioned before in our commands section.

php artisan make:controller YourControllerName

That will create the necessary file in app/Http/Controllers where you can define its methods. You can use the typical ones from above or write your own ones. Just remember to create them first and then define the routes in the necessary files. Such flexibility is amazing if you are looking for a more customizable application. If you are looking for something more straightforward, though, don't be afraid to use Resource Controllers. They are the perfect introduction for beginners.

On this page...