Delete Query in Laravel using Eloquent ORM | Laravel 9 | delete(), is_null() and find()

Delete Query in Laravel using Eloquent ORM

First of all create a get request to delte query in the web.php
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::post('/customer', [customerController::class, 'store']);
Route::get('/customer', [customerController::class, 'view']);

There are two methods to delete query using url and route.
1. using url:
<td>
    <a href="{{url(&#39;/customer/delete&#39;)}}/{{$customer-&gt;customer_id}}"><button class="btn btn-danger">Delete</button></a>
    <a href=""><button class="btn btn-primary">Edit</button></a>
</td>
2. using route:
<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=""><button class="btn btn-primary">Edit</button></a>
</td>
Inside customerController delete function delete the queries
app>http>controllers>customerController
namespace App\Http\Controllers;

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

class customerController extends Controller
{
    public function index(){
        return view('customer');
    }

    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);
    }
}

Find function fetch the primary key, delete function use to delete and is_null() use to check if it is null or not.

Comments