Search code examples
phpcontrollerlaravel-5.5

Laravel - Undefined variable $data on view


I have a problem with this.

Undefined variable: acara (View: /var/www/html/event_organizer/resources/views/admin/home.blade.php)

But I have declared $acara on the controller like this

Controller

use App\events; 

    public function lihat_acara()
    {
      $data['acara'] = events::all();
      return view('admin.home')->with($data);
    }

and the view like this

home.blade.php

@foreach($acara as $key)
  <tbody>
    <tr>
      <td>{{ $key->nama_acara }}</td>
      <td>{{ $key->kategori_acara }}</td>
      <td>{{ $key->lokasi_acara }}</td>
    </tr>
  </tbody>
  @endforeach

What's wrong with my code? Any idea? :)


Solution

  • use App\events; 
    
    public function lihat_acara()
    {
      $data['acara'] = events::all();
      return view('admin.home', ['acara' => $data['acara'] ]);
    }
    

    OR

    use App\events; 
    
    public function lihat_acara()
    {
      $data['acara'] = events::all();
      return view('admin.home')->with('acara', $data['acara']);
    }
    

    OR

    use App\events; 
    
    public function lihat_acara()
    {
      $data['acara'] = events::all();
      return view('admin.home')->withAcara($data['acara']);
    }
    

    From this laravel official site Passing data to view, you can find all the way to send data from controller to view.