Check if laravel model got saved or query got executed
Asked Answered
C

4

47

I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.

And also can I check if the queries bellow got executed like this

Check if model got saved

Eg:

$myModel = new User();

$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');

$myModel->save();

//Check if user got saved
if ( ! $myModel->save())
{
  App::abort(500, 'Error');
}

//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);

Is the above a safe way to check whenever my model got saved or not?

Check if query returned a result

Eg:

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

if (! $UserProduct)
{
    App::abort(401); //Error
}

Does above return an error if no product where found?

Check if query got executed

Eg:

$newUser = User::create([
        'username' => Input::get('username'),
        'email' => Input::get('email')
]);

//Check if user was created
if ( ! $newUser)
{
    App::abort(500, 'Some Error');
}


//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);

Does above check if a user was created?

Crawford answered 10/1, 2015 at 15:40 Comment(0)
N
77

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');
}
Nevers answered 10/1, 2015 at 15:55 Comment(2)
Thanks! So I can use $newUser = User::create([values..]) then use $newUser->id to check if it got inserted?Crawford
Yes. Unless you are setting the id manually, it will null until the data is successfully inserted in your db.Nevers
A
32

You can also check the public attribute $exists on your model.

if ($myModel->exists) {
    // Model exists in the database
}
Anticlerical answered 5/4, 2017 at 9:2 Comment(2)
this is testing if the object exists on the DB not if it was saved (right now)Nicholenicholl
@GabrielFernandez That's what I was looking for when Google landed me here.Gunsel
I
19

I would do such move to when I use Model::create method :

$activity = Activity::create($data);

if ($activity->exists) {
   // success
} else {
   // failure 
}

As for the Save method it's easier because $model->save() returns Bool :

$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();

if ($is_saved) {
    // success
} else {
    // failure 
}
Illusionism answered 17/6, 2017 at 4:13 Comment(1)
If a user tries to insert a dup val then an exception will be thrown before returning the create. Then no point of checking the response. you will have to handle the exception first.Wessex
R
0
/**
 * Store a newly created country in storage.
 *
 * @url /country
 * @method POST
 * @param Request $request
 * @return \Illuminate\Http\JsonResponse
 */
public function store(Request $request)
{
  # Filer & only get specific parameters.
  $request = $request->only('code', 'name', 'status');

  # Assign login user(Auth Control).
  $request['created_by'] = Auth::user()->id;

  # Insert data into `countries` table.
  $country = Country::create($request);

  if(!$country)
    throw new Exception('Error in saving data.');
}
Reedreedbird answered 10/1, 2015 at 15:40 Comment(1)
Are you sure @ShankaSMS that $country does mean that the country successfully inserted ? the create method returns an instance of the model but it does not say or confirm it has been persisted in the database .Illusionism

© 2022 - 2024 — McMap. All rights reserved.