How To Delete Record By ID using Laravel Eloquent
In this tutorial, we will learn How To Delete Record By ID using Laravel Eloquent. Laravel default provide delete() and destroy() method to delete data. If you want to delete a record by id in the Laravel application, then you are right place. I will give you a few examples of how to delete records by id using Laravel Eloquent.
Are you looking for an example of Delete Record By ID using Laravel Eloquent? You will learn Laravel eloquent to delete records by id. So, let’s discuss deleting records in Laravel using by id.
Example 1: Eloquent query
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Posts;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Posts::where('id', 1)->delete();
}
}
Example 2: Eloquent delete method
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Posts;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$post = Posts::find(1);
$post->delete();
}
}
Example 3: Eloquent destroy method
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Posts;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Posts::destroy(1);
}
}
Example 4: Delete an array of ids
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Posts;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
Posts::destroy([1, 2, 3]);
}
}