Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent
Last updated 2 years ago.
0

Hmm...there is an updateOrCreate method.

/**
 * Create or update a related record matching the attributes, and fill it with values.
 *
 * @param  array  $attributes
 * @param  array  $values
 * @return \Illuminate\Database\Eloquent\Model
 */
public function updateOrCreate(array $attributes, array $values = [])
{
    $instance = $this->firstOrNew($attributes);

    $instance->fill($values);

    $instance->save();

    return $instance;
}

I believe for this method, the first argument is for any matching attributes. The second argument is for the new values so you might able to do something like this.

$order->location()->updateOrCreate([], $arrayOfData);
Last updated 9 years ago.
0

Thanks for the info @thomastkim. I couldn't get that to work, my model is using a hasOne relationship which returns a HasOne class object, which is en extention of the base Relation class, which doesnt have the updateOrCreate method. Infact I couldnt find that method you posted anywhere in the laravel source. I am working with 4.2.

I was able to get close to what I am looking for by grabbing the related model directly,

// This will create the new row successfully
$order->location()->getRelated()->updateOrCreate(['data']);

// However the order still isn't aware of the new related row
var_dump($order->location);
// This outputs NULL even though the related row was created

// The only way to get the newly added location is to go
$location = $order->find(1)->location;
// This is an unnecessary database call

Last updated 9 years ago.
0

I was able to figure it out by looking at the laravel 5 source code and the function you provided @thomastkim! Thanks!

For anyone interested,


$order->setRelation(
    'location',
    $order->location()
        ->getRelated()
        ->updateOrCreate(['data'], ['data'])
);

Last updated 9 years ago.
0

That is weird. HasOne extends HasOneOrMany, which does have the function.

But glad you got it to work! :)

0

Sign in to participate in this thread!

Eventy

Your banner here too?

calebfavor calebfavor Joined 17 Sep 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.