0

In PHP, I have already understood that double arrow ( => ) is used with arrays to assign a value to the key and the object operator ( -> ) is used to access the properties of objects (methods and variables).

Please take a look at the following code:

public function show() {
    $items = Test::all();
    return view('display'['item'=> $items]);
}

Could anyone explain what exactly the double arrow ( => ) operator is doing here and how it is possible in this context?

foreach($items as $item) {
    echo $item->name;
}

As per the definition the left side of the object operator ( -> ) must be an instance variable. Then how this operator is applicable here?

Michel
  • 867
  • 11
  • 23

2 Answers2

0

When you define the $Items variable in your php script, you are instantiating a php object. Next, you assign the object as a value in your array [Item=>object] before pushing it to your view. In the view, you now have access to that object by calling it using it's key [$Item] in your foreach loop as $Value and then from there you may access is as you normally would in a php script because of the view engine.

Bottom line, you pass an object to your view so you will still be able to access it's properties and methods in the front-end using the template engine and Laravel framework.

Luke
  • 733
  • 4
  • 12
0
public function show()
{
    // This returns an array of Item objects. In this case 'items' is 
    // probably a table in your database, so each Item object is a
    // row in that table.
    $Items = Item::all();

    // give this array as 'Items' to the view (don't forget the comma here)
    return view('display', ['Items' => $Items]);
}

In your view you should use the same variable names. (I use blade template in this example)

@foreach ($Items as $item):
   {{ $item->ItemName }}
@endforeach
winkbrace
  • 2,525
  • 22
  • 19