Delete users but not their posts in laravel!

Delete users but not their posts in laravel!


Hello dear followers, today we have an exclusive tutorial for you. in this tutorial we are going to learn how to delete users but not their posts in laravel 5.4/5.5, we also will talk why this is good feature to have in your application.

1) why?

Having user terminate in your application is a necessary need if you're going to allow users register in your website.

For many reasons you might need to delete users from your application. But what will happen to your website SEO if some of those users had published posts in your website? would it cause you trouble with ranking? sure it does. When google or other search engines bots try to reach your posts/pages but they no longer exist or show your url as result and human users visits your site and there would be no such a page it will make you trouble with SEO which obviously you worked hard to build it up.

Now one of the solution of this issue might be to save those posts but still be able to delete the author(s), how? that's what we will discuss in this tutorial.


Note: We are going to use post(s) for this tutorial but your controller can be anything such as products etc.

First of all let's take a look at our posts destroy method in UserController.

public function destroy($id)
      $user = User::findOrFail($id);

      return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');

This is basically our destroy function to delete user(s).

What we need is a default user to assign deleted user posts to it and then delete the user. So you can go to your phpmyadmin or any other that you use and create a user. (We named our default user bot).

Now we have our default user let's back to destroy function and change it.

public function destroy($id)
        $user = User::findOrFail($id);
        $posts = $user->post()->get();
            $botUser = User::where('username', '=', 'bot')->get()->first();
            foreach($post as $post)
                $post->user_id = $botUser->id;
        return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');

What we did?

we said find the user that we want to delete in line 3.

Then we collected all his/her posts in line 4.

In line 5 we said IF s/he has any post and we lopped them also in line 6 we called our default user by username (why username? well I prefer username because I think if I make opensource application the id of bot user could be different in different website and that's why I prefer username rather than id. But you can use id if you like).

In line 10 finally we assigned our user posts to our bot user.

And in line 11 we saved our changes.

Else parameter in line 15 will work for the users without post and will delete them immediately.

In line 17 we will delete user image if they have.

And in line 18 we return to our users list.


we used $user->forceDelete(); in line 15 which tell us that we are using softDelete eloquent in our User model.

Let's take a look at our User model.


namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateDatabaseEloquentSoftDeletes;

class User extends Authenticatable
    use Notifiable;
    use SoftDeletes;

   // Rest of the codes....

Now the last thing you need to do is to add $table->softDeletes(); to your users table.

Go to database folder -> migrations and open -> create_users_table.php .

And add the line above before your timestamps.

public function up()
        Schema::create('users', function (Blueprint $table) {

Now you can refresh your database with

php artisan migrate:fresh

In laravel 5.5 or

php artisan migrate:refresh

In laravel 5.4 .

2 + 1)

I have extra tutorial for you that you might like

As you see we added sofDelete to our application and users with post will be sofDelete instead of forceDelete, Confuse?

Let me explain it:

SoftDelete will not delete the user from your database but will add timestamps to new column we added before named deleted_at . In this way user still exist in your database and you can take him/her back but till then s/he cannot use your website. However forceDelete is permanently delete and directly sweep user from your database like before we use softDelete eloquent.

Hope you underestand now. Let's move on..

The extra tutorial is about bring back the user and delete him/her permanently.

for taking back the user (restore) we need new function in our UserController we will call it restoreuser , this is how it looks like:

public function restoreuser($id)
        $user = User::onlyTrashed()->where('id', $id);
        return redirect()->route('users.index')->with('flash_message', 'User successfully restored');

And obviously we need a route for that, and it will be like this:

Route::get('/restoreuser/{id}', 'UserController@restoreuser')->name('restoreuser');

Then in our blade where all the users are listed index.blade.php . We will have a link like this:

<a class="text-primary" href="{{route('restoreuser', $user->id)}}">Restore</a>

Now we can restore our deleted user and bring it back to life .

I will leave an assignment for you and that is how to delete user permanently? if you'd paid attention to this tutorial that would be easy for you to do

- Last updated 4 years ago

Be the first to leave a comment.

You must login to leave a comment