0

Is exist a possibility to easy get relation value in Laravel 5? Here an example of what i need:

I have model Book and i have author relation to model Author. Author also have relation country to model Country. I need to show on book page country name of Author. I can easy wrote:

echo $model->author->country->name

But what if a author of book not provided or we don't know author coutry? I will got a notice.

So I need to add additional checkings:

if ($model->author && $model->author->country) echo $model->author->country->name

Maybe exists some method in laravel, which simplify getting a value? Maybe something like SomeHelperClass::getValue($model, 'author.country.name'), so if some part of the chain is null, then method also returns null. Thanks.

5
  • Why dont you add a method $Book->countryName() to the Book were it checks the author if exist return the country name if not return null or empty string. In other words: Wrap the logic of retrieving the country name in that method Commented Apr 23, 2016 at 13:08
  • @DavidLavieri because i have a lot of similar situations and wrap each checking into separate method isn't wise desicion. Commented Apr 23, 2016 at 13:46
  • SomeHelperClass::getValue($model, 'author.country.name') would be as well wrappers and checking or actually queries to database behind the covers, probably even more messy since laravel abstractions are so... abstracts Commented Apr 23, 2016 at 13:56
  • @DavidLavieri you can check my answer and use the solution in future. Cheers. Commented Apr 26, 2016 at 8:12
  • there is more complexity behind it. But I guess is fine if operation and time complexity is not a matter for you Commented Apr 26, 2016 at 17:53

1 Answer 1

1

Sorry for answering my own question. Anyway:

Laravel 5.1 has helper function array_get, which works similar to what i want. But problem is that function works only with arrays. So i need to eager load all required data and convert object to an array:

$model = Book::with('author.country')->findOrFail($id);
$country_name = array_get($model->toArray(), 'author.country.name');
// or
$country_name = object_get($model, 'author.country.name');
Sign up to request clarification or add additional context in comments.

2 Comments

Then object_get($model, 'nested.relation.field') also will do
Stack Overflow encourages self answers: stackoverflow.com/help/self-answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.