schellingerht
schellingerht

Reputation: 5806

PHP 5.5 : how to convert array with 1 element to property of parent

I have this:

$foo = Foo::getFooById(100);

public static function getFooById($id)
{
    return Foo::where('id', $id)->with('locations')->firstOrFail();
}

This returns an Eloquent collection.

$foo gives now the following properties:

$foo->name
$foo->locations

$foo->locations is an array with always 1 element

Just I want:

$foo->location = $foo->locations[0];
unset($foo->locations);

This code works, but is very terrible, because it happens on different places. How can I do this in a clear way?

Upvotes: 0

Views: 55

Answers (1)

Simba
Simba

Reputation: 5032

You haven't shown it, but I assume you've defined Foo as having a one-to-many relationship with locations.

If there is always just a single location for any given Foo, then you should define it with a one-to-one relationship rather than one-to-many, then you'll be able to say $foo->location to get the single location object rather than $foo->locations to get an array of them.

In other words, I guess you have code in your Foo model that looks like this:

public function locations()
{
    return $this->hasMany('locations');
}

You need to replace it with something more like this:

public function location()
{
    return $this->hasOne('locations');
}

Then change with('locations') in your query function to with('location').

Upvotes: 1

Related Questions