Controllers in Laravel 5.3

As we have seen in previous example of passing arguments to view, the route file actually looks ugly and hard to read. As we know Laravel use MVC (Model View Controller) , it is best to use a controller for that example. In short it is best to include any logic in controller. A controller may have one or more than one action.

Lets understand controller with an example. To create an boilerplate code for an controller we have to pass following command in root of the project directory.

php artisan make:controller UsersController

The above command will create UsersController.php file under app/Http/Controllers/ directory with the required boilerplate.

Now we will delete the users route and replace this with following code:

By saving the file and running laravel development server, we will see the same output. This time logic are placed inside controller file. This not only make code readable, but very easy to understand. Consider scenario where there are lot of users related function such as create, delete etc. All logic will be placed inside this controller file under different function/method. And we will call required function in the routes file. Example is given below.

Route::post('users', 'UsersController@create');

Route::delete('users', 'UsersController@delete');