mercredi 21 septembre 2016

create categories and subcategories laravel 5

I need to output the following using a one to many relation in Laravel 5.2 grouping by news_category_id:

  • Cat 1

    • SubCat 1.1
    • SubCat 1.2
  • Cat 2

    • SubCat 2.1
    • SubCat 2.2

My query:

   $communications = Communications::with('news_category')->get();

    foreach ($communications as $c){
        echo "<b>" . $c->news_category->category_name . "</b><br/>";
            foreach ($c as $n){
                //echo $n->subject . "<br/>";
            }

Models:

The foreign key in communications table is "news_category_id" and in NewsCategory is "id"

class Communications extends Model
{
    public function news_category()
    {
    return $this->belongsTo('PropertyManager\NewsCategory');
    }
}


class NewsCategory extends Model
{
    public function communications()
    {
     return $this->hasMany('PropertyManager\Communications', 'news_category_id');
    }
}

I can not figure out what I'm missing to loop and display my data as described above and I'd need some input here. Thanks in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire