Updated April 11, 2023
Introduction to Laravel Resource()
One of the primary tasks of any admin backend is to manipulate data or resources. A resource, will over a period in time, be Created, those resources will be read, over the course in time updated, and finally, when the need is over, deleted, perhaps. This entire process seems to be an arduous task. It is not always easy for the developer to create systems that will be capable of manipulating data in myriad ways. To make this task easy, resource controllers are created. These controllers overlook the entire process of creating, reading, updating, and deleting resources. In the LARAVEL parlance, they at=are called CRUD controllers and is also one of the reasons why the Laravel Framework is such a sought after platform. In this topic, we are going to learn about Laravel Resource().
It helps the developer create the most robust of functionalities in the shortest possible time. Its expressive query command line is user friendly. The Laravel framework is also highly scalable. This is why ecommerce developers look forward to working on it. Its diverse library makes the Laravel Framework a robust framework.
The Laravel framework, being open-sourced, allows third-party platforms and software to be integrated with its framework. This flexibility leads to the creation of numerous standalone functionalities.
The CRUD format is the easiest way to create a resource controller since it is a one-stop shop for users to update and manipulate data or resources. It is a kind of user form. In the laravel framework, the expressive command line structure ensures that the controller creation is smooth and hitch-free. In addition, the resource () query allows the developer to quickly source the content that needs to be pulled.
How is Resource() controller created in Laravel?
Let us now have a quick look as to how a resource controller is created:
In this example, we will be creating a form where one can add or create resources through a form.
This is the route to be used:
use App\Contact;
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'surname'=>'required',
'email_address'=>'required'
]);
$contact = new Contact([
'name' => $request->get('name'),
'surname' => $request->get('surname'),
'email_address' => $request->get('email_address'),
'job_designation’ => $request->get('job_designation’),
'company_name' => $request->get(‘company_name'),
'location' => $request->get('location')
]);
$contact->save();
return redirect('/contacts')->with('success', 'Contact added!');
}
public function create()
{
return view('contacts.create');
}
$ cd resources/views
$ touch base.blade.php
The below set of codes pertains to the design of the code in HTML. HTML or HyperText Markup Language is universally used to create designs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
@yield('main')
</div>
<script src="{{ asset('js/app.js') }}" type="text/js"></script>
</body>
</html>
$ mkdir contacts
$ cd contacts
$ touch create.blade.php
@extends('base')
@section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Add Contact</h1>
<div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div><br />
@endif
<form method="post" action="{{ route('contacts.store') }}">
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" class="form-control" name="surname"/>
</div>
<div class="form-group">
<label for="email_address">Email Address</label>
<input type="text" class="form-control" name="email_address"/>
</div>
<div class="form-group">
<label for="job_designation">Job Designation</label>
<input type="text" class="form-control" name="job_designation"/>
</div>
<div class="form-group">
<label for="company_name">Company Name</label>
<input type="text" class="form-control" name="company_name"/>
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" name="location"/>
</div>
<button type="submit" class="btnbtn-primary-outline">Add contact</button>
</form>
</div>
</div>
</div>
@endsection
Output:
Another example for Laravel Resources()
The below code involves the Creation of the resources:
Open: app/Http/Controllers/ContactController.php
Update the underneath code in index():
public function index()
{
$contact_details = Contact::all();
return view('contact_details.index', compact('contact_details'));
}
This set of codes will help create the Read method
Create: resources/views/contact_details.index.blade.php file
$ touch index.blade.php
Locate: resources/views/contact_details/index.blade.php and update the below code:
@extends('base')
@section('main')
<div class="row">
<div class="col-sm-12">
<h1 class="display-3">Contact Details</h1>
<table class="table table-striped">
<thead>
<tr>
<td>Name</td>
<td>Surname</td>
<td>Email Address</td>
<td>Job Designation</td>
<td>Company Name</td>
<td>Location</td>
<td colspan = 2>Actions</td>
</tr>
</thead>
<tbody>
@foreach($contact_details as $contact)
<tr>
<td>{{$contact->name}}</td>
<td>{{$contact->name}} {{$contact->surname}}</td>
<td>{{$contact->email_address}}</td>
<td>{{$contact->job_designation}}</td>
<td>{{$contact->company_name}}</td>
<td>{{$contact->location}}</td>
<td>
<a href="{{ route('contact_details.edit',$contact->name)}}" class="btnbtn-primary">Edit</a>
</td>
<td>
<form action="{{ route('contact_details.destroy', $contact->name)}}" method="post">
@csrf
@method('DELETE')
<button class="btnbtn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
@endforeach
</tbody>
</table>
<div>
</div>
@endsection
public function edit($id)
{
$contact = Contact::find($id);
return view('contact_deatils.edit', compact('contact'));
}
As we have seen in plenty in all the examples above, the edit function enables the user to update the form, and the database gets updated. The public function is a global function. It works without restrictions. It simply makes the entire content accessible to the other classes. Hence, it becomes imperative for any function that needs to be recalled in the quickest possible time; a public function is used.
The above set of codes will need to be added to
app/Http/Controllers/ContactController.php
public function edit($id)
{
$contact = Contact::find($id);
return view('contact_details.edit', compact('contact'));
}
The below code is the implementation of the update method:
public function update(Request $request, $id)
{
$request->validate([
'name'=>'required',
'surname'=>'required',
'email_address'=>'required'
]);
$contact = Contact::find($id);
$contact->name = $request->get('name');
$contact->surname = $request->get('surname');
$contact->email_address = $request->get('email_address');
$contact->job_designation = $request->get('job_designation');
$contact->company_name = $request->get('company_name');
$contact->location = $request->get('location');
$contact->save();
return redirect('/contact_details')->with('success', 'Contact successfully updated!');
}
And finally, this set of codes will help create the Delete method. As we have seen from the past, The CRUD controller is necessary to create smoothly functioning forms. This is relevant from the point of view of Laravel Resource () since the only thing we are dealing with here right now is with resources or data.
$ touch edit.blade.php will need to be created within:
resources/views/contacts/
@extends('base')
@section('main')
<div class="row">
<div class="col-sm-8 offset-sm-2">
<h1 class="display-3">Updating the contact</h1>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
<br />
@endif
<form method="post" action="{{ route('contact_details.update', $contact->id) }}">
@method('PATCH')
@csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" value={{ $contact->name }} />
</div>
<div class="form-group">
<label for="surname">Surname</label>
<input type="text" class="form-control" name="surname" value={{ $contact->surname }} />
</div>
<div class="form-group">
<label for="email_address">Email Address</label>
<input type="text" class="form-control" name="email_address" value={{ $contact->email_address }} />
</div>
<div class="form-group">
<label for="company_name">Company_name</label>
<input type="text" class="form-control" name="company_name" value={{ $contact->company_name }} />
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" name="location" value={{ $contact->location }} />
</div>
<div class="form-group">
<label for="job_designation">Job Designation</label>
<input type="text" class="form-control" name="job_designation" value={{ $contact->job_designation }} />
</div>
<button type="submit" class="btnbtn-primary">Update</button>
</form>
Now delete operation needs to be added to:
app/Http/Controllers/ContactController.php
public function destroy($id)
{
$contact = Contact::find($id);
$contact->delete();
return redirect('/contact_details')->with('success', 'Contact deletion successful!');
}
Locate: resources/views/contacts/index.blade.php and insert the following line of code:
<div class="col-sm-12">
@if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div>
@endif
</div>
Our controller is ready. We have been able to create a Create Read Update Delete or a CRUD controller to manipulate resources.
To create this form, one would need this. As seen in an earlier example, this is the HTML code that needs to be added to the above code.
<div>
<a style="margin: 19px;" href="{{ route('contact_deatils.create')}}" class="btnbtn-primary">Create New Contact</a>
</div>
<image>
Output:
The above example is an ideal illustration showcasing the usefulness of the controller.
Conclusion
The Laravel framework is one of the most user-friendly platforms in the world of software development. With Laravel resources, we can see how easily the CRUD functionality was created to manipulate data. CRUD allows one to modify resources. This is the reason why it finds much application in forms.
A CRUD controller is also necessary since forms are manipulated all the time. With a controller, one can easily maneuver through the maze of codes. In fact, one of the reasons why a CRUD controller is built through Laravel Resources () is to avoid the swim through the maze of coding language.
Recommended Articles
We hope that this EDUCBA information on “Laravel Resource()” was beneficial to you. You can view EDUCBA’s recommended articles for more information.