Update/Edit Query in Laravel Using Eloquent ORM

Update Query in Laravel Using Eloquent ORM

First of all I have changed routes>web.php file 

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\registrationController;
use App\Http\Controllers\customerController;
// use App\Models\Customers;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function(){
    return view('index');
});
Route::get('/register', [registrationController::class, 'index']);
Route::post('/register', [registrationController::class, 'register']);

Route::get('/customer/create', [customerController::class, 'index'])->name('customer.create');
Route::get('/customer/delete/{id}', [customerController::class, 'delete'])->name('customer.delete');
Route::get('/customer/edit/{id}', [customerController::class, 'edit'])->name('customer.edit');
Route::post('/customer/update/{id}', [customerController::class, 'update'])->name('customer.update');
Route::post('/customer', [customerController::class, 'store']);
Route::get('/customer', [customerController::class, 'view']);

After that I have create last two functions edit and update. In the edit function there are customer key in the compact which is used to get data in the customer blade file.

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Customers;

class customerController extends Controller
{
    public function index(){
        $title = "Customer Registration";
        $url = url('/customer');
        $data = compact('url', 'title');
        return view('customer')->with($data);
    }

    public function store(Request $request){
        echo "<pre>";
        print_r($request->all());

        $customers = new Customers;
        $customers->name = $request['name'];
        $customers->email = $request['email'];
        $customers->password = md5($request['password']);
        $customers->city = $request['city'];
        $customers->state = $request['state'];
        $customers->address = $request['address'];
        $customers->gender = $request['gender'];
        $customers->dob = $request['dob'];
        $customers->save();

        return redirect('/customer');
    }

    public function view(){
        $customers = Customers::all();
        // echo "<pre>";
        // print_r($customers->toArray());
        // echo "</pre>";

        $data = compact('customers');
        return view('customer-view')->with($data);
    }

    public function delete($id){
        // find targets primary key
       $customer = Customers::find($id);
       if(!is_null($customer)){
        $customer->delete();
       }
        return redirect('customer');
        // echo "<pre>";
        // print_r($customer);
    }

    public function edit($id){
        $customer = Customers::find($id);
        if(is_null($customer)){
            // not found
            return redirect('customer');
        }else{
            // found
            $title = "Customer Updatation";
            $url = url('customer/update') . "/" . $id;
            $data = compact('customer', 'url', 'title');
            return view('customer')->with($data);
        }
    }

    public function update($id, Request $request){
        $customer = Customers::find($id);
        $customer->name = $request['name'];
        $customer->email = $request['email'];
        $customer->city = $request['city'];
        $customer->state = $request['state'];
        $customer->address = $request['address'];
        $customer->gender = $request['gender'];
        $customer->dob = $request['dob'];
        $customer->save();
        return redirect('customer');
    }
}

After that is change customer blade file

<!--doctype html-->
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Customer Registration</title>
  </head>
  <body>
    <nav class="navbar navbar-expand-sm navbar-dark bg-dark px-5">
      <a class="navbar-brand" href="{{url(&#39;/&#39;)}}">VictoryAlphaWeb</a>
      <button class="navbar-toggler d-lg-none" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavId" aria-controls="collapsibleNavId"
          aria-expanded="false" aria-label="Toggle navigation"></button>
      <div class="collapse navbar-collapse" id="collapsibleNavId">
          <ul class="navbar-nav me-auto mt-2 mt-lg-0">
              <li class="nav-item">
                  <a aria-current="page" class="nav-link active" href="{{url(&#39;/&#39;)}}">Home <span class="visually-hidden">(current)</span></a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="{{url(&#39;/register&#39;)}}">Register</a>
              </li>
              <li class="nav-item">
                  <a class="nav-link" href="{{url(&#39;/customer&#39;)}}">Customer</a>
              </li>
          </ul>
      </div>
  </nav>

    <div class="container">
        <h2 class="text-center">{{$title}}</h2>

            <form class="row g-3" action="{{$url}}" method="post">
                @csrf
                <div class="col-md-6">
                  <label for="inputEmail4" class="form-label">Name</label>
                  <input type="text" name="name" class="form-control" id="inputEmail4" value="{{$customer->name}}">
                </div>
                <div class="col-md-6">
                  <label for="inputPassword4" class="form-label">Email</label>
                  <input type="email" name="email" class="form-control" id="inputPassword4" value="{{$customer->email}}">
                </div>
                <div class="col-md-6">
                  <label for="inputEmail4" class="form-label">Password</label>
                  <input type="password" name="password" class="form-control" id="inputEmail4">
                </div>
                <div class="col-md-6">
                  <label for="inputPassword4" class="form-label">Confirm Password</label>
                  <input type="password" name="cpassword" class="form-control" id="inputPassword4">
                </div>
                <div class="col-md-6">
                  <label for="inputEmail4" class="form-label">City</label>
                  <input type="text" name="city" class="form-control" id="inputEmail4" value="{{$customer->city}}">
                </div>
                <div class="col-md-6">
                  <label for="inputPassword4" class="form-label">State</label>
                  <input type="text" name="state" class="form-control" id="inputPassword4" value="{{$customer->state}}">
                </div>
                <div class="col-12">
                  <label for="inputAddress2" class="form-label">Address</label>
                  <textarea type="text" name="address" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">{{$customer->address}}</textarea>
                </div>
                <div class="col-md-6">
                  <label for="inputCity" class="form-label">Gender: </label>
                  <div class="form-check ">
                    <input class="form-check-input" type="radio" name="gender" id="inlineRadio1" value="M"
                    {{$customer->gender == "M" ? "checked" : ""}}
                    >
                    <label class="form-check-label" for="inlineRadio1">Male</label>
                  </div>
                  <div class="form-check">
                    <input class="form-check-input" type="radio" name="gender" id="inlineRadio2" value="F"
                    {{$customer->gender == "F" ? "checked" : ""}}
                    >
                    <label class="form-check-label" for="inlineRadio2">Female</label>
                  </div>
                  <div class="form-check">
                    <input class="form-check-input" type="radio" name="gender" id="inlineRadio3" value="O"
                    {{$customer->gender == "O" ? "checked" : ""}}
                    >
                    <label class="form-check-label" for="inlineRadio3">Other</label>
                  </div>
                </div>
                <div class="col-md-4">
                  <label for="inputState" class="form-label">Date of Birth</label>
                  <input type="date" name="dob" class="form-control" id="inputCity" value="{{$customer->dob}}">
                </div>
                <div class="col-12">
                  <button type="submit" class="btn btn-primary">Submit</button>
                </div>
              </form>
    </div>


    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>

And the data resulted on customer-view blade file

<!--doctype html-->
<html lang="en">

<head>
  <title>VictoryAlphaWeb</title>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS v5.2.1 -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

</head>

<body>
    <nav class="navbar navbar-expand-sm navbar-dark bg-dark px-5">
        <a class="navbar-brand" href="{{url(&#39;/&#39;)}}">VictoryAlphaWeb</a>
        <button class="navbar-toggler d-lg-none" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavId" aria-controls="collapsibleNavId"
            aria-expanded="false" aria-label="Toggle navigation"></button>
        <div class="collapse navbar-collapse" id="collapsibleNavId">
            <ul class="navbar-nav me-auto mt-2 mt-lg-0">
                <li class="nav-item">
                    <a aria-current="page" class="nav-link active" href="{{url(&#39;/&#39;)}}">Home <span class="visually-hidden">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{url(&#39;/register&#39;)}}">Register</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{{url(&#39;/customer&#39;)}}">Customer</a>
                </li>
            </ul>
        </div>
    </nav>

    <div class="container my-4">
        <a href="{{Route(&#39;customer.create&#39;)}}">
            <button class="btn btn-primary d-inline-block m-2 float-end">Add</button>
        </a>
    <div class="table">
        <table class="table table-dark">
            <thead>
                <tr>
                    <th scope="col">Name</th>
                    <th scope="col">Email</th>
                    <th scope="col">Gender</th>
                    <th scope="col">State</th>
                    <th scope="col">City</th>
                    <th scope="col">Address</th>
                    <th scope="col">DOB</th>
                    <th scope="col">Status</th>
                    <th scope="col">Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach ($customers as $customer)
                <tr class="">
                    <td>{{$customer->name}}</td>
                    <td>{{$customer->email}}</td>
                    <td>
                        @if ($customer->gender == "M")
                            Male
                        @elseif($customer->gender == "F")
                            Female
                        @else
                            Other
                        @endif
                    </td>
                    <td>{{$customer->state}}</td>
                    <td>{{$customer->city}}</td>
                    <td>{{$customer->address}}</td>
                    <td>{{$customer->dob}}</td>
                    <td>
                        @if ($customer->status == "1")
                            <span class="badge bg-success">Active</span>
                        @else
                            <span class="badge bg-danger">Inactive</span>
                        @endif
                    </td>
                    <td>
                        <a href="{{Route(&#39;customer.delete&#39;, [&#39;id&#39; =&gt; $customer-&gt;customer_id])}}"><button class="btn btn-danger">Delete</button></a>
                        <a href="{{Route(&#39;customer.edit&#39;, [&#39;id&#39;=&gt; $customer-&gt;customer_id])}}"><button class="btn btn-primary">Edit</button></a>
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>
    </div>
</div>
    
  <!-- Bootstrap JavaScript Libraries -->
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"
    integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous">
  </script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.min.js"
    integrity="sha384-7VPbUDkoPSGFnVtYi0QogXtr74QeVeeIs99Qfg5YCF+TidwNdjvaKZX19NZ/e6oz" crossorigin="anonymous">
  </script>
</body>

</html>

Observe the code and understand to concepts carefully. Thats all about update query in Laravel using eloquent ORM.

Comments