Controllers

Introduction

Controllers oranize your application logic into classes to which you can refer directly from routes and ajaxes. All controllers are stored inside app\Http\Controllers directory.

Each one controller should extend base Assely\Routing\Controller class in order to have access to addional properties like Illuminate\Http\Request.

Basics of controllers

First, you need to define route inside routes.php that points to the controller.

Route::get('posttype:post', 'PostController@index');

On the route match, the index method will be called on App\Http\Controllers\PostController class.

Next, we need a controller itself. Make new file with choosen class name and within App\Http\Controllers namespace.

<?php

namespace App\Http\Controllers;

use View;
use Post;
use Assely\Routing\Controller;

class PostController extends Controller
{
    /**
     * Display the specifed resource.
     *
     * @return void
     */
    public function show($id)
    {
        return View::make('post.single', ['post' => Post::find($id)]);
    }
}

Dependency Injection

Constructor Injection

Controllers are resolved by service container, so you are able to type-hint dependences and they will be automatically injected for you.

<?php

namespace App\Http\Controllers;

use View;
use Assely\Routing\Controller;
use App\Posttypes\Posts;

class PostController extends Controller
{
    /**
     * The posts instance.
     *
     * @var \App\Posttypes\Posts
     */
    protected $posts;

    /**
     * Construct controller.
     *
     * @param \App\Posttypes\Posts
     */
    public function __construct(Posts $posts) {
        $this->posts = $posts;
    }
}

Method Injection

You also can type-hint controller methods dependeces.

<?php

namespace App\Http\Controllers;

use View;
use Assely\Routing\Controller;
use App\Posttypes\Posts;
use App\Taxonomies\Categories;

class PostsController extends Controller
{
    /**
     * Display the specifed resource.
     *
     * @return void
     */
    public function show(
        Posts $post,
        Categories $categories,
        $categoryId
    ) {
        return View::make('posts.index', [
            'posts' => $posts->withTerm($categories->find($categoryId))
        ]);
    }
}

Controller Properties

Request

Inside controllers, which extends base controller, you have access to the request object.

<?php

namespace App\Http\Controllers;

class IndexController extends Controller
{
    /**
     * Display a list of resources.
     *
     * @return void
     */
    public function index()
    {
        // Dump request data
        dd($this->request->getMethod());
    }
}