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:
2. using route:
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 "";
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 "";
// print_r($customers->toArray());
// echo "";
$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 "";
// 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
Post a Comment