use soft delete laravel code example

Example 1: force delete soft delete laravel

Soft Delete : $user->delete();
Force Delete : $user->forceDelete();
Restore Soft Deleted Item : $user->restore();

Example 2: softdeletes laravel

class Clientes extends Model{    use SoftDeletes;    protected $dates = ['deleted_at'];}

Example 3: laravel soft delete

/** in migrations this changes need to
    add for table we want to add soft delete (LARAVEL)*/

	/** The migrations. START */
	public function up()
	{
		Schema::table('users', function(Blueprint $table)
		{
			$table->softDeletes();
		});
	}
	/** The migrations. END */

	/** after adding softdelete you need to
    point that column in table related model (LARAVEL)*/

	/** The Model. START */
  	use Illuminate\Database\Eloquent\SoftDeletes;
  	class User extends Model {
	  use SoftDeletes;
	  protected $dates = ['deleted_at'];
	}
	/** The Model. END */

Example 4: apply soft delete by custom laravel

Inside Migrations : 
=====================
  
public function up()
{
  Schema::create('users', function (Blueprint $table) {
	.........
    .........
    $table->timestamp('deleted_at')->nullable();
   	...........
  });
}

Inside Models : 
=================

class User extends Authenticatable
{  
  ..........
  protected static function boot()
  {
    parent::boot();
    static::addGlobalScope(new CustomSoftDeleteScope);
  }
  .......
}

Add a global scope file :
==========================
  
<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class CustomSoftDeleteScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \Illuminate\Database\Eloquent\Model $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->whereNull('deleted_at');
    }
}

Tags:

Php Example