DEV Community

Bijay Kumar Pun
Bijay Kumar Pun

Posted on

Laravel Controllers

Exceprts from the book Laravel: Up and Running by Matt Stauffer

Requests can come to applications not only via routes, but also cron jobs, Artisan command-line calls, queue jobs etc.
Controller's primary job is to capture the intent of an HTTP request and pass it on the rest of the application.

To create controller, run:
php artisan make:controller <controller-name>

This creates a controller class inside app/Http/Controllers/.
Additionally, the --resource option can be used to autogenerate methods for basic resource routes like create() and update()

Artisan's make namespace provides a lot tools for generating skeleton files for a variety of system files.

A common controller method example:

//SomeController.php
public function index(){
return view('tasks.index')
->with('tasks',Tasks:all());
}

The above can be used as:
//route/web.php
Route::get('/','SomeController@index');

This loads the resources/views/tasks/index.blade.php or resources/views/tasks/index.php and passes it a single variable named tasks which contains the result of the Task::all() Eloquent method.

Top comments (0)