Reputation: 457
I have a simple class called MyClass like so:
namespace App\MyDomain;
class MyClass{
private $msg;
public function __construct($msg){
$this->msg = $msg;
}
public function saySomething(){
return $this->msg;
}
}
And I have a simple test view called testView.blade.php under Pages subfolder like so:
<h3>Test View page</h3>
<p>Content before</p>
<p>Contents from controller:
<ul>
@foreach($results as $result)
<li>{{$result}}</li>
@endforeach
</ul>
</p>
<p>Content after</p>
And below is what my Routes look like:
Route::get('/sandbox', 'PageController@getData');
And in my PageController, I have a method getData like so:
public function getData(){
$results = new MyClass('aloha');
// I can see the variable when dumping
// dd($results);
// but this is not working. it only displays the test view but not the results variable
return view('pages.testView',compact('results'));
}
So when I hit the 'sandbox' URI, I should hit the controller and get the result back to my view and then I should see the word 'aloha' but its just empty. I don't see the variable result in the view.
I've also tried the suggestion on this link but I dont think it applies to my version or I just don't know how to make it work
Is there something I missed? thanks for the help in advance.
Upvotes: 0
Views: 52
Reputation: 139
you try to loop over the object. {{ var_dump($results) }}
to see the object. If you want to see the message. {{ $results->saySomething() }}
Upvotes: 0
Reputation: 457
Sorry, I forgot to call the method of my MyClass that's why its not visible on the view.
public function getData(){
$obj = new MyClass('aloha');
$result = $obj->saySomething();
return view('pages.testView',compact('result'));
}
Now its working ;-)
<h3>Test View page</h3>
<p>Content before</p>
<p>Contents from controller:
{{ $result }}
</p>
<p>Content after</p>
thanks guys for your comments. it gave me the hint!
Upvotes: 1
Reputation: 13259
Yes you are looping over a single Object. In your view, remove the foreach
loop and simply do.
<ul>
<li>{{ $result->saySomething() }}</li>
<ul>
Your $results
variable contains 1 instance of MyClass
.
Upvotes: 0