Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Creating controllers in Laravel

Wednesday, April 8th, 2015 by Servage

laravelLaravel is based on a variation of the MVC pattern. It stands for Model, View, Controller. The theory says that a system should encapsulate its underlying data logic in models (reflecting a database record, like a user or a post), while the application logic is placed in controllers (the response handler for a given request, like handling a login og submitting a post). Lastly views are the HTML (or other output format) representation needed to create the visuals.

Following this pattern in Laravel, you need to create controllers that are being executed based on a given request. That means you configure a route to use that controller. You can have multiple rules using the same controller if needed, which makes sense when you have similar functionality behind different URL endpoints.

Define a controller for a route

Below is an example of a GET request to the /my-test endpoint, which should execute the hello-method in the MyTest controller class. Notice how the @ between controller name and method name allows for a straightforward syntax in the rule configuration.

Route::get('/my-test', 'MyTestController@hello');

Now any request to that endpoint will trigger the desired controller to run. Let us define that controller class now.

Define a controller class

Below is the basic definition of a sample controller class with one method. In the new Laravel 5 system controllers are placed in the app/http/controllers folder.

class MyTestController extends BaseController
{
  public function hello()
  {
    // Your controller code here ...
  }
}

Notice how the action method is public. You can of course create multiple methods in here, including methods that should only be available inside the controller as protected or private methods.

Restfull controllers

Many use-cases follow the same pattern of making specific common actions available. For example a blog post administration system will likely have a posts controller which enables functionality like viewing posts, adding new posts, editing existing posts, and removing posts. These common actions add, edit, delete are also known from HTTP request verbs as GET, POST, PUT or DELETE. There is a common pattern called REST (or Restfull development) which emphasizes the use of such standard patterns to facilitate generic ways of producing code for easier understandability and quicker speed of development. Laravel supports REST and can let you build controllers with relevant methods easily.

Dependency injection

Nowadays Laravel has come to support dependency injection, which is a clever way of declaring required code in your controller classes. This way you can further simplify the definition of dependencies, and make them easier to grasp for other coders reviewing your code. You have the option to use dependency injection in two occasions in controllers. Consider the example below showing both constructor and method dependency injection:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class UserController extends Controller {

  /**
   * The post repository instance.
   */
  protected $posts;

  /**
   * Create a new controller instance.
   *
   * @param  PostRepository  $posts
   * @return void
   */
  public function __construct(PostRepository $posts)
  {
    $this->posts = $posts;
  }


  /**
   * Store a new post.
   *
   * @param  Request  $request
   * @return Response
   */
  public function view(Request $request)
  {
    $name = $request->input('name');
    
    // More code to handle the view-action here and return the response.
  }

}
?>

Constructer dependency injection allows you to declare required instances for all methods in the controller.

Method dependency injection allows you to declare required instances for a specific method together with the expected parameters passed along by the route.

 

Creating controllers in Laravel, 5.0 out of 5 based on 5 ratings
Categories: Guides & Tutorials

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.