Creating a basic controller in laravel

Model-View-Controller (MVC) patterns are very popular in PHP frameworks. In this recipe,
we’ll create a simple controller that extends another base controller.

Getting ready

To start, we just need a standard Laravel installation.

How to do it…

To complete this recipe, follow these steps:
1. In the app/controllers directory, create a file named UsersController.php
and type the following code in to it:
class UsersController extends BaseController {
public function actionIndex()
return “This is a User Index page”;
public function actionAbout()
return “This is a User About page”;

2. Then, in the routes.php file, add the following lines:
Route::get(‘users’, ‘UsersController@actionIndex’);
Route::get(‘users/about’, ‘UsersController@actionAbout’);
3. Test the controller by going to http://your-server/users and
http://your-server/users/about, where your-server is the
URL to your app.

How its Works…

In our User controller (and pretty much in any other controller that we create), we start by
extending the base controller. If we look in the BaseController.php file, we see only one
method, the setupLayout() method, which is used for our layout views. The base controller
could also be used if there’s some code that we want to run on every page of the site.

Back in the User controller, we define two methods for our Index and About page, with each
method prefixed by action. For our purposes, we’re just returning a single string, but this would
be where all of our controller logic would go and where we would set the view to be displayed.
So that Laravel is able to parse the URL and determine which controller and methods to use,
we need to register the routes in our routes file. Now, in our browser, when we go to /users
(or /users/index), we’ll be taken to our Index page, while /users/about will take us to
our About page.


Leave a Reply

Your email address will not be published. Required fields are marked *