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:
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.
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:
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 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.
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.
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.
As with all controllers, Resource Controllers utilize a set of methods. We have outlined them below for you.
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
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.
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.