CRUD (Create, Read, Update, Delete) stands as a basic requirement for any Laravel application. Being new to Laravel, developers must first learn simple CRUD operations as they are fundamentals of any Laravel application.
There are many CRUD generator packages of Laravel available on GitHub. But if you haven’t any basic knowledge about how it works, it would be of no use to you. You could only master these packages once you know how to work with CRUD manually on Laravel.
So in this tutorial, I will demonstrate simple Laravel CRUD operations step by step including record listing, record inserting, record updating, and record deleting.
Prerequisite
For the purpose of this tutorial, I assume that you have a Laravel application installed on a web server. My setup is:
-
Laravel 5.5
-
PHP 7.x
-
MySQL
For an optimized developer stack, I have installed my Laravel application on a Cloudways-managed server. You can also sign up for free Cloudways Web Hosting for PHP easily and can set up your application within a few minutes.
Laravel CRUD Database Configuration
Using Cloudways, the database configuration variables are already set up in .env and database.php file. But if you want to use another database then you could do so by changing its configuration in both files.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=<DATABASE_NAME>
DB_USERNAME=root
DB_PASSWORD=<DB_PASSWORD>
CRUD Operations in Laravel PHP Framework
Create Task Table
After successfully configuring the database, now we will move towards creating a task table. But before creating a task table, first, create the migration for a table by executing the following command:
php artisan make:migration create_tasks_table
And then update the following code into created migration file.
public function up()
{
Schema::create('tasks', function (Blueprint $table)
{
$table->increments('id');
$table->string('title');
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
* @return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
Now run the php
artisan migrate
command to set up a table in the database.
Migration with Create model or controller
Now create the migration with the model and controller of a specific table by just entering the following given command in the SSH terminal.
php artisan make:model Task -mcr
Setup Model
Now open the task model and paste the following array in the task.php file.
protected $fillable = [ 'title', 'description'];
Controller
After successfully setting up the model, now open the taskController.php file and change all the functions according to their function names like update store, edit, or destroy functions.
Task Controller index()
Paste the following code into index()
function.
public function index()
{
$tasks = Task::all();
return view('tasks.index',compact('tasks',$tasks));
}
Task Controller create()
Now copy the below code and paste it into create()
function.
public function create()
{
return view('tasks.create');
}
Task Controller store()
To insert data into the database, paste the following code into the store function.
public function store(Request $request)
{
// Validate
$request->validate([
'title' => 'required|min:3',
'description' => 'required',
]);
$task = Task::create(['title' => $request->title,'description' => $request->description]);
return redirect('/tasks/'.$task->id);
}
Task show()
public function show(Task $task)
{
return view('tasks.show',compact('task',$task));
}
Task Edit ()
public function edit(Task $task)
{
return view('tasks.edit',compact('task',$task));
}
Task Destroy()
public function destroy(Request $request, Task $task)
{
$task->delete();
$request->session()->flash('message', 'Successfully deleted the task!');
return redirect('tasks');
}
Create View Laravel - CRUD
To finalize the layout view of CRUD, create the view files with the names create.blade.php, edit.blade.php, index.blade.php, and show.blade.php. Use Twitter Bootstrap v4 for making layout views consistent.
Create.blade.php
@extends('layout.layout')
@section('content')
<h1>Add New Task</h1>
<hr>
<form action="/tasks" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Task Title</label>
<input type="text" class="form-control" id="taskTitle" name="title">
</div>
<div class="form-group">
<label for="description">Task Description</label>
<input type="text" class="form-control" id="taskDescription" name="description">
</div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
Show View
@extends('layout.layout')
@section('content')
<h1>Showing Task {{ $task->title }}</h1>
<div class="jumbotron text-center">
<p>
<strong>Task Title:</strong> {{ $task->title }}<br>
<strong>Description:</strong> {{ $task->description }}
</p>
</div>
@endsection
Edit View
@extends('layout.layout')
@section('content')
<h1>Edit Task</h1>
<hr>
<form action="{{url('tasks', [$task->id])}}" method="POST">
<input type="hidden" name="_method" value="PUT">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Task Title</label>
<input type="text" value="{{$task->title}}" class="form-control" id="taskTitle" name="title" >
</div>
<div class="form-group">
<label for="description">Task Description</label>
<input type="text" value="{{$task->description}}" class="form-control" id="taskDescription" name="description" >
</div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection
Delete
<form action="{{url('tasks', [$task->id])}}" method="POST">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="Delete"/>
</form>
Routes
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/create','TaskController@create');
Route::get('/task', 'TaskController@index');
Route::get('/edit/task/{id}','TaskController@edit');
Route::post('/edit/task/{id}','TaskController@update');
Route::delete('/delete/task/{id}','TaskController@destroy');
Conclusion
So in this article, I have demonstrated in detail how to develop a simple CRUD application in Laravel. It covers brief detail of all steps from the database to configuration to setting table migrations and creating views. Basically, CRUD holds very significant importance for any web developer as it completes the fundamental operations (Create, Read, and Update) of the apps.
Still, if you have any further questions about this article, feel free to share your comments in the below comments section.
Frequently Asked Questions(FAQs)
1. What is CRUD in Laravel?
CRUD stands for Create, Read, Update, and Delete, which are the basic operations involved in managing data in a database. In Laravel, these operations are seamlessly handled through its expressive and powerful ORM (Object-Relational Mapping) called Eloquent.
2. How do I perform a create operation in Laravel?
To create a new record in Laravel, you can use the create
method provided by Eloquent. This method allows you to assign values to the model's attributes and save them to the database with just a single line of code.
3. How can I retrieve data using Laravel's Eloquent ORM?
Laravel provides a variety of methods to fetch data from the database using Eloquent. The most common one is the get
method, which retrieves all records from a table. You can also use methods like find
retrieving a single record by its primary key or where
performing more complex queries.
4. What is the best way to update data in Laravel?
To update data in Laravel, you can use the update
method provided by Eloquent. This method allows you to specify the fields you want to update and their new values, making it a straightforward and efficient way to modify existing records.
5. How can I delete data in Laravel?
Laravel makes deleting records a breeze with the delete
method provided by Eloquent. You can delete a record by calling this method on an instance of the model or by using the destroy
method to delete multiple records based on their primary keys.
You may also like: