Laravel Controllers

Controllers are the most important feature in MVC architecture. In MVC, 'C' stands for controller.

When we create the controller using artisan command, it'll be saved under app/Http/Controllers directory.

# Basic Controllers

Controller can be created by executing the following artisan command -

php artisan make:controller controller_name

We'll create controller i.e UserController using artisan command.

php artisan make:controller UserController

it'll be created under app/Http/Controllers/ directory.

app/Http/Controllers/UserController.php

<?php 
namespace AppHttpControllers;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRoute;

class UserController extends Controller 
 {
  // Do Stuff
 }

# Resource Controllers

Laravel resource controller makes it easier to create CRUD application. when we create an application we need to perform CRUD (Create, Read, Update, Delete) operation. Laravel makes this job easy for us and automatically provide all the methods in resource controller.

To create the resource controller, we will first delete the UserController.php from the project, which we have created in the previous step.

Type below artisan command to generate resource controller.

php artisan make:controller UserController --resource

<?php 
namespace AppHttpControllers;
use IlluminateHttpRequest;

class UserController extends Controller 
 {
   public function index()
   {
      // Display a listing of the resource.
   }
   public function create()
   {
      // Show the form for creating a new resource.
   }
   public function store(Request $request)
   {
      // Store a newly created resource in storage.
   }
   public function show($id)
   {
      // Display the specified resource.
   }
   public function edit($id)
   {
      // Show the form for editing the specified resource.
   }
   public function update(Request $request, $id)
   {
      // Update the specified resource in storage.
   }
   public function destroy($id)
   {
      // Remove the specified resource from storage.
   }
}

The above code contains the functions which are used to perform the various operations on the resources such as:

create(): It is used to show the form for creating a new resource.

store(): It is used to store a newly created resource in storage.

show(): It is used to display the specified resource.

edit(): It is used to editing the specified resource.

update(): It is used to update the specified resource in storage.

destroy(): It is used to remove the specified resource from storage.

Add the following line of code in app/Http/routes.php.

Route::resource('user', 'UserController');

We'll use artisan command to show a list of all the registered routes for the application.

php artisan route:list

Laravel Resource Routing