What is Controller
In MVC architectural pattern, the letter ‘C’ stands for Controller. It acts as a directing traffic between Views and Models. Controllers help you to organize the logic codes into classes.
How to create controller in Laravel
Go to Command Line from your Laravel project directory and write this command to create a new controller.
php artisan make:controller ControllerName
Suppose, you want to create a controller named UserController. Then you will have to write:
php artisan make:controller UserController
In Laravel, Controllers are stored in the app/Http/Controllers
directory.
Using a controller
Suppose, you want to show a list of registered users, show a page to edit user’s details, update the user’s details, delete the user and also more depending on what you need. To do all of these, in Laravel, you can create a controller and organize these tasks in different functions. Suppose, you created a controller called UserController. Then you organize these tasks like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
// Write codes to show user's list
}
public function edit(Request $request)
{
// Write codes to show user's detail edit page
}
public function update(Request $request)
{
// Write codes to edit user's detail
}
public function destroy()
{
// Write codes to delete a user
}
}