Laravel Controllers

So before starting on this article make sure you know the basic stuff of using routes and blade templates in Laravel. For very small applications you may not use the controllers but if you want to create big applications then you should use controllers as writing big applications in routes file will cause a messed up code.

In this article we will see how does the controller works in Laravel.

Suppose we want to see a list of users who registered, this what we do in our route.

Here User::all() is used to get all the records from users table. We will be displaying the record on users/index.blade.php. We need to pass the data to this view page. We can do this passing an array like array(“users” => $users) as a second parameter in View::make.

In index.blade.php we will show the user list like this

 

Here $users variable is the array index we passed in our route.

Now if you open http://localhost:8000/user/ you will see the list of users from users table.

user list
user list view

 

Now we will do the same thing using controller.

First we have to change our route to this

Now we have to create a UsersController in our controller directory. Laravel provide easy manner to generate controllers using php artisan.

For that open your CLI and write this command

php artisan controller:make UsersController

Make sure you are in your project directory before running this command.

You should see following response in your CLI.

Controller generated using php artisan command
Controller generated using php artisan command

Thats it! You can check your controller directory. You will notice UsersController is generated with all common functions already defined in the file.

UsersController generated
UsersController generated

We can do this by creating the controller manually in also. Make sure you write the correct syntax while doing this.

Also keep in mind that all controller extends BaseController.

In route UsersController@index indicates that we are going to use function index of UsersController class.

So now we have to write the code to show data in function index of UsersController as follows

You can also use .(dot) instead of / in View::make like this

return View::make(‘user.index’,array(“users” => $users));

Now if you go to http://localhost:8000/user/ you will see it works like before.

So main thing is we have reduced our line of codes in route file and moved our logical data handling part to separate controller.

There is another method to do this which is known as Resource Routing.

We will learn about it in next article.

Share this article: