CRUD Operations In Laravel PHP Framework


Today we learn CRUD operations in laravel. CRUD (Create, Read, Update, Delete) This is very necessary for any project. stands as a basic requirement for any Laravel project. new developers must first learn simple CRUD operations in laravel as they are fundamentals of any Laravel application.

There are many CRUD generator packages of Laravel available on GitHub, any website, etc. But if you haven’t any basic knowledge of laravel about how it works, it would be of no use to you. You can use these packages you know how to work with CRUD operation in laravel.

in this tutorial, we will demonstrate simple Laravel CRUD operations step by step including record listing, record inserting, record updating, and record deleting.

[CRUD] Operations In Laravel PHP Framework - Step By Step
Install Laravel

First of all, we need to get a fresh laravel  version (laravel) application using bellow command because we are going from scratch, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Laravel CRUD Database Configuration

Using MySQL, the database configuration variables are already set up in .env and database.php file. But if use other databases 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>
Create Table

After successfully configuring the database, now we will create 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 the 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 setup table into the database.

Migration With Create Model Or Controller

Now create the migration with model and controller of a specific table by just entering the following given cmd.

php artisan make:model Task -mcr

Setup Model

Now open the task model and paste the following array in task.php file.

protected $fillable = [ 'title', 'description'];
Controller

After successfully setting up 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()
public function index()
{
    $tasks = Task::all();
    return view('tasks.index',compact('tasks',$tasks));
}
 // Task Controller create()
public function create()
{
    return view('tasks.create');
}
// Task Controller store()
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 name create.blade.php, edit.blade.php, index.blade.php, and show.blade.php. Use Bootstrap 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.blade.php

@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.blade.php

@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', '[email protected]')->name('home');
Route::get('/create','[email protected]');
Route::get('/task', '[email protected]');
Route::get('/edit/task/{id}','[email protected]');
Route::post('/edit/task/{id}','[email protected]');
Route::delete('/delete/task/{id}','[email protected]');

So in this article, I have demonstrated in detail how to create 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.


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close