Introduction to Laravel Controllers
Your whole application can be created just by using Closures in routes.php file, it would become messy but will be doable. What if you can possibly organize your whole process with the help of Controller classes? Let’s see how. Controllers are capable of the group within one class, all the associated logics of request handling. Directory app/Http/Controllers is responsible to store controllers. In the MVC framework, ‘C’ stands for Controller that acts as directing traffic amid Views and Models. In this topic, we are going to learn about Laravel Controllers.
List of Laravel Controllers
Here is the List Controllers mention below
1. Basic Controllers
Below you can have a look at a basic example of the controller class. You may notice here that ‘MyController’ extends ‘Controller’. Here ‘Controller’ is the base class. Base class ‘Controller’ provides methods like ‘middleware’, ‘dispatch’ and ‘validate’ methods which makes 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 route URI matches with a specific request, then the method ‘show’ on class ‘MyController’ gets executed and parameters specified in route get assigned to the method as well.
Some extra cherries for you:
- There’s no need to mention the full namespace for the controller as ‘RouteServiceProvider’ automatically loads in route group which has namespace contained in it, all the route files. You simply 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 will be able to do so by placing 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, there’s just need to create the controller and you can leave 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 route can be registered for all methods in routes.php file.
Let’s take an 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 command. Let’s look at the Artisan command ‘make: controller’ quickly in order 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 itself many routes that can handle numerous actions. This controller is going to have specific methods for each available action. It will also include the notes which will inform you about the URIs and HTTP verbs that are being handled.
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 just 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 be responding to ‘users’, which is root/base URI being handled by Controller.
An action with multiple words can be accessed by 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 will 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 methods of your controller. 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 one 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 be considered in the development of an application. Laravel provides security by its inbuilt application security.
- Artisan: Artisan helps in performing repetitive tasks without having them to perform manually by developers. These can be used to create the database structure, code, a migration so as to make it 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 which will enable you to create your very own controller for your application, which will be secure and powerful at the same time. You may also look at the following article to learn more –
5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses