Framework: update model after sync relation

Created on 12 Apr 2016  路  9Comments  路  Source: laravel/framework

Hi
example from Doc:
user has roles with id : 4,5,6

$user = App\User::find(1);
$user->roles()->detach();
$user->toArray();

so if you use $user->toArray() it return an array with all previous roles!
this behavior is true after $user->roles()->sync([1,2,3]) too.
Please help me to update my model after sync.
thanks

Most helpful comment

Remember that $user->fresh() does not update the existing model. It returns a new model, so you'll need to do $user = $user->fresh() if you will use the $user variable again.

All 9 comments

you probably should just do $user = $user->fresh()before calling $user->toArray();
(edited from @iget-master's comment)

see: https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_fresh

that being said, this is probably not a bug :)

Remember that $user->fresh() does not update the existing model. It returns a new model, so you'll need to do $user = $user->fresh() if you will use the $user variable again.

good catch!

Thanks :-)
and a question:
Whats parameter of this function? ( array|string $with = array())
thanks a lot

from the source:

    /**
     * Reload a fresh model instance from the database.
     *
     * @param  array|string  $with
     * @return $this|null
     */
    public function fresh($with = [])
    {
        if (! $this->exists) {
            return;
        }
        $key = $this->getKeyName();
        return static::with($with)->where($key, $this->getKey())->first();
    }

It looks like you can pass a relation to reload with the model as well, so for ex. if your User has a child model called Badge, and in your user model you've specified:

public function badges()
{
    return $this->hasMany('App\Badge');
}

It _seems_ like you can do $user = $user->fresh('badges'); to load the badges along with a refreshed user model. You could also do $user = $user->fresh(['badges', 'comments']);

Haven't tested it myself though. You might want to try playing with php artisan tinker :dancers:

It works! Thanks a lot :-)

@heisian and @iget-master are ok, you need to refresh your object and assign to itself, but very important, if you want to retrieve the roles relationship, you have to say that to the fresh method like this:

$user = App\User::find(1);
$user->roles()->detach();
$user = $user->fresh('roles');
$user->toArray();

The fresh method can receive an string defining a relationship to retrieve also, or an array with relationships like this:

$user = $user->fresh(array('roles', 'relationship_2'));

Regards!

Isn't that exactly what I put in my answer.. already?

I didn't see that ..sorry :-P

Was this page helpful?
0 / 5 - 0 ratings

Related issues

progmars picture progmars  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments

YannPl picture YannPl  路  3Comments

lzp819739483 picture lzp819739483  路  3Comments

JamborJan picture JamborJan  路  3Comments