Laravel Controller
In this post we will learn about controllers. How we can create controllers and create routes using the controller methods.
To create new controller run below command.
php artisan make:controller TodoController
You can give any name to the controller. This will create a new controller class in App\Http\Controllers
namespace. The generated class will look like this.
namespace App\Http\Controllers;use Illuminate\Http\Request;class TodoController extends Controller
{}
We can write any number of methods inside a controller. You can crea
Single Action Controller
If you want to create controller that performs single action. There is a special controller you can create called single action controller. This controller will only contain single__invoke
method. This controller will look something like this.
namespace App\Http\Controllers;use Illuminate\Http\Request;class ShowTodoController extends Controller
{
/**
* Show the details for the given todo task.
*
* @param int $id
*/
public function __invoke($id)
{
// your code
}
Resource Controller
Most of the times we need to do CRUD for any model. In such cases we need to implement all the HTTP methods in controller. In such cases we use resource controller and we can do so by using below command.
php artisan make:controller TodoController --resource
This will generate todo controller with all the resource methods (index, create, store, show, edit, update, destroy). And it looks like this.
namespace App\Http\Controllers;use Illuminate\Http\Request;class TodoController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
} /**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
} /**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
} /**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
} /**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
And then we can create resource routes for this controller like this.
Route::resource('todos', 'TodoController');
Api Resource Controller
You can also create api resource controller easily using below command.
php artisan make:controller API/TodoController --api
Thats all on the topic controllers. Do check the laravel official page for more details here.