New Tutorials:   JAVASCRIPT    SASS/SCSS    PL/SQL  
CLOSE
   PHP  Laravel  
   Technology    Programming

CRUD Operations in Laravel PHP Framework

         
 NOVEMBER 19, 2018   by iamabhishek

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 optimized developer stack, I have installed my Laravel application on a Cloudways managed server. You can also sign up for a 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>



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 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 command in SSH terminal.


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()

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 into create() function.


public function create()
{
    return view('tasks.create');
}

Task Controller store()

To insert data into the database, paste the following code into 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 name 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', '[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]');



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


RELATED POSTS



Subscribe and receive amazing posts directly in your inbox.