Check If Laravel Model Got Saved or Query Got Executed

Check if laravel model got saved or query got executed

Check if model got saved

save() will return a boolean, saved or not saved. So you can either do:

$saved = $myModel->save();

if(!$saved){
App::abort(500, 'Error');
}

Or directly save in the if:

if(!$myModel->save()){
App::abort(500, 'Error');
}

Note that it doesn't make sense to call save() two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...

Check if query returned a result

first() will return null when no record is found so your check works find. However as alternative you could also use firstOrFail() which will automatically throw a ModelNotFoundException when nothing is found:

$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();

(The same is true for find() and findOrFail())

Check if query got executed

Unfortunately with create it's not that easy. Here's the source:

public static function create(array $attributes)
{
$model = new static($attributes);

$model->save();

return $model;
}

As you can see it will create a new instance of the model with the $attributes and then call save(). Now if save() where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)

if(!$newUser->id){
App::abort(500, 'Some Error');
}

Laravel Checking If a Record Exists

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}

In Laravel, is there a way to find out whether `firstOrCreate` created or if it found the row?

If you created the model in the current lifecycle, then the model's wasRecentlyCreated attribute will be set to true. Otherwise, that attribute will be set to false.

In other words, lets say you have a user with the email, bob@example.

$user = User::firstOrCreate(['email' => 'bob@example.com']);

// the below will dump out false because this entry already existed
var_dump($user->wasRecentlyCreated);

Now, lets say new@example.com doesn't exist.

$user2 = User::firstOrCreate(['email' => 'new@example.com']);

// the below will dump out true because this user was created
// in the current request lifecycle
var_dump($user2->wasRecentlyCreated);

What is the real query behind Laravel's Model::belongsTo() method?

You cant use the toSql() method to check query will run on laravel illuminate,

$sql = Person::query()->with('user')->find(1)->toSql();
dd($sql);

Laravel Check If Related Model Exists

In php 7.2+ you can't use count on the relation object, so there's no one-fits-all method for all relations. Use query method instead as @tremby provided below:

$model->relation()->exists()

generic solution working on all the relation types (pre php 7.2):

if (count($model->relation))
{
// exists
}

This will work for every relation since dynamic properties return Model or Collection. Both implement ArrayAccess.

So it goes like this:

single relations: hasOne / belongsTo / morphTo / morphOne

// no related model
$model->relation; // null
count($model->relation); // 0 evaluates to false

// there is one
$model->relation; // Eloquent Model
count($model->relation); // 1 evaluates to true

to-many relations: hasMany / belongsToMany / morphMany / morphToMany / morphedByMany

// no related collection
$model->relation; // Collection with 0 items evaluates to true
count($model->relation); // 0 evaluates to false

// there are related models
$model->relation; // Collection with 1 or more items, evaluates to true as well
count($model->relation); // int > 0 that evaluates to true

How to get the save query in Laravel?

toSql(); is for the model query builder. so that's why when you do $user->toSql(); you get select all statement.

you can do two things here

one, use DB::listen

    DB::listen(function ($query) {
echo $query->sql;
});
$user = New User;
$user->name = "test";
$user->mail = "test@example.com";
$user->save();

two, QueryLog if you need more details.

DB::enableQueryLog();
$user = New User;
$user->name = "test";
$user->mail = "test@example.com";
$user->save();
dd(DB::getQueryLog());

if you do not want to run the query, just wrap it with DB::pretend just like when you do migration adding --pretend, so that you will not migrate the DB you will get all the sql scripts.


DB::pretend(function () {
$user = New User;
$user->name = "test";
$user->mail = "test@example.com";
$user->save();
});

laravel . How can I judge the results of ORM

save() will return a boolean. So you can either do:

$saved = $example->save();

if(!$saved){
// something
}

Or directly save in the if:

if(!$example->save()){
// something
}


Related Topics



Leave a reply



Submit