Laravel

Crud Operation in Laravel 8 with Example

In this article, I will guide you about crud operation in Laravel 8. We will do create, read, update and delete, we will step by step guide to do crud operation in Laravel 8.

To do the crud operation in PHP we will follow the below steps -:

  • Installing Laravel 8
  • Setting up a MySQL Database
  •  Create Model & Migration
  • Create Routes
  • Create Controller
  • Create Blade Views File

Step: 1 – Installing Laravel 8

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

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

Step 2 – Setting up a MySQL Database

In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 8. So let’s open .env file and fill all details like as below:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database-name
DB_USERNAME=database-user-name
DB_PASSWORD=database-password

Step 3 –  Create Model & Migration

we are going to create crud application for students. so we have to create migration & model together for “students” table using Laravel 8 php artisan command, so first fire below command:

php artisan make:model Student -m

After this command you will find one file in following path “database/migrations” and you have to put below code in your migration file for create students table.

<?php

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

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

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

Now you have to run this migration by following command:

php artisan migrate

Ok, so after run bellow command you will find “app/Models/Student.php” and put below content in Student.php file:

<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Student extends Model
{
    use HasFactory;

    protected $fillable = ['name','email'];
    
    
}

Step 4 – Create Routes

Here, we need to add resource route for student crud application. so open your “routes/web.php” file and add following route.

	
<?php

Route::prefix('school')->middleware('auth', 'acl')->group(function () {
    Route::get('/', 'SchoolController@index')->name('schools.index');
    Route::get('schools/create', 'SchoolController@create')->name('schools.create');
    Route::post('schools/store', 'SchoolController@store')->name('schools.store');
    Route::get('/show/{school}', 'SchoolController@show')->name('schools.show');
    Route::get('/edit/{id}',     'SchoolController@edit')->name('schools.edit');
    Route::post('/update/{id}', 'SchoolController@update')->name('schools.update');
    Route::post('/delete/{id}', 'SchoolController@destroy')->name('schools.destroy');
});

Step 5 – Create Controller

In this step, now we should create new controller as StudentController. So run bellow command and create new controller. below controller for create controller.

php artisan make:controller StudentController

After below command you will find new file in this path “app/Http/Controllers/StudentController.php”.

In this controller will create seven methods by default as below methods:

1)index()

2)create()

3)store()

4)show()

5)edit()

6)update()

7)destroy()

So, let’s copy below code and put on StudentController.php file.

app/Http/Controllers/StudentController.php

<?php

 
namespace App\Http\Controllers;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\Student\Entities\Student;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index()
    {
        
       
        $students = Student::get();

        return view('student::index',compact('students'))
        ->with('i', (request()->input('page', 1) - 1) * 5);


        }
    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        return view('student::create');
        
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
       
        $students = \Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required',
            
         ]
         [
            'required'  => 'The :attribute field is required.',  
          ]);
              
       Student::create($request->all());
        
        return redirect()->route('students.index');              
   
                   
    }

    /**
     * Show the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function show($id)
    {
        return view('student::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($student)
    {
        $students = Student::where('id',$student)->first(); 
        return view('student::edit',compact('students'));
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required',


        ]);
        $data = [
            'name' => $request->name,
            'email' => $request->email,


          
           ];
         Student::where('id', $id)->update($data);
        

        return redirect()->route('students.index')
                        ->with('success','Student Name Updated Successfully');
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($students)
    {
        Student::where('id', $students)->delete();

        return redirect()->route('students.index')
                ->with('success','Student Name Deleted Successfully');
    }
}

Step 4 – Create Blade Views File

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder “students” then create blade files of crud app. So finally you have to create following below blade file:

1) layout.blade.php

2) index.blade.php

3) create.blade.php

4) edit.blade.php

5) show.blade.php

So let’s just create following file and put below code.

resources/views/students/layout.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 CRUD Application </title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  
<div class="container">
    @yield('content')
</div>
   
</body>
</html>

resources/views/students/index.blade.php

@extends('students.layouts.app')
@section('content')
 <div class="app-main__inner">
  <div class="row mb-2 mb-xl-3">
   <div class="col-auto ms-auto text-end mt-n1">
    <a class="btn btn-success" href="{{ route('students.create') }}">
       Create New student</a>
   </div>
  </div>
  <div class="row">
   <div class="col-md-12">
    <div class="main-card mb-3 card">
      <div class="card-body">
       <div class="table-responsive">
         <table class="table table-striped table-bordered" id="dataTable"
           width="100%" cellspacing="0">              
           <thead>
            <tr>
             <th>Id</th>
             <th>Name</th>
             <th>Email</th>                
             <th>Action</th>
            </tr>
           </thead>
           <tbody>
            @isset( $students)
            @foreach ( $students as $key =>
             $student)
             <tr>
               <td>{{  $student->id }}</td>
               <td>{{  $student->name }}</td>
               <td>{{  $student->email }}</td>                                    
               <td>
                <a class="btn btn-primary btn-shadow"
                href="{{ route('students.edit',  $student->id) }}">
                <i class="fa fa-fw" aria-hidden="true" title="edit"></i>
                </a>

                <a href="javascript:void(0)" id="{{  $student->id }}"
                class="delete-student btn btn-danger">
                <i class="fa fa-fw" aria-hidden="true" title="delete"></i>
                </a>
               </td>
              </tr>
             @endforeach
            @endisset
           </tbody>
          </table>
        </div>
       </div>
      </div>
     </div>
    </div>
  </div>
@endsection

resources/views/students/create.blade.php

@extends('students.layout')
  
@section('content')
<div class="row">
    <div class="col-lg-12 margin-tb">
        <div class="pull-left">
            <h2>Add New Student</h2>
        </div>
        <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('students.index') }}">              
            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('students.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 class="alert-danger">{{ $errors->first('name') }}</div>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Email:</strong>
                <textarea class="form-control" style="height:150px"
                  name="detail" placeholder="Detail"></textarea>
                <div class="alert-danger">{{ $errors->first('email') }}</div>
            </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

resources/views/students/edit.blade.php

@extends('students.layout')
   
@section('content')
    <div class="row">
       <div class="col-lg-12 margin-tb">
          <div class="pull-left">
             <h2>Edit students</h2>
          </div>
          <div class="pull-right">
            <a class="btn btn-primary" href="{{ route('students.index') }}">
                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('students.update',$students->id) }}" method="POST">
        @csrf
        @method('PUT')
   
         <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" value="{{ $student->name }}"    
                      class="form-control" placeholder="Name">
                    <div class="alert-danger">{{ $errors->first('name') }}</div>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
                <div class="form-group">
                    <strong>Email:</strong>
                    <textarea class="form-control" style="height:150px" 
                     name="detail" placeholder="Detail">{{ $students->detail }}      
                    </textarea>
                    <div class="alert-danger">{{ $errors->first('email')}}</div>
                </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

resources/views/students/show.blade.php

@extends('students.layout')
  
@section('content')
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="pull-left">
                <h2> Show Student</h2>
            </div>
            <div class="pull-right">
                <a class="btn btn-primary" href="{{ route('students.index') }}">     
                    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>
                {{ $students->name }}
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12">
            <div class="form-group">
                <strong>Email:</strong>
                {{ $students->detail }}
            </div>
        </div>
    </div>
@endsection

Now we are ready to run our crud application example with laravel 8 so run below command for a quick run:

php artisan serve

Now you can open the below URL on your browser:

localhost:8000

I hope the above article will help you understand laravel crud operation, please rate me 5 to keep me motivated.

Related Articles

4 Comments

Leave a Reply

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

Back to top button