user2094178
user2094178

Reputation: 9454

Detect if model is being created or updated inside a method

In my BaseModel which extends Eloquent I have the validate method.

My question is, how can I detect inside this method if the model is being created or updated?

I'm aware and I use the model events, but can't figure out how to achieve the same inside methods.

Upvotes: 0

Views: 103

Answers (2)

mpj
mpj

Reputation: 5367

You could see if the attributes are already set in that model using getOriginal().

Depending on what you get, you can know if it's a new model or an existing one.


getOriginal() docs:

http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Model.html#2114-2124

Upvotes: 0

Anam
Anam

Reputation: 12189

Laravel has a method called exists() to check whether a model is from database or not.

if Model created or updated, the following will return true.

$model->exists

update a model:

$affectedRows = User::where('votes', '>', 100)->update(array('status' => 2));

dd($affectedRows);

Reference:

http://laravel.com/docs/eloquent#insert-update-delete

Upvotes: 1

Related Questions