0
votes

I have a laravel application and I have the following models

  1. Workshop
  2. WorkshopCategory

I have 3 tables,

  • workshops
  • workshop_categories
  • workshop_category_relation

I am trying to use eloquent to out put all my workshops, with the associated categories like the following:

{

"id":14,
"workshop_name":"First Workshop",
"description":"Located all over",
"categories": array: [
      0 => "wood"
      1 => "metal"
    ]

}

What would the best method be to achieve this? would I in my workshop model add the following:

public function categories()
    {
        return $this->belongsToMany('App\Workshopcategory', 'workshop_category_relation', 'workshop_id', 'category_id');
    }

I have added the above function to my workshop model and when I try output a workshop like the following:

$workshop = Workshop::FindOrFail(14);
return $workshop->categories(); 

I get the following error:

Object of class Illuminate\Database\Eloquent\Relations\BelongsToMany could not be converted to string

2

2 Answers

0
votes

I think you're just looking for a Many to Many relation.

All you'll need to do is rename your workshop_category_relation table to 'workshop_category' and then your belongsToMany should work.

0
votes

When you call:

return $workshop->categories()->get(); 

or just:

return $workshop->categories; 

You'll get a Collection of categories related to workshop and then you can itterate over like:

foreach($workshop->categories as $category) {
    $category->field_name
}