phplaraveleloquentmaatwebsite-excel

Get laravel relations value as attribute


I have two models, Portal and Tag and relation many-to-many between them with extra database portal_tag. All working great and I can access to portal->tag without problem.

But my goal is to get this model like "all values from model" and all relations value as one attribute, between commas. Is it possible?

Because I need it inside PortalsExport class in this form to use in export into CSV libary.

Now its look like this:

Portal::with('tags')
  ->select('url','type','topic','description','prohibited','visits','facebook_url','twitter_url','instagram_url')
  ->where('user_id', Auth::id())->get();

I have no idea how to make tags.name same as all other options from select.

I am using Laravel9 and PHP8.


Solution

  • If you want to get tags relations as comma separated string then One approach is, You will need to define a accessor in your Portal model which will append you tags array into string. like once I was did in one of my project:

    Step 1:

    public function getTagsAsStringAttribute(): string
        {
            $array = $this->tags->pluck('name')->all();
    
            return implode(", ",
                array_map(function ($k, $v) {
                    return $k;
                }, array_keys($array), array_values($array))
            );
        }
    

    In above closure functions, plz verify yourself that you tag name value is available in $k or $v variable.

    Step 2:

    add that accessor in Portal model append array like that:

     protected $appends = [      
            'tags_as_string',
        ];
    

    Step 3:

    In the result of yours below query you will get tags_as_string attribute which contains comma separated tags as string.

    Portal::with('tags')
      ->select('url','type','topic','description','prohibited','visits','facebook_url','twitter_url','instagram_url')
      ->where('user_id', Auth::id())->get();
    

    If tags_as_string shown empty then try it above query without select() clause.