Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model->save() returns false but no error

Normally when I call Model->save(), it creates the new record in the database successfully. I'm trying to debug a situation when nothing happens and Model->save() returns false. How do I find out what's happening?

$user = new User;
$user->fields = 'example';
$user->save(); // returns false

Running this does not show any insert queries.

dd(DB::getQueryLog());

But if I var_dump($user), I correctly get all the fields properly saved in the object.

Thanks!

like image 425
Lyon Avatar asked Apr 20 '15 23:04

Lyon


People also ask

What does Laravel save () return?

Laravel Model->save() returns false but no error. Bookmark this question. Show activity on this post. Normally when I call Model->save() , it creates the new record in the database successfully.

How do I save a model in Laravel?

Laravel Model::create or Model->save()$product = new Product(); $product->title = $request->title; $product->category = $request->category; $product->save();

What is difference between create and save in Laravel?

Save can be used to both create a new Record and update a existing record . Whereas create is used to create a new record by providing all required field at one time .

How do you check record is inserted or not in Laravel?

Check if query got executed$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);


2 Answers

To get the insert queries when $user->save(); error, you can try to catch the exception like this:

    try{
       $user = new User;
       $user->fields = 'example';
       $user->save(); // returns false
    }
    catch(\Exception $e){
       // do task when error
       echo $e->getMessage();   // insert query
    }

Hope this helps :)

like image 130
Eng Cy Avatar answered Oct 18 '22 05:10

Eng Cy


I know it's already answered, but in case someone else needs a different approach, I was able to see the $model->save() error with the underappreciated component of Laravel: tinker

php artisan tinker
$old = \App\Model\User::find(1);
$new = $old->replicate();
$new->save();

Then I was able to see the error:

Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'relations' in 'field list' (SQL: insert into temp_users (...

like image 35
Ivan Avatar answered Oct 18 '22 04:10

Ivan