All Articles

Laravel - Controller


Laravel controller. We can sort of think controller as the man in the middle, Controller receives a request, and ask the model for data, then present it to view to render on the screen..

In Laravel, controllers are stored at:

app/Http/Controllers

To generate a controller, let say we need one for Task, we can run:

php artisan make:controller TasksController

we can see a file named TasksController.php is created in the folder.

Now we can think that everything in the TasksController.php as equivalent of what’s stored in

Route::get('/tasks', function () {
   //Everything here
});

The result web.php file

<?php
Route::get('/', function () {
    $name = 'Aston' ;
    return view('welcome', compact('name'));
});

Route::get('/about', function () {
    return view('about');
});

Route::get('/tasks', 'TasksController@index');
Route::get('/tasks/{task}', 'TasksController@show');

and the result TasksController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Task;

class TasksController extends Controller
{
    public function index()
    {
        // $tasks = DB::table('tasks')->get(); 
        $tasks = Task::all();
        return view('tasks.index', compact('tasks'));
    }

    public function show($id){
    $task = Task::find($id);
    return view('tasks.show', compact('task'));
    }
}

Route Model Binding

In the TasksController.php file, we can do route model binding by doing

public function show(Task $task) {
  return view('tasks.show', compact('task'));
}

Note

The variable name has to match the name specified in web.php

Route::get('/tasks/{task}', 'TasksController@show');

Laravel will automatically match it, For example, if a user visits /tasks/1, thanks to route model binding, we can make Laravel automatically fetch the Task with an id of 1, and then inject that instance into your controller action. and this is pretty neat.

Back