Mauro
Mauro

Reputation: 372

Laravel undefined variable template rendering

I am currently busy with some Laravel Blade Templating, but I can't figure out why my code won't work. I have a Controller that has three names and descriptions in an array and I need to show them on the welcome page with a foreach loop.

PlanetenController.php:

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Route;

class PlanetenController extends Controller
{
    public $planets = [
        [
            'name' => 'Mars',
            'description' => 'Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System, being larger than only Mercury.'
        ],
        [
            'name' => 'Venus',
            'description' => 'Venus is the second planet from the Sun. It is named after the Roman goddess of love and beauty.'
        ],
        [
            'name' => 'Earth',
            'description' => 'Our home planet is the third planet from the Sun, and the only place we know of so far thats inhabited by living things.'
        ]
    ];
    public function index() {
        return view('welcome')->with('planets', $planets);
    }
}

welcome.blade.php:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
    </head>
    <body>
        @foreach ($planets as $planeten)
            <ul><li>$planeten[$name]</li>
            $planeten[$description]
            <ul>
        @endforeach
    </body>
</html>

When I try my code it gives an error of '$planets is undefined'. Can someone help me with this? This needs to be the output: enter image description here

Upvotes: 1

Views: 525

Answers (1)

Maik Lowrey
Maik Lowrey

Reputation: 17566

You have to call planetswith $this. Planets are a class member var.

return view('welcome')->with('planets', $this-> planets);

After then you change in your blade the array keys to they static names. and work with the blade {{ $var }} brackets to print the variable out. Then it would be work fine.

@foreach ($planets as $planeten)
  <ul>
      <li>{{ $planeten['name'] }}</li>
      <li>{{ $planeten['description'] }}</li>
  <ul>
@endforeach

Small Note It is better to rename planetento the singular name like planet. Because planetsalready plural.

Upvotes: 5

Related Questions