30 C
Jaipur
Sunday, October 18, 2020

Laravel Resource Controllers – Linux Hint

Must read

7 Best Free Case Converter Online|Title Capitalization Tool In 2020

While it’s possible to change case of a couple of sentences manually, doing the same for long paragraphs can be burdensome. This is where...

PopSockets Is Developing New MagSafe-Compatible Grips

With the launch of the newest iPhone 12 series, Apple revived the MagSafe charging system for its mobile devices. Although there is an array...

Tesla Will Roll out ‘Full Self-Driving’ Features to Limited Drivers next Week

To achieve the dream of making Tesla a fully autonomous vehicle, Musk’s automobile company often rolls out various automation features for their EVs. Now,...

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

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

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=”https://linuxhint.com/laravel_resource_controllers/”.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}’, [email protected]);

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.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

7 Best Free Case Converter Online|Title Capitalization Tool In 2020

While it’s possible to change case of a couple of sentences manually, doing the same for long paragraphs can be burdensome. This is where...

PopSockets Is Developing New MagSafe-Compatible Grips

With the launch of the newest iPhone 12 series, Apple revived the MagSafe charging system for its mobile devices. Although there is an array...

Tesla Will Roll out ‘Full Self-Driving’ Features to Limited Drivers next Week

To achieve the dream of making Tesla a fully autonomous vehicle, Musk’s automobile company often rolls out various automation features for their EVs. Now,...

Spider-Man: Miles Morales Has a Cute Spider-Cat Sidekick

Since Insomniac Games announced Spider-Man: Miles Morales video game for the next-gen consoles, we have heard about a few developments of the project. However,...