Updated July 5, 2023
Introduction to Laravel Controllers
Your whole application can be created just by using Closures in the routes.php file; it would become messy but will be doable. What if you can organize your entire process with the help of Controller classes? Let’s see how. Controllers are capable of the group within one class all the associated logic of request handling. The directory app/Http/Controllers is responsible for storing controllers. In the MVC framework, ‘C’ stands for Controller, which directs traffic amid Views and Models. In this topic, we are going to learn about Laravel Controllers.
List of Laravel Controllers
Here is the List of Controllers mentioned below
1. Basic Controllers
Below you can look at a basic example of the controller class. You may notice here that ‘MyController’ extends ‘Controller.’ Here ‘Controller’ is the base class. The base class ‘Controller’ provides methods like ‘middleware,’ ‘dispatch,’ and ‘validate’ methods, making it convenient. You can use middleware to assign it to the Controller’s Route or in your Controller’s constructor.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
class MyController extends Controller
{
/**
* Show profile
*
*/
public function show($id)
{
return view('user.profile', ['user' => User::foundOrLost($id)]);
}
}
The Route to MyController can be defined like this:
Route::get('user/{id}', 'MyController@show');
Assigning middleware in route files:
Route::get('profile', 'MyController@show')->middleware('auth');
When the Route URI matches a specific request, the method ‘show’ on the class ‘MyController’ gets executed, and parameters specified in Route get assigned to the method.
Some extra cherries for you:
- There’s no need to mention the entire namespace for the Controller as ‘RouteServiceProvider’ automatically loads in the route group, which has a namespace contained in it, all the route files. You need to specify that portion of the name which will appear after App\Http\Controllers.
- If you wish to define the single-action controller, you can place a single method’__invoke’ on your Controller.
2. Resource Controllers
While creating an application, we require performing CRUD (Create, Read, Update, Delete) operations. With Laravel resource controllers, you must make the Controller and leave the rest on Laravel. The Laravel resource route will allot the CRUD operation routes to the Controller, that too just with one line of coding. A single course can be registered for all methods in the routes.php file.
For example, suppose for your application, you want to make a controller which handles all the incoming HTTP requests relative to ‘images’ stored. This will be swiftly done with the help of Artisan’s command. Let’s look at the Artisan command’ make: controller’ quickly to create one similar Controller as follows:
php artisan make:controller ImageController --resource
A controller will be generated at the app/Http/Controllers/ImageController.php by the above command. This Controller will consist of a method dedicated to each resource operation available.
Now, you can declare a route to handle various actions like this:
Route::resource('images', 'ImageController');
This declaration of Route creates many routes that can take numerous actions. This Controller is going to have specific methods for each available action. It will also include notes informing you about handling the URIs and HTTP verbs.
If you want to register more than one resource controller in one go, you can do so with the help of an array, as shown below:
Route::resources([
'images' => 'ImageController',
'posts' => 'PostController'
]);
Table of Actions
Verb | URI / Path | Action Event | Route Name |
POST | /images | store | images.store |
GET | /images | index | images.index |
GET | /images/create | create | images.create |
GET | /images/{image} | show | images.show |
PUT/PATCH | /images/{image} | update | images.update |
GET | /images/{image}/edit | edit | images.edit |
DELETE | /images/{image} | destroy | images.destroy |
3. Implicit Controllers
With the help of these controllers, you can handle every action just by defining one Route. You have to define Route first by using Route:: Controller like this:
Route::controller('users', 'MyController');
Here, two arguments are being passed to the Controller.
- Base URI
- Controller’s class name
Now you have to add methods to ‘MyController’ with HTTP verb prefixed to them.
class MyController extends Controller {
public function getIndex()
{
//
}
public function anyLogin()
{
//
}
public function postProfile()
{
//
}
}
The methods’ index’ will respond to ‘users,’ which is the root/base URI being handled by Controller.
An action with multiple words can be accessed using ‘dash’ in URI. Refer to below controller action as an example:
public function getAdminProfile() {}
This controller action in MyController will respond to URI’ users/admin-profile’.
4. Dependency Injection and Controllers
Dependencies Injection makes your web applications easier to test and maintain.
i. Constructor Injection
Laravel manages class dependencies and resolves all controllers. Your Controller might need dependencies in the constructor; with Laravel, you can type-hint almost any of these dependencies. Laravel service controller will resolve all the dependencies automatically and inject them into the instance of the Controller.
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class MyController extends Controller
{
/**
* The user repository instance.
*/
protected $users;
/**
* Create a new controller instance.
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
$this->users = $users;
}
}
ii. Method Injection
Apart from injecting dependencies into the constructor, you can also type-hint them into your Controller’s methods. For example, instance Illuminate\Http\Request can be injected into the Controller’s method as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MyController extends Controller
{
/**
* Store a new user.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$name = $request->name;
//
}
}
Features of Laravel Controllers
Below are a few features of the Laravel Controller:
- MVC Support: Laravel is backed by MVC Architecture. It makes the development fast as one user can work on logic while the other works on view. Multiple views are supported for a model without duplication, as business logic is separated from presentation logic.
- Authentication: Laravel has an inbuilt system for authentication; you only have to take care of other aspects like configuring views, models, and controllers.
- Security: Security is the foremost factor to consider in developing an application. Laravel provides security through its inbuilt application security.
- Artisan: Artisan helps perform repetitive tasks without having developers perform them manually. These can make the database structure, code, and migration manageable.
- Templates: With Laravel’s innovative and powerful template engine, developers can create dynamic web applications.
Recommended Articles
This is a guide to Laravel Controllers. Here we discuss a fair number of Laravel controller concepts that will enable you to create your very own Controller for your application, which will be secure and robust simultaneously. You may also look at the following article to learn more –