Delete users but not their posts in laravel!

Delete users but not their posts in laravel!

1,586

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.

2)

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);
      Storage::delete($user->image);
      $post->delete();

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

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();
        if(isset($posts))
        {
            $botUser = User::where('username', '=', 'bot')->get()->first();
            foreach($post as $post)
            {
                $post->user_id = $botUser->id;
                $post->save();
            }
            $user->delete();
        }
        else
        {
            $user->forceDelete();
        }
        Storage::delete($user->image);
        return redirect()->route('users.index')->with('flash_message', 'User successfully deleted');
  }
PHP

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.

Important:

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.

<?php

namespace App;

use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateDatabaseEloquentSoftDeletes;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

   // Rest of the codes....
}
PHP

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) {
            $table->increments('id');
            $table->string('fullname');
            $table->text('about')->nullable();
            $table->string('username')->unique();
            $table->string('image')->nullable();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->softDeletes();
            $table->timestamps();
        });
    }
PHP

Now you can refresh your database with

php artisan migrate:fresh
Markup

In laravel 5.5 or

php artisan migrate:refresh
PHP

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);
        $user->restore();
        return redirect()->route('users.index')->with('flash_message', 'User successfully restored');
    }
PHP

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

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

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>
PHP

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