Framework: All attributes instead of explicitly defined ones

Created on 23 Apr 2017  路  6Comments  路  Source: laravel/framework

  • Laravel Version: 5.4.19
  • PHP Version: 7.1
  • Database Driver & Version: MySQL 5.7.17

Description:

Model X has 3 attributes (id, user_id, and stage), the stage column has a default value, so I don't define it explicitly. After a successful insertion, the $model variable doesn't have the stage attribute! but those explicitly defined (id and user_id).

Steps To Reproduce:

$model = new X();
$model->user()->associate($user);
$model->save();

dd($model);

All 6 comments

As a workaround, defining default values for attributes:

$attributes = ['stage' => 'pending'];

It's good to return all attributes instead of any workarounds.

This is not a bug. Open an issue on the laravel/internals repo (for a proposal)

Some sgbd have a RETURNING statements on SQL query, but others like MySQL don't. So you would have to query (select) the row again.

I think you could use $user->fresh()

@caiquecastro fresh() method does what I need, thanks. Why not make a new refresh by default after each insertion?

@meNESS Because some applications don't want another SELECT query after the INSERT because you may not need the 'fresh' model after insertion. Making less queries is preferred over making more queries, hence why it is not default.

Because some applications don't want another SELECT query after the INSERT because you may not need the 'fresh' model after insertion

Exactly, it's up to the developer to use the existing instance or fetch a new one from the DB.

Closing then, thanks everyone.

Was this page helpful?
0 / 5 - 0 ratings