pmiranda
pmiranda

Reputation: 8470

Laravel, get relation data

I'm kinda new to relations in Laravel.

When I do ddof an object, I get this:

Collection {#485 ▼
  #items: array:1 [▼
    0 => Menu {#484 ▼
      #table: "menus"
      #fillable: array:6 []
      #hidden: array:2 [▶]
      #connection: null
      #primaryKey: "id"
      #perPage: 15
      +incrementing: true
      +timestamps: true
      #attributes: array:9 []
      #original: array:11 []
      #relations: array:2 [▼
        "pivot" => Pivot {#486 ▶}
        "subMenus" => Collection {#items: array:3 [▼
        0 => SubMenu {#488 ▼
          #table: "sub_menus"
          #fillable: array:5 []
          #hidden: array:2 []
          #connection: null
          #primaryKey: "id"
          #perPage: 15
          +incrementing: true
          +timestamps: true
          #attributes: array:8 []
          #original: array:10 [▼
            "id" => 16
            "name" => "My name"   <--------- this is what I need to get
            "created_at" => "2018-11-20 15:19:14"
            "updated_at" => "2018-11-20 20:29:34"

How can I get the namevalue from the Model SubMenu that has a relation with my dd(model) ?

In Menu I got thos relation:

public function subMenus()
{
    return $this->belongsToMany('App\SubMenu', 'menu_submenu', 'menu_id', 'submenu_id')->where('estado', Define::ESTADO_ACTIVO)->orderBy('orden');
}

I tried something like:

dd($MyMenuObject->subMenus());

but not working. Tried with get(), ->submenu, etc.

EDIT: This is my data:

with dd($perfil_activo->menus); I get:

enter image description here

Upvotes: 2

Views: 178

Answers (2)

Shree Sthapit
Shree Sthapit

Reputation: 316

You can list all the subMenu names on an array: or object

$names=$model->subMenus()->pluck('name'); //object
//or
$names=$model->subMenus()->pluck('name')->toArray();// to array
dd($names);

Upvotes: 1

Tim Lewis
Tim Lewis

Reputation: 29316

You can access it via

$model->subMenus()->first()->name;

But since $subMenus() is a many-to-many relationship, you should probably do this via a loop:

foreach($model->subMenus AS $subMenu){
   $subMenu->name; // Do with as you please.
}

Edit: Since $model is also a Collection, you need to use ->first() or a loop:

$model->first()->subMenus->first()->name;

// OR

foreach($model AS $model){
   $model->subMenus->first()->name;
   // OR
   foreach($model->subMenus AS $subMenu){
       $subMenu->name;
   }
}

This is all dependant on how you fetch $model; if your Query ends with a ->get() or ->all(), it will be a Collection. If it ends with ->first(), ->find(), etc, it will be a single Model.

Upvotes: 2

Related Questions