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.

Laravel Resource Controllers Laravel

Create a Resource Controller:

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

$ php artisan make:controller UserController resource

Laravel Resource Controllers Laravel

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 AppHttpControllers;

use IlluminateHttpRequest;

class UserController extends Controller

{

/**


* Display a listing of the resource.


*


* @return IlluminateHttpResponse


*/


public function index()

{

//

}

/**


* Show the form for creating a new resource.


*


* @return IlluminateHttpResponse


*/


public function create()

{

//

}

/**


* Store a newly created resource in storage.


*


* @param IlluminateHttpRequest $request


* @return IlluminateHttpResponse


*/


public function store(Request $request)

{

//

}

/**


* Display the specified resource.


*


* @param int $id


* @return IlluminateHttpResponse


*/


public function show($id)

{

//

}

/**


* Show the form for editing the specified resource.


*


* @param int $id


* @return IlluminateHttpResponse


*/


public function edit($id)

{

//

}

/**


* Update the specified resource in storage.


*


* @param IlluminateHttpRequest $request


* @param int $id


* @return IlluminateHttpResponse


*/


public function update(Request $request, $id)

{

//

}

/**


* Remove the specified resource from storage.


*


* @param int $id


* @return IlluminateHttpResponse


*/


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.

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.

Laravel Resource Controllers Laravel

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 AppUser;

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 (IlluminateDatabaseQueryException $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

Laravel Resource Controllers Laravel

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

Laravel Resource Controllers Laravel

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
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.

Laravel Resource Controllers Laravel

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.
;

}

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.

Laravel Resource Controllers Laravel

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.
;

    $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.

Laravel Resource Controllers Laravel

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.
;


    echo “<a href='".url(‘/’).“https://linuxhint.com/users/delete/”.$id.“‘>Delete“;

}

Laravel Resource Controllers Laravel

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.

Laravel Resource Controllers Laravel

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

Laravel Resource Controllers Laravel

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.