Home > Net >  Laravel Livewire Get Relation Data From String
Laravel Livewire Get Relation Data From String

Time:10-24

I'm creating a Livewire data table component that dynamically render data. But I faced some issues while rendering relation data.

Subscription.php (Model)
class Subscription extends Model
{
    ...
    public function user()
    {
        return $this->belongsTo('App\Models\User');
    }
}

LivewireComponent.php
class SubscriptionTable extends Component
{
    ...
    public $columns =[
       [
          "name" => "User ID",
          "field" => "user_id",
          "sortable" => false, 
       ],
       [
          "name" => "Owner",
          "field" => null,
          "sortable" => false,
          "relation" => "user->name"
       ]
    ];
}     

livewire-component.blade.php:
...
@if(isset($columns['relation']))
   {{ dd($subscription->{$columns['relation']}) }} //return null
@else
   {{ dd($subscription->{$columns['field']}) }} //return User model
@endif

Is there any solution to this or any workaround to retrieve the user name?

CodePudding user response:

You can use data_get to get the data from relation.

class SubscriptionTable extends Component
{
    ...
    public $columns =[
       [
          "name" => "User ID",
          "field" => "user_id",
          "sortable" => false, 
       ],
       [
          "name" => "Owner",
          "field" => null,
          "sortable" => false,
          "relation" => "user.name"
       ]
    ];
} 

livewire-component.blade.php:
...
@if(isset($columns['relation']))
   {{ dd(data_get($subscription,$columns['relation'])) }}
   // with get the value like $subscription['user']['name']
  // you can also pass the 3rd argument as default value
@else
   {{ dd($subscription->{$columns['field']}) }} //return User model
@endif
  • Related