Scroll to top

Controllers in Laravel

In the basic routing tutorial we have learnt how to link routes to Closures. Closures are nice and quick way of writing of an application logic in a single file app/routes.php. But it’s better to organize this behavior using Controller class and take advantage of Laravel MVC framework features.

Controllers are typically stored in app/controllers.php directory, and this directory registered in the class map option of your composer.json file by default. Technically you can keep controllers in any place as long as composer knows how to autoload the controller class. By the way, Route declarations are not dependent on the location of the controller class file at all.

"autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ]
    },

Basic Controllers:

// app/controller/BlogController.php
 
class BlogController extends BaseController
{
 
       public function index()
       {
 
             // loading home page view
             return View::make('index');
 
        }
 
 
       public function showBlog($blogId)
       {
         
            // loading blog page view 
            return View::make('blog.page');
 
       }
 
}

All controllers should extend the BaseController class. The BaseController class extends frameworks Controllers class. Now let’s see how we can call this controller action in Routes file.

Route::get('blog/{id}', 'BlogController@showBlog');

Now let’s see how we can use namespaces in controllers when we have to create controllers with the same name. Just make sure to include the namespace within your route declaration.

// app/controllers/BlogController.php
 
namespace Blog\Controller;
 
use View;
use BaseController;
 
class BlogController extends BaseController
{
 
     public function showIndex()
    {
 
           return View::make('index');
 
     }
 
}

Let’s see how the namespaced controller can be routed to in Routes.php file.

// app/routes.php
 
Route::Get('index', 'Blog\Controller\BlogController@showIndex');

To generate a URL to a controller action, we can use URL::action or action helper method.

$url = URL::action('BlogController@showIndex');
 
$url = action('BlogController@showIndex');

We have already seen how to mention Filters in controllers routes. We can also specify Filters within controllers class also for certain methods.

// app/controllers/UserController.php
 
class UserController extends BaseController
{
 
     public function _construct()
    {
         $this->beforeFilter('auth', array('expect' => 'getLogin'));
    }
 
}

It says you can call getLogin action method only before auth filter, to access other methods you need to authenticate yourself first.

RESTful Controllers:

The only big difference between RESTful controllers and Basic controllers in the method naming convention.Method names in a RESTful controller should start with one of the HTTP verbs supported in laravel: “get”, “post”, “put”, “delete” or “patch”.The second part of the method name should start with a capital letter ex: getUsers, postCheckout.

Let’s create a new RESTful controller for our Blog application for the following actions.

  • View all list of blog posts
  • Creating a new blog post
  • View an individual blog post
  • Editing an individual blog post
  • Deleting a blog post

At high level we are going to create a controller called BlogController which would contain functionality for displaying and managing blog posts.

// app/controllers/BlogController.php
 
class BlogController extends BaseController
{ 
  
  // View all posts
  public function getIndex(){ ... }
   
 // Show an individual post
  public function getView($id){ ... }
  
  // Show the form for the creation of a new post
  public function getNew(){ ... }
  
  // Process submission of a new post
  public function postNew(){ ... }
  
  // Show a form editing a post
  public function getEdit($id){ ... }
  
  // Process submission of edited post
  public function postEdit($id){ ... }
  
  // Delete a specific post
  public function deletePost($id){ ... }
 
}

To call RESTful controllers methods we can use implicit Routing like below in app/routes.php  file

// app/routes.php
 
Route::controller('blog','BlogController');

Resource Controllers:

Resource Controllers are named that way because they deal with “resources” –  types of data that the application works with. For example if your application manages blogs these blogs could be considered as a type of resource. Resource controllers provide a consistent way of controlling CRUD operations on a resource.

Resource controllers follow a convention that is somewhat different from RESTful controllers yet it allows for creating of RESTful application structure. With Resource controllers each kind of operation on a resource such as creation, reading, updating and deleting. Resource controllers can handle ip to seven different actions on resource items.

  • index ( to show a list of the blog items)
  • create (to show a form for creation of a new blog item)
  • store ( to save a new blog item)
  • show (to show a specific blog post)
  • edit (to show a form for editing a blog post)
  • update (to process updating of a specific blog)
  • delete ( to delete a specific blog post)

We can create Resource controller using Artisan command.

php artisan controller:make SomeController
// app/controllers/blogController.php
 
class SomeController extends BaseController {
  
  // List the items of the resource
  public function index(){}
  
  // Show a form for creation of a new item of the resource
  public function create(){}
  
  // Save a new item of the resource
  public function store(){}
  
  // Show a specific item of the resource
  public function show($id){}
  
  // Show a form for editing an item of the resource
  public function edit($id){}
  
  // Process updating of an item of the resource
  public function update($id){}
  
  // Delete a specific item of the resource
  public function destroy($id){}
 
}

We can call a Resource controller in app/Routes.php file like below.

Route::resource('blog', 'BlogController');

Author avatar

admin

http://www.kodeinfo.com
Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Post a Comment

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