Home > Back-end >  Laravel 8 Dynamic relationships
Laravel 8 Dynamic relationships

Time:01-04

I'm using Laravel 8. I have relationships strings but I don't how to load the relationships inside a loop. I'd like to explode() my relationships on the dot and load each relationship to get the column

$userPostTitle = 'post.title';
$userAvatarFilename = 'profil.avatar.filename';

The idea is to use explode() on the dot explode('.', $userPostTitle) and add bracket object dynamically for each relationship :

    // for the userPostTitle we need two level
    $postTitle = $user->{explode[0]}->{explode[1]};

    // for the userAvatarFilename we need three level
     $avatarFilename = $user->{explode[0]}->{explode[1]}->{explode[2]};

How it's possible to add dynamically the exploded relationship ? {rel1}->{rel2}->{rel3} etc... Maybe there is a better solution than using explode()

CodePudding user response:

You have to keep in mind that your solution possibly does a lot of queries if you haven't preloaded the relations beforehand. However I think you can use the Laravel helper object_get() for your problem:

$relation = 'profile.avatar.filename';
$avatarFilename = object_get($user, $relation);
// Which roughly translates to calling `$user->profile->avatar->filename`

It also accepts a third parameter which is a default value if the property turns out to be null.

  • Related