CRUD Operation By Laravel

Welcome back, Developers! Today I want to share some basic and clear steps on how to create a CRUD application by using the Laravel php framework.

How to install and configure Laravel setups on your local machine visit here https://bbn11.com/laravel/.

In this tutorial, we cover all of Laravel’s basic concepts and advanced concepts.

Step 1: Download the Laravel framework by using the following commands

Composer create-project –prefer-dist Laravel/Laravel crud app

Step 2: change your directory to a project directory by using

               Cd crudapp

Step 3:  Run the project by using the command below

               Php artisan serve

How to Create Route on Laravel

Route tells the direction of the system. Gives the getaways off the system.

To create Route follow the following steps.

step 1: open your project with the code editor you want. For these tutorials, I used the Vs code free version and Opened by Vs code routes folder selected web.php files, and edited contents found on wep.php

Step 2: Open web.php and update the code by the following code.

<?php

use Illuminate\Support\Facades\Route;

use \App\Http\Controllers\StudentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', [StudentController::class,'index'])->name('student.list');
Route::get('/add', [StudentController::class,'create'])->name('student.add');
Route::post('/save', [StudentController::class,'store'])->name('student.save');
Route::get('/edit/{id}', [StudentController::class,'edit'])->name('student.edit');
Route::post('/update/{id}', [StudentController::class,'update'])->name('student.update');
Route::get('/delete/{id}', [StudentController::class,'destroy'])->name('student.delete');

The above code is used to create a Route for crud application based on student information

How to Create Controller on Laravel

To create a controller use the following commands.

Php artisan make: controller StudentController

The controller is the fundamental concept of the setups. In the controller, we can perform all actions like List, Edit, Delete, and other filter functions.

In Controller, we create methods with private and public methods.

Let’s copy the following functions into your controllers

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Students;
use Illuminate\Http\Request;


class StudentController extends Controller
{
    //
    public function index()  {
        $students=Students::all();
        return view('student.list',['students'=>$students]);
    }
    public function create(){
        return view('student.add');
    }
    public function store(Request $request) {
        $student=new Students();
        $student->first_name=$request->first_name;
        $student->middle_name=$request->middle_name;
        $student->last_name=$request->last_name;
        $student->email=$request->email;
        $student->phone=$request->phone;
        $student->dob=$request->dob;
        $student->department=$request->department;
        $student->save();
        return redirect('/')->with('success','Student Added Successfully!');        
    }

    public function edit($id){
        $student=Students::find($id);
        return view('student.edit',['student'=>$student]);
   }
   public function update(Request $request, $id)
   {
    $stuent= Students::find($id);
    $student->first_name=$request->first_name;
    $student->middle_name=$request->middle_name;
    $student->last_name=$request->last_name;
    $student->email=$request->email;
    $student->phone=$request->phone;
    $student->dob=$request->dob;
    $student->department=$request->department;
    $student->update();
    return redirect('/')->with('success','Student Updated Successfully!');        

   }

   public function destroy($id){
    $student=Students::find($id);
    $student->delete();
    return redirect('/')->with('success','Student Deleted Successfully!');        

   }
   
}

The above code has different functions, index, create, edit, update, and destroy.

Index functions are used to list all students from the database.

Create a function used to display the student-created forms.

Store function used to save student information to the database.

Edit functions used to display interfaces

Destroy is used to delete student information from the database.

How to Configure Laravel with Database

To configure Laravel setups with database and application names follow the following steps

Step 1: go to the .env file and edit it to your database configuration files.

DB_CONNECTION=mysql// your database engine
DB_HOST=127.0.0.1 // localhost ip address
DB_PORT=3306 // port numbers
DB_DATABASE=appdb // your database 
DB_USERNAME=root //database username
DB_PASSWORD= // database password

Step 2. Configure Application or System Name Update .env file on the top

APP_NAME=Laravel  // Application Name

How to Create Models

To create a model use the following command on the terminals.

 Php artisan make:model Students -m

The above command is used to create models and –m also creates migrations of the database for tables. crudapp> php artisan make:

model Students –m

How to Migrate migration data to a database

To migrate the migration database or schema to the database use the following command When we migrate there are two types

of actions are performed

1.       New Database  created

2. A table in the database on migrations is included.

Php artisan migrates// Migrate migrated seed data to the database. How to Create View in Laravel Laravel is used for the view blade template. Blade template means .blade extensions, blade template we can use bootstrap, HTML, CSS, and js files. In these tutorials, we create three files in student folders in the resources directory. Add, Edit, list,

and others.

Add.blade.php

@extends('layouts.app')
@section('contents')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Dashboard</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Dashboard v1</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <div class="container-fluid">
        <div class="row">
            <!-- left column -->
            <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Student Registration Form</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form action="{{route('student.save')}}" method="post">
                        @csrf
                        <div class="card-body">
                            <div class="form-group">
                                <label for="exampleInputEmail1">Student Name</label>
                                <input type="text" name="first_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter First Name">
                            </div>
                           
                           
                            <div class="form-group">
                                <label for="exampleInputEmail1">Middle Name</label>
                                <input type="text" name="middle_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Middle Name">
                            </div>
                           
                            <div class="form-group">
                                <label for="exampleInputEmail1">Last Name</label>
                                <input type="text" name="last_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Last Name">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Email</label>
                                <input type="email" name="email" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Email">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Phone</label>
                                <input type="text" name="phone" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Phone">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">DOB</label>
                                <input type="date" name="dob" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Last Name">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Department</label>
                                <input type="text" name="department" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter department">
                            </div>
                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">Submit</button>
                        </div>
                    </form>
                </div>

            </div>
            <!--/.col (left) -->
            <!-- right column -->
            
            <!--/.col (right) -->
        </div>
        <!-- /.row -->
@endsection

List.blade.php

in these blade files, we can retrieve all data from the database and display it in table formats.

@extends('layouts.app')
@section('contents')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Student</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Student List</a></li>
                        <li class="breadcrumb-item active">Lsit</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <div class="row">
          <div class="col-12">
            <div class="card">
              <div class="card-header">
                <h3 class="card-title">List of Stuent</h3>

                <div class="card-tools">
                  <div class="input-group input-group-sm" style="width: 150px;">
                    <input type="text" name="table_search" class="form-control float-right" placeholder="Search">

                    <div class="input-group-append">
                      <button type="submit" class="btn btn-default">
                        <i class="fas fa-search"></i>
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              <!-- /.card-header -->
              <div class="card-body table-responsive p-0">
                <table class="table table-hover table-bordered">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th>Full Name</th>
                      <th>Email</th>
                      <th>Phone</th>
                      <th>Department</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    @foreach ($students as $student)
                    <tr>
                      <td>{{ $loop->iteration }}</td>
                      <td>{{$student->first_name }} {{$student->middle_name}}  {{$student->last_name}}</td>
                      <td>{{$student->email}}</td>
                      <td>{{$student->phone}}</td>
                      <td>{{$student->department}}</td>
                      <td>
                        <a href="#" class="btn btn-sm btn-info">Edit</a>
                        <a href="#" class="btn btn-sm btn-danger">Delete</a>
                      </td>
                    </tr>
                    @endforeach
                    
                
                  </tbody>
                </table>
              </div>
              <!-- /.card-body -->
            </div>
            <!-- /.card -->
          </div>
        </div>
    @endsection

Edit.blade.php

In these view templates, we can create and edit student data. The difference between edit and add is that add is creating or storing new data, but edit updating existing data fully or partially.

To get the edit interface we must use the link that gets the unique ID of the students

<a href=”{{url(‘edit/’.$student->id)}}” class=”btn btn-sm btn-info”>Edit</a>

let’s start typing code for editing the view interface

on StudentControllers Update the following Codes

 public function edit($id){
        $student=Students::find($id);
        return view('student.edit',['student'=>$student]);
   }

$student variable get data from the database of associated students by ID and hold on.

On View, we call it a single variable, not multiple values.

edit.blade.php

@extends('layouts.app')
@section('contents')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Students</h1>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item active">Edit Student</li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
    <div class="container-fluid">
        <div class="row">
            <!-- left column -->
            <div class="col-md-12">
                <!-- general form elements -->
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Student Edit Form</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form action="{{route('student.update')}}" method="post">
                        @csrf
                        @method("PUT")
                        <div class="card-body">
                            <div class="form-group">
                                <label for="exampleInputEmail1">Student Name</label>
                                <input type="text" value="{{$student->first_name}}" name="first_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter First Name">
                            </div>
                           
                           
                            <div class="form-group">
                                <label for="exampleInputEmail1">Middle Name</label>
                                <input type="text"  value="{{$student->middle_name}}" name="middle_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Middle Name">
                            </div>
                           
                            <div class="form-group">
                                <label for="exampleInputEmail1">Last Name</label>
                                <input type="text"  value="{{$student->las_name}}" name="last_name" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Last Name">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Email</label>
                                <input type="email"  value="{{$student->email}}" name="email" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Email">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">Phone</label>
                                <input type="text" value="{{$student->phone}}" name="phone" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Phone">
                            </div>

                            <div class="form-group">
                                <label for="exampleInputEmail1">DOB</label>
                                <input type="date"  value="{{$student->dob}}" name="dob" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter Last Name">
                            </div>
                            <div class="form-group">
                                <label for="exampleInputEmail1">Department</label>
                                <input type="text"  value="{{$student->department}}" name="department" class="form-control" id="exampleInputEmail1"
                                       placeholder="Enter department">
                            </div>
                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">Update</button>
                        </div>
                    </form>
                </div>

            </div>
            <!--/.col (left) -->
            <!-- right column -->
            
            <!--/.col (right) -->
        </div>
        <!-- /.row -->
@endsection
 

Updating data is not fetching student information on the interface, we must update our database information. To update data on the database we must use the controller StudentController and function update methods

On StudentController Edit the following Code.

  public function update(Request $request, $id)
   {
    $stuent= Students::find($id);
    $student->first_name=$request->first_name;
    $student->middle_name=$request->middle_name;
    $student->last_name=$request->last_name;
    $student->email=$request->email;
    $student->phone=$request->phone;
    $student->dob=$request->dob;
    $student->department=$request->department;
    $student->update();
    return redirect('/')->with('success','Student Updated Successfully!');        

   }

The above code is used to update data on the database based on client-summited data from the interface.

Delete.blade.php

Deleting is removing data from the database permanently. Deleting data can be performed by using the information of data from the client summited.

On routes /web.php we must configure it like below

Route::get('/delete/{id}', [StudentController::class,'destroy'])->name('student.delete');

After Configuring on list of student blade interfaces we must have the link that takes to these route configurations, these links as below

 <a href="{{url('delete/'.$student->id)}}" class="btn btn-sm btn-danger">Delete</a>

The above code displays links that are used to delete data from the database with action and user ID.

On StudentController we must edit the following code to make delete operations

 public function destroy($id){
    $student=Students::find($id);
    $student->delete();
    return redirect('/')->with('success','Student Deleted Successfully!');        

   }

Conclusion

A general crud operation is the creation of basic framework operations.

Laravel is an easy and very useful php framework to work with it

CRUD means

C: Create

R: Reading data from the database

U: Update

D: Delete/ or Destroy data from the database

Author: bbnadmin

1 thought on “CRUD Operation By Laravel

Leave a Reply

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