php

Laravel Resource Controllers

A resource controller is used in Laravel to perform CRUD operations easily. When you will create a resource controller using artisan command from the terminal then it will create all necessary methods inside the controller related to CRUD operations. It handles all HTTP requests for the application and requires a single line of code for CRUD routes. How you can create a resource controller and perform CRUD operations in Laravel are shown in this tutorial.

Prerequisite:

You will require a table in the database where the Laravel project is connected. You can create a table by migrate command or manually. I have used the users table in this tutorial to do the CRUD operation using the resource controller. The table is empty now. The structure of the table is shown below.

Create a Resource Controller:

Run the following command from the terminal to create the resource controller named UserController.

$ php artisan make:controller UserController --resource

If you open the controller from any editor you will see the following codes are already written in the controller. Seven methods are created inside the controller automatically for doing the CRUD operations.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController 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)
{
//
}
}

Resource Routes:

Add the following route for the UserController to create resource routes in the web.php file.

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

Now, run the following command from the terminal to check the current route list from the web.php file.

$ php artisan route:list

The following route information is generated for using the Route::resource() method. seven routes are created for calling seven methods. The uses of these routes are explained later in the next part of this tutorial.

Add the following lines at the beginning of the UserController.php file to import the User model, Hash service for hashing the password, and DB service for database operations.

use App\User;
use Hash;
use DB

Insert Record:

Modify the create() method of UserController with the following code. Here, an object of the User model is created to insert the new records. After assigning the mandatory values, the save() function is called to insert the new record into the students table.

public function create()
{
    $user = new User;

    $user->name = 'fahmida';
    $user->email = '[email protected]';
    $user->password = Hash::make('12345');
    try{
        $user->save();
        echo "Record is inserted";
    }
    catch (\Illuminate\Database\QueryException $e) {
        echo "Duplicate entry";
    }
}

The route to call the create() method of UserController is ‘users/create’. Run the following URL from the browser. If the record is inserted properly then the following output will appear.

http://localhost/laravelpro/public/users/create

Now, if the check the table from the database then you will get the following output.

View All Records:

Modify the index() method of UserController with the following code to retrieve all records from the users table and display the values of name and email.

public function index()
{
    $users = DB::select('select * from users');
    foreach($users as $user)
    {
        echo "Name: $user->name";
        echo "<br/>Email:$user->email";
    }
}

The route to call the index() method of UserController is ‘users’. Run the following URL from the browser.

http://localhost/laravelpro/public/users

The following output will appear.

Select Specific Record:

Modify the show() method of UserController with the following code to retrieve a record from the users table that contains 1 in the id field and display the value of the name.

public function show($id)
{
$user = DB::select('select * from users where id='.$id);
echo "The name of the user is ". $user[0]->name."<br/>";

}

The route to call the show() method of UserController is ‘users/{id}’. Run the following URL from the browser.

http://localhost/laravelpro/public/users/1

The following output will appear.

Update Record:

Two methods are mainly defined in the resource controller to update a database record. These are edit() and update() where the data of the record updates using any edited form. But no edit form is used here. So, only the edit() method is used to update a particular record of the students table. The current value of a particular record is printed before and after executing the update query.

public function edit($id)
{
    $user = DB::select('select * from users where id='.$id);
    echo "The current email of the user is ". $user[0]->email."<br/>";

    $email = '[email protected]';
    $user = DB::select("Update users set email='$email'where id=".$id);

    $user = DB::select('select * from users where id='.$id);
    echo "The email of the user after update is ". $user[0]->email;
}

The route to call the edit() method of UserController is ‘users/{id}/edit’. Run the following URL from the browser.

http://localhost/laravelpro/public/users/1/edit

The following output will appear.

Delete Record:

destroy() method is defined to delete any record from the table. But the route for deleting the record passes from another method. Here, I have used the show() method to create a hyperlink for deleting the record that is added at the end of the method.

public function show($id)
{
    $user = DB::select('select * from users where id='.$id);
    echo "The name of the user is ". $user[0]->name."<br/>";
    echo "<a href='".url('/')."/users/delete/".$id."'>Delete</a>";
}

Add the following code in the destroy() method to delete a particular record.

public function destroy($id)
{
    $user = DB::select('Delete from users where id='.$id);
    echo "The record is deleted";
}

Add the route in web.php file for calling the destroy() method.

Route::get('/users/delete/{id}', 'UserController@destroy');

After clicking the delete link the following output will appear.

Conclusion:

The use of the resource controller and the concept of the route resource are explained in detail in this tutorial by using a CRUD operation. I hope, it will help the new Laravel users to implement CRUD operation easily in their project.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.