Laravel CRUD Operation for a beginner with example and demo.

crud

Today, we share with you a very important tutorial on Laravel CRUD Operation using MySQL. in these tutorials, we are using simple data insert update & delete. You can easily create a CRUD in laravel.so, here we are starting Basic CRUD operation for the beginner.

Overview Of Task:

  •  Step 1: Install Laravel latest version
  • Step 2: Database updation.
  •  Step 3: Create database tables
  •  Step 4: Create a route
  •  Step 5: Create Controller and Model
  •  Step 6: Create Blade Files

Step 1: Install Laravel Latest Version

First of all, we need to get fresh version application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Database updation

In the second step, we have to open .env file in the Laravel folder & changes of the database name, password, and username.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE= your database name(Example. person)
DB_USERNAME=your database username(Example. root)
DB_PASSWORD=your database password(Example. root)

Step 3: Create database tables

In this step, we create database tables, so open your terminal and run this below command.

php artisan make:migration create_person_table

After these commands perform you have to open {Project Name}/database/migration and put below code.

<?php


use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;


class CreatePersonTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('person', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->text('detail');
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('person');
    }
}

Now you have to run this migration by the following command:

php artisan migrate

Step 4: Create a route

In this step, we have to find routes/web.php and put the below code.

Route::get('person', 'PersonController@index')->name('person');
Route::get('person/create', 'PersonController@create')->name('person/create');
Route::post('person/store', 'PersonController@store')->name('person/store');
Route::get('person/show/{id}', 'PersonController@show')->name('person/show');
Route::get('person/edit/{id}', 'PersonController@edit')->name('person/edit');
Route::post('person/edit/{id}', 'PersonController@update')->name('person/edit');
Route::any('person/destroy/{id}', 'PersonController@destroy')->name('person/destroy');

Step 5:Create Controller and Model

In this step we have to create Controller & Model, so open your terminal and run below command.

php artisan make:controller PersonController --resource --model=Person

After this Command, we have to create seven methods in laravel.

  • index => This method used to show the student data.
  • create => This method used to create data.
  • store => This method uses for an entered data stores in the database.
  • show => This method uses to show the data by its id.
  • edit => This method uses to edit its data by id.
  • update => This method make changes and store in the database.
  • destroy => This method delete data by its id.

In this step, we have to find app/Http/Controllers/PersonController.php and put the below code.

<?php
namespace App\Http\Controllers;

use App\Person;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PersonController extends Controller
{
    public function index(){
        $person = Person::latest()->get();
        return view('person/index',compact('person'));
    }
    public function create(){
        return view('person/create');
    }
    public function store(Request $request){
        $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
        Person::create($request->all());
        return redirect()->route('person');
    }
    public function show(Person $person, $id){
        $person = Person::where("id", $id)->first();
        return view('person/show',compact('person'));
    }
    public function edit(Person $person,$id){
        $person = Person::where("id", $id)->first();
        return view('person/edit',compact('person'));
    }
    public function update(Request $request, Person $person){
         $request->validate([
            'name' => 'required',
            'detail' => 'required',
        ]);
        $person->update($request->all());
        return redirect()->route('person');
    }
    public function destroy(Person $person){
        $person->delete();
        return redirect()->route('person/index');
    }
}

In this step, we have to find app/Person.php and put the below code.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    public $table = 'person';
    protected $fillable = [
        'name', 'detail'
    ];
}

Step 6: Create Blade Files

In this step, we have to find resources/views and create a new folder name person & put the below code.

First, you have had to create index.blade.php


@extends('layouts.app')
 
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Laravel CRUD Opeartion for the Beginners</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-success" href="{{ route('person/create') }}"> Create New Person</a>
            </div>
        </div>
    </div>
   
    @if ($message = Session::get('success'))
        <div class="alert alert-success">
            <p>{{ $message }}</p>
        </div>
    @endif
   
    <table class="table table-bordered">
        <tr>
            <th>No</th>
            <th>Name</th>
            <th>Details</th>
            <th width="280px">Action</th>
        </tr>
        @foreach ($person as $key=>$persons)
        <tr>
            <td>{{  $key + 1 }}</td>
            <td>{{ $persons->name }}</td>
            <td>{{ $persons->detail }}</td>
            <td>
                 <a href="{{ route('person/edit',$persons->id) }}" class="btn btn-primary">Edit</a>
                 <a href="{{ route('person/show',$persons->id) }}" class="btn btn-primary">Show</a>
                 <form action="{{ route('person/destroy', $persons->id)}}" method="post">
                    @csrf 
                    @method('DELETE')
                </form>
            </td>
        </tr>
        @endforeach
    </table>

<style type="text/css">
    .card-header {
        border-radius: .625rem !important;
        box-shadow: 0 0.46875rem 2.1875rem rgba(90,97,105,.1), 
                    0 0.9375rem 1.40625rem rgba(90,97,105,.1), 
                    0 0.25rem 0.53125rem rgba(90,97,105,.12), 
                    0 0.125rem 0.1875rem rgba(90,97,105,.1);
    }
</style>
@endsection

After creating an index file, you have had to create create.blade.php

@extends('layouts.app')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Person</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('person') }}"> Back</a>
        </div>
    </div>
</div>
   
@if ($errors->any())
    <div class="alert alert-danger">
        <strong>Whoops!</strong> There were some problems with your input.<br><br>
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif
   
<form action="{{ route('person/store') }}" method="POST">
    @csrf
     <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Detail:</strong>
                <textarea class="form-control" style="height:150px" name="detail" placeholder="Detail"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>
@endsection

After creating a Person, if you want to check by its id then create a show.blade.php blade file.

@extends('layouts.app')
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Person</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('person') }}"> Back</a>
            </div>
        </div>
    </div>
   
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Name:</strong>
                {{ $person->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Details:</strong>
                {{ $person->detail }}
            </div>
        </div>
    </div>
@endsection

After checking all these things if you want to update your person than you have to create edit.blade.php file.

@extends('layouts.app')   
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2>Edit Person</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('person') }}"> Back</a>
            </div>
        </div>
    </div>
    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
    <form action="{{ route('person/edit',$person->id) }}" method="POST">
        @csrf
        @method('PUT')
        <div class="form-group">
            <label class="label">Name:</label>
            <input type="text" name="name" value="{{ $person->name }}" class="form-control" placeholder="Name">
        </div>
        <div class="form-group">
            <label class="label">Detail:</label>
            <input type="text" name="detail" value="{{ $person->detail }}" class="form-control" placeholder="Detail">
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-success">Submit</button>
        </div>
        </form>
@endsection

Now we are ready to run our task with laravel , so run bellow command for the run:

php artisan serve

Now you have to open your browser and put below URL:

http://localhost:8000/person/

About Dhaval Shah

My name is Dhaval Shah. I'm a PHP developer, entrepreneur and CEO of DAG inventions PVT ltd. I live in India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Java-script, JQuery, Laravel, WordPress and Bootstrap.
Follow me on Github / Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!