How to perform a delete operation on a Model?

58,080

Solution 1

You can put this code for example in controller.

You can use

$user = User::find($id);    
$user->delete();

if you don't use SoftDeletingTrait trait or

$user = User::find($id);    
$user->forceDelete();

if you do, and you want to really remove user from database, not just hide it from results.

More you can read at Laravel page

Solution 2

in Laravel 5 you can use the destroy method.

$user->destroy($id);

and, sure, you have a command line to do so.

$ php artisan tinker

and you can run for example

>> $var = new App\User;
>> $user= $user->find($id);
>> $user->destroy();

Solution 3

Several ways to do this.

If your controller defines the user as an argument:

public function destroy(User $user) 
{
    return $user->delete();
}

You can also delete any user by $id:

User::destroy ($id);

Assuming you're wrapping these routes with some security.

Edit: Corrected spelling

Solution 4

You can use bellow example to delete data with multiple parameters......

> 
> tableName::where('field_1','=',$para1)
>               ->where('field_2,'=',$para2)
>               ->delete();
Share:
58,080
Sylar
Author by

Sylar

Updated on July 31, 2022

Comments

  • Sylar
    Sylar over 1 year

    Coming from a Ruby on Rails experience where you load up the rails console to delete a user or all users. I am new to Laravel 5 and I am looking for something similar to delete a user already in the sqlite3 database.

    I see where people are talking about User::find(1)->delete(); to delete a user but where to you put that and run in? Is there a console to perform a delete task in? I would like to know how to delete a user without dropping the table. I do not want to soft delete.