Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a delete operation on a Model?

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.

like image 760
Sylar Avatar asked Mar 19 '15 22:03

Sylar


People also ask

What is a delete operation?

The delete operation may be performed over one or more objects that satisfy the conditional expression defined for it. The delete operation may be used in conjunction with a list (any kind of list), where the user may select the object(s) to be deleted.

What is delete operation in database?

The Delete command in SQL is a part of the Data Manipulation Language, a sub-language of SQL that allows modification of data in databases. This command is used to delete existing records from a table. Using this, you can either delete specific records based on a condition or all the records from a table.

How to delete users in laravel?

update users set deleted_at = NOW() where id = X; Or, if you prefer to not connect to database, and use Artisan Tinker, you can do this: User::find(1)->delete();

How do I delete a model in laravel?

Laravel Eloquent Deleting You can delete data after writing it to the database. You can either delete a model instance if you have retrieved one, or specify conditions for which records to delete. To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete();


2 Answers

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

like image 148
Marcin Nabiałek Avatar answered Oct 05 '22 18:10

Marcin Nabiałek


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();
like image 39
Jeff Avatar answered Oct 05 '22 20:10

Jeff