I'm relearning Laravel with laravel 7 and have hit an issue where I'm unable to query a record in my database table. So instead of a call like $test = Test::find_by_id_and_name(1, 'test 1'); (and also $test = Test::where('id', 1); returning a class of Illuninate\Database\Eloquent\Model it returns a class of Illuminate\Database\Eloquent\Builder.
I have created a Migration for a table called Tests and seeded it with a few rows of test data. The Test Model in App is as follows
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Test extends Model
{
protected $guarded = [];
use SoftDeletes;
}
the Migration is:
se Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTestsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tests', function (Blueprint $table) {
$table->id();
$table->string( 'name' );
$table->string( 'url', 255 );
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tests');
}
}
So anyone any idea why I'm not getting the Model I need so i can do for instance a dd($test); and see the values stored in the database for the row with the id of 1? or even do an echo($test->name); and see the name of this item?
thanks
* ADDITIONAL *
Should of pointed out my initial code had Test::find_by_id_and_name(1, 'test 1'); but this didn't work and throw an exception about finding the class. I modified if with where and above was a typo as it was where( 'id', 1 ); (I've corrected the code using my initial find_by code). Adding a get() or any other thing now returns null. I have verified that the database contains the table tests and that an item with the id and name of 'test 1' exists
* RESULT *
The underlying issue in the end was the data, the url had https::// in it (additional colon) so indeed it would return null. Thanks guys helped me find the reason.
Misunderstanding of query builder vs models in Laravel. Check doc for reference.
Calling query builder method statically on a model returns a builder.
User::where('id', 1); // returns builder
To resolve a query builder you can either use get() or first().
User::where('id', 1)->get(); // Returns a collection of users with 1 element.
User::where('id', 1)->first(); // Returns one user.
You can also fetch the user out of the collections this is not recommended as you might as well just call first().
User::where('id', 1)->get()->first(); // Returns collection fetches first element that is an user.
Laravel has static methods for finding models by id.
User::find(1); // returns user or null
User::findOrFail(1); // returns user or exception
Try to use the following
$test = Test::find(1);
Then you will get the record,
Related
I have a model called Tree that is supposed to be associated to 1..n Things. Things can be associated to 0..n things. In other words this is a many-to-many relationship, and a Thing must be chosen when a Tree is being created. My thing_tree migration looks like this (there's also a thing_thing pivot table but that's irrelevant):
public function up()
{
Schema::create('thing_tree', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->unsignedBigInteger('tree_id')->nullable();
$table->unsignedBigInteger('thing_id')->nullable();
$table->unique(['tree_id', 'thing_id']);
$table->foreign('tree_id')->references('id')->on('trees')->onDelete('cascade');
$table->foreign('thing_id')->references('id')->on('things')->onDelete('cascade');
});
}
My Tree model looks like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tree extends Model
{
use HasFactory;
protected $guarded = [];
public function path(){
$path = '/trees/' . $this->id;
return $path;
}
public function associatedThings () {
return $this->belongsToMany(Thing::class);
}
}
The Thing model looks like this:
public function trees()
{
return $this->belongsToMany(Tree::class);
}
public function parentOf (){
return $this->belongsToMany(Thing::class, 'thing_thing', 'parent_id', 'child_id');
}
public function childOf(){
return $this->belongsToMany(Thing::class, 'thing_thing', 'child_id', 'parent_id');
}
Finally, the Tree Nova resource has these fields:
public function fields(Request $request)
{
return [
ID::make(__('ID'), 'id')->sortable(),
Text::make('name'),
ID::make('user_id')->hideWhenUpdating()->hideWhenCreating(),
Boolean::make('public'),
BelongsToMany::make('Things', 'associatedThings')
];
}
It should not be possible to create a Tree without an attached Thing, but the creation screen looks like this:
How do I require this in Nova?
This is not possible through nova's default features. Here is how I would go about it with the least effort (you Might want to create a custom field for that yourself) - or at least how I solved a similar issue in the past:
1. Add the nova checkboxes field to your project
2. Add the field to your nova ressource :
// create an array( id => name) of things
$options = Things::all()->groupBy('id')->map(fn($e) => $e->name)->toArray();
// ...
// add checkboxes to your $fields
Checkboxes::make('Things', 'things_checkboxes')->options($options)
3. Add a validator that requires the things_checkboxes to be not empty
4. Add an observer php artisan make:observer CheckboxObserver that will sync the model's relations with the given id-array through the checkboxes and then remove the checkboxes field from the object (as it will throw a column not found otherwise), so something like this:
public function saving($tree)
{
// Note: In my case I would use the checkbox_relations method of the HasCheckboxes trait and loop over all checkbox relations to perform the following and get the respective array keys and relation names
$available_ids = array_unique($tree['things_checkboxes']);
// Attach new ones, remove old ones (Relation name in my case comes from the HasCheckboxes Trait)
$tree->things->sync($available_ids);
// Unset Checkboxes as the Key doesn't exist as column in the Table
unset($tree['things_checkboxes']);
return true;
}
5. Add the same thing in reverse for the retreived method in your observer if you want to keep using the checkboxes to handle relations. Otherwise, add ->hideWhenUpdating() to your checkbox field
I added a trait for that to easily attach the relations through checkboxes to a model:
trait HasCheckboxRelations
{
/**
* Boot the trait
*
* #return void
*/
public static function bootHasCheckboxRelations()
{
static::observe(CheckboxObserver::class);
}
/**
* Defines which relations should be display as checkboxes instead of
* #return CheckboxRelation[]
*/
public static function checkbox_relations()
{
return [];
}
}
And checkbox_relations holds an array of instances of class CheckboxRelation which again holds informations about the key name, the relation name and so on.
public function __construct(string $relationName, string $relatedClass, string $fieldName, bool $hasOverrides = false, string $relationType = null, array $_fields = [])
Also, I added a method attachCheckboxRelationFields to the default nova resource which will be called on the $fields when the model uses the trait.
Now, I only have to add HasCheckboxRelations to a model, add the array of checkbox_relations and thats it - I have a belongsToMany relation on the nova resource through checkboxes. Of course you don't have the option to manage pivot fields anymore if you go for it this way - which might be why it was not done by the nova devs - but for simple belongsToMany relations I really like to work with the checkbox solution instead of the default attach-table. And for data with pivot fields you can still use the default way.
Also note that parts of the code where written on the fly so it might not work out of the box, but the overall idea should be delivered.
Hope it helped!
alternative
https://github.com/Benjacho/belongs-to-many-field-nova
BelongsToManyField::make('Role Label', 'roles', 'App\Nova\Role'),
I have three relational table attached below.
https://drive.google.com/file/d/1q1kdURIwFXxHb2MgdRyBkE1e3DMug7r-/view?usp=sharing
I have also three separate models where defined relation among all of my table's.I can read the City Model's information from Country model using hasManyThrough() relation But cannot read the Country information from City model. I have tried to retrieve City model's using ``hasManyThrough``` but didn't get result (attached as commented country method ). Please read my model and it's relational method here..
Is there someone to help me for getting City model's information using Eloquent method hasManyThrough / hasManyThrough or using inverse of hasManyThrough / hasManyThrough ?
01.
<?php
namespace App\Hrm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Country extends Model
{
//use SoftDeletes;
protected $fillable = ['name','description','status'];
public function districts(){
return $this->hasMany(District::class);
}
public function cities(){
return $this->hasManyThrough(City::class,District::class);
}
}
02.
<?php
namespace App\Hrm;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class District extends Model
{
//use SoftDeletes;
protected $fillable = ['country_id','name','description','status'];
public function country(){
return $this->belongsTo(Country::class);
}
public function cities(){
return $this->hasMany(City::class);
}
}
3.
namespace App\Hrm;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class City extends Model
{
//use SoftDeletes;
protected $fillable = ['district_id','name','description','status'];
public function district(){
return $this->belongsTo(District::class);
}
// public function country(){
// return $this->hasOneThrough(Country::class, District::class);
// }
Doesn't look like there is a native way to define the inverse of a "hasManyThrough" relationship yet in Laravel. There have been a few issues opened on github to request it, but they were closed.
You could use the staudenmeir/belongs-to-through package if you don't mind installing a third-party package for this functionality. Then you should be able to define a belongsToThrough relationship like this:
class City extends Model
{
use \Znck\Eloquent\Traits\BelongsToThrough;
public function country() {
return $this->belongsToThrough(Country::class, District::class);
}
}
Why can't use parent method?
$city = City::find(1);
$country = $city->district->country();
i just had a similar situation i was able to accomplish a belongsToThrough with hasOneThrough
public function country()
{
return $this->hasOneThrough(
Country::class, // model we are trying to get
District::class, // model we have an _id to
'id', // WHERE `district`.`id` = `city`.`district_id`
'id', // `countries`.`id`
'district_id', // local column relation to our through class
'country_id' // `district`.`country_id`
);
}
what this should generate is
SELECT * FROM `countries`
INNER JOIN `districts`
ON `districts`.`country_id` = `countries`.`id`
WHERE `districts`.`id` = ?
-- ? == city.district_id
Database structure:
City:
id: increments
district_id: integer
...
Country:
id: increments
...
District:
id: increments
country_id: integer
...
we can then do $city->country
note: i have not fully tested this but with the testing that i have done it 'works'
Edit: i originally thought that i needed to leave the localKey
parameter null otherwise the relation wont work. it turns out i didnt
fully understand what that column was doing and that was wrong. That
key is the local column that relates to our through column (unless i
still have more to learn/figure out), when left the value as null, it
would use the local id column which a. is the wrong value, b. can also
be out of range (which is how i discovered it was using the wrong
value)
in my testing i only had two rows, both with the same relations. what
i didnt realize though was that on the "through table" both row 1 and
2 and the same related (relation where are trying to reach) so i didnt
notice the issue right away. hopefully now its all working
I come here cause i have an issue with Eloquent relations One To Many, i've tested a lot since a week now but nothing to do. I try here for my last chance, after this, i will try Database: Query Builder, but i will prefer to perform my code with Eloquent.
To make simple, i want to show the differents furnitures use with the id task, so a task hasMany furnitures.
So i give you the problem, i made the relation into my model, when i call the function HasMany, it's returned to me an empty object...
I use php artisan tinker on git bash but after a thousand of try, it's not working.
I show you my try with GitBash and after my code.
When i do this ">>> $comments = App\BonIntervention::find(2003);"
Tinker show me the right thing, the id "2003" to my Table related to my model, with all his components. But when i do this after:
"$comment = $comments->bonInterventionFournitures"
I'have this answer "Illuminate\Database\Eloquent\Collection {#810
all: [],
}"
And for a lot of try with different name/method his always the same, like my table are empty, but they're not....
Here you have my model for the "task", When i read the doc Laravel eloquent HastoMany, it appears that you can pass to the return, for the first parameter the namespace, for the second parameter the foreign key of the table, and for third parameter the primary key. So i did like this, i hope i didn't mistake myself.
namespace App;
use Illuminate\Database\Eloquent\Model;
class BonIntervention extends Model
{
protected $primaryKey = 'Id_TTa';
protected $table = 'T_Taches';
public $timestamps = false;
public function bonInterventionFournitures(){
return $this->hasMany('App\BonInterventionFournitures', 'Id_TTa', 'Id_TTaDFo');
}
}
Now it's the model for furnitures. (Same method for the parameters in the return)
namespace App;
use Illuminate\Database\Eloquent\Model;
class BonInterventionFournitures extends Model
{
protected $table = 'T_Taches_Details_Fournitures';
protected $primaryKey = 'Id_TTaDFo';
public function bonInterventions(){
return $this->belongsTo('App\BonIntervention', 'Id_TTa', 'Id_TTa');
}
}
I can show you my migrations for this table.
First, the table task (i not show you the entire table, because it's a lot of information.
public function up()
{
Schema::create('T_Taches', function(Blueprint $table)
{
$table->integer('Id_TTa', true);
$table->string('Responsable_TCa')->nullable()->index('Responsable_TCa');
$table->dateTime('Date_TTa')->nullable()->default('0000-00-00 00:00:00');
$table->string('Ste_TCl')->nullable()->index('Ste_TCl');
$table->string('Ste_Utl')->nullable()->index('Ste_Utl');
$table->string('Adr_Liv_TCl')->nullable()->index('Adr_Liv_TCl');
$table->string('Contact_TCo')->nullable()->index('Contact_TCo');
$table->string('Collaborateur_TCa')->nullable()->index('Collaborateur_TCa');
$table->string('NDevis_TDv')->nullable()->index('NDevis_TDv');
$table->string('Devis_Type_TTa')->nullable();
$table->string('NCommande_TDv')->nullable()->index('NCommande_TDv');
$table->dateTime('Date_Debut_TTa')->nullable();
$table->dateTime('Date_Fin_TTa')->nullable();
$table->dateTime('Date_Demande_TTa')->nullable();
Now the furnitures table
public function up()
{
Schema::create('T_Taches_Details_Fournitures', function(Blueprint $table)
{
$table->integer('Id_TTaDFo', true);
$table->integer('Id_TTa')->nullable()->index('Id_TTa');
$table->string('Class_TTaDFo')->nullable();
$table->string('Des_TTaDFo')->nullable();
$table->string('Ref_TTaDFo')->nullable();
$table->float('Qte_TTaDFo', 10, 0)->nullable()->default(0);
$table->float('PAHT_TTaDFo', 10, 0)->nullable()->default(0);
$table->float('Tx_Mge_TTaDFo', 10, 0)->nullable()->default(1.5);
$table->float('Vente_HT_TTaDFo', 10, 0)->nullable()->default(0);
});
}
I hope you understand my question, and thanks all for watching.
SOLVED
I solved this and i explain why on the answer, after my post.
I've found the solution. In fact in my models i erase the second and third parameters.
return $this->belongsTo('App\BonIntervention', 'Id_TTa', 'Id_TTa');
return $this->hasMany('App\BonInterventionFournitures', 'Id_TTa', 'Id_TTaDFo');
I just add the second parameter in my return hasMany, just like this
return $this->hasMany('App\BonInterventionFournitures', 'Id_TTa');
return $this->belongsTo('App\BonIntervention');
Now with artisan tinker when i do this
$comments = App\BonIntervention::find(2003);
$comment = $comments->bonInterventionFournitures;
I find the right answer.
I'm trying to create tables that will have a primary key which is a UUID defined as binary(16) instead of the default auto-incrementing id field.
I've managed to create migrations using raw SQL statements though DB::statement like so:
DB::statement("CREATE TABLE `binary_primary_keys` (
`uuid` binary(16) NOT NULL DEFAULT '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;");
However, I have trouble getting the model working. I've followed the tutorial available here. I've defined my model like so:
class UuidModel extends Model
{
public $incrementing = false;
public $primaryKey = 'uuid';
/**
* The "booting" method of the model.
*
* #return void
*/
protected static function boot()
{
parent::boot();
/**
* Attach to the 'creating' Model Event to provide a UUID
* for the `id` field (provided by $model->getKeyName())
*/
static::creating(function ($model) {
$model->{$model->getKeyName()} = (string)$model->generateNewId();
echo($model->{$model->getKeyName()});
});
}
/**
* Get a new version 4 (random) UUID.
*/
public function generateNewId()
{
return Uuid::generate();
}
}
where Uuid is an alias to Webpatser\Uuid.
One problem, I'm having is I cannot derive UuidModel from Eloquent as explained in the tutorial. In fact I don't see an Eloquent class. I'm deriving from Model instead. I am guessing the tutorial was written in Laravel 4.
I would appreciate help in implementing tables with UUIDs as primary keys in Laravel 5.
EDIT 1:
So, if I define my class like so:
use Illuminate\Database\Eloquent
class UuidModel extends Eloquent { ... }
I get the following error:
PHP Fatal error: Class 'Illuminate\Database\Eloquent' not found in /home/vagrant/transactly/app/UuidModel.php on line 8
If I remove the use Illuminate\Database\Eloquent line, I get the following error:
PHP Fatal error: Class 'App\Eloquent' not found in /home/vagrant/transactly/app/UuidModel.php on line 8
Edit 2:
I have discovered that the static::creating event is never called for when instances of UuidModel are created.
I tried setting up the creating event listener in AppServiceProvider but that's not being called as well. Interestingly, the creating event is not called for a regular Laravel generated model User either.
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
/**
* Attach to the 'creating' Model Event to provide a UUID
* for the `id` field (provided by $model->getKeyName())
*/
echo "Booting...\n";
UuidModel::creating(function ($model) {
echo "Creating Uuid Model...\n";
$model->{$model->getKeyName()} = (string)$model->generateNewId();
});
User::creating(function($user){
echo "Creating User Model...";
$user->name = 'Forced Name in boot()';
});
}
public function register(){}
}
How about this idea for storing a 36chr UUID as Binary(16) :
IMO there is an advantage in not having Laravel generating the UUID. Namely, if new records (some day in the future) get inserted into the database from outside the application the UUID field is properly populated.
My suggestion: Create a UUID default value trigger using migrations
(this trigger makes the DataBase server do the work to generate the UUID each time a new customer is inserted)
<?php namespace MegaBank\HighInterestLoans\Updates;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class MigrationTriggerForCustomers extends Migration
{
public function up()
{
DB::unprepared('CREATE TRIGGER before_insert_customers
BEFORE INSERT ON
`megabank_highinterestloans_customers`
FOR EACH ROW
SET new.uuid = UNHEX(REPLACE(UUID(), "-","");');
}
public function down()
{
DB::unprepared('DROP TRIGGER `before_insert_customers`');
}
}
Finally, if you want to get a human-readable version of your UUID just do the following:
SELECT HEX(UUID) FROM customers;
Anyway, hope this helps someone :-)
So, I got the thing working like a charm (not tested unit testing):
class UuidModel extends Eloquent is an older (Laravel 4) construct. We use class UuidModel extends Model in Laravel 5
The solution was to move the
UuidModel::creating(function ($model) {
echo "Creating Uuid Model...\n";
$model->{$model->getKeyName()} = (string)$model->generateNewId();
});
from AppServiceProvider::boot() to EventServiceProvider::boot(). No other changes were required. Everything worked as expected.
I still don't know why (2) works in EventServiceProvider and not in AppServiceProvider as explained in the official docs. But judging from the name, that's perhaps the way it was meant to be.
This is a quick solution without using events.
UUidModel.php
<?php namespace App;
use \Illuminate\Database\Eloquent\Model;
use \Illuminate\Database\Eloquent\Builder;
class UuidModel extends Model
{
/**
* Insert the given attributes and set the ID on the model.
*
* #param \Illuminate\Database\Eloquent\Builder $query
* #param array $attributes
* #return void
*/
protected function insertAndSetId(Builder $query, $attributes)
{
$keyName = $this->getKeyName();
$id = $attributes[$keyName] = $this->generateNewId();
$query->insert($attributes);
$this->setAttribute($keyName, $id);
}
/**
* Get a new version 4 (random) UUID.
*/
public function generateNewId()
{
return 'uuid!!' ;// just for test
}
}
?>
Model Example Car.php
<?php namespace App;
class Car extends UuidModel {
}
also try use this package will automatically generate and assign UUID field in your model, also can show and update by UUIDs key.
https://github.com/EmadAdly/laravel-uuid
in our project we must be use soft delete for each posts. in laravel document i think we can only use this feature for tables.
can we use that for posts on table such as
$id = Contents::find($id);
$id->softDeletes();
Updated Version (Version 5.0 & Later):
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model {
use SoftDeletes;
protected $table = 'posts';
// ...
}
When soft deleting a model, it is not actually removed from your
database. Instead, a deleted_at timestamp is set on the record. To
enable soft deletes for a model, specify the softDelete property on
the model (Documentation).
For (Version 4.2):
use Illuminate\Database\Eloquent\SoftDeletingTrait; // <-- This is required
class Post extends Eloquent {
use SoftDeletingTrait;
protected $table = 'posts';
// ...
}
Prior to Version 4.2 (But not 4.2 & Later)
For example (Using a posts table and Post model):
class Post extends Eloquent {
protected $table = 'posts';
protected $softDelete = true;
// ...
}
To add a deleted_at column to your table, you may use the softDeletes
method from a migration:
For example (Migration class' up method for posts table) :
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function(Blueprint $table)
{
$table->increments('id');
// more fields
$table->softDeletes(); // <-- This will add a deleted_at field
$table->timeStamps();
});
}
Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results. To soft delete a model you may use:
$model = Contents::find( $id );
$model->delete();
Deleted (soft) models are identified by the timestamp and if deleted_at field is NULL then it's not deleted and using the restore method actually makes the deleted_at field NULL. To permanently delete a model you may use forceDelete method.
You actually do the normal delete. But on the model you specify that its a softdelete model.
So on your model add the code:
class Contents extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
Then on your code do the normal delete like:
$id = Contents::find( $id );
$id ->delete();
Also make sure you have the deleted_at column on your table.
Or just see the docs: http://laravel.com/docs/eloquent#soft-deleting
I just did this with Laravel 8 and it worked. It's basically what #The alpha said, but trying to wrap everything quicker. Follow this steps.
In the migration file add:
$table->softDeletes();
In the model:
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
...
];
}
In the controller:
$user->delete();
Bonus: if you need to restore the deleted user
User::withTrashed()->find($id);->restore();
Just an update for Laravel 5:
In Laravel 4.2:
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Post extends Eloquent {
use SoftDeletingTrait;
protected $dates = ['deleted_at'];
}
becomes in Laravel 5:
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
protected $dates = ['deleted_at'];
In Laravel 5.5 Soft Deleted works ( for me ).
Data Base
deleted_at Field, default NULL value
Model
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model {
use SoftDeletes;
}
Controller
public function destroy($id)
{
User::find($id)->delete();
}
In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task.
In Model, inside the class just write 'use SoftDeletes'. Example
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Model
{
use SoftDeletes;
}
And In Controller, you can do deletion. Example
User::where('email', 'youremail#example.com')->delete();
or
User::where('email', 'youremail#example.com')->softDeletes();
Make sure that you must have 'deleted_at' column in the users Table.
Here is the details from laravel.com
http://laravel.com/docs/eloquent#soft-deleting
When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record. To enable soft deletes for a model, specify the softDelete property on the model:
class User extends Eloquent {
protected $softDelete = true;
}
To add a deleted_at column to your table, you may use the softDeletes method from a migration:
$table->softDeletes();
Now, when you call the delete method on the model, the deleted_at column will be set to the current timestamp. When querying a model that uses soft deletes, the "deleted" models will not be included in query results.