Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a record is new in Laravel?

I recently started using Eloquent.

When I used PHP Active Record, there was a nice function that checked if a record was loaded from the database or is a new instance. Is there something similar in Eloquent that I could use?

By new I mean:

$article = new Article; 

whereas one from the database would be

$article = Article::find(1); 
like image 845
Craig Ward Avatar asked Aug 28 '13 21:08

Craig Ward


People also ask

How to check record exists in laravel?

The efficient way to check if the record exists you must use is_null method to check against the query. The code below might be helpful: $user = User::where('email', '=', Input::get('email')); if(is_null($user)){ //user does not exist... }else{ //user exists... }

How do I know if my data is saved in laravel?

Check if model got saved$myModel->save()) { App::abort(500, 'Error'); } //User got saved show OK message return Response::json(array('success' => true, 'user_added' => 1), 200);

What do you mean by dd () function?

dd stands for "Dump and Die." Laravel's dd() function can be defined as a helper function, which is used to dump a variable's contents to the browser and prevent the further script execution. Example: dd($array);


1 Answers

All laravel models have a ->exists property.

More specifically if the model is either loaded from the database, or has been saved to the database since being created the exists property will be true; Otherwise it will be false.

If you wish to know if the model has been modified since being grabbed from the database, or simply not saved at all (aka if it needs saving) then you can use the ->isDirty() function.

The Laravel API is a useful place for this kind of information: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_isDirty and often sheds far more light than the default documentation.

like image 158
Hailwood Avatar answered Oct 01 '22 02:10

Hailwood