skip to Main Content

I want to display the detail page based on the table id that is already available. However, the Undefined variable $data error appears when I enter code like this

Controller

public function show($id)
    {
        return view('daftar_mahasiswa', [
            'data' => Mahasiswa::findOrFail($id),
        ]);
    }

Route

Route::get('/daftar_mahasiswa/{id}', [MahasiswaController::class, 'show']);

daftar_mahasiswa.blade.php

<button class="action" style="background: #3C91E6">
      <a href="daftar_mahasiswa/{{ $data->id }}" style="color: inherit">
          <i class='bx bxs-detail'></i>
          Detail
      </a>
</button>

I hope the code can display the details of the selected data based on the ID.

2

Answers


  1. The $data variable is not defined here.

    You can modify your Controller code like this:

    Controller:

        public function show($id)
        {
          $data = Mahasiswa::findOrFail($id);
          return view('daftar_mahasiswa', compact('data'));
        }
    

    daftar_mahasiswa.blade.php

    <button class="action" style="background: #3C91E6">
    <a href="{{ url('daftar_mahasiswa', $data->id) }}" style="color: 
    inherit">
        <i class='bx bxs-detail'></i>
        Detail
    </a>
    </button>
    
    Login or Signup to reply.
  2. the code you provided, the Mahasiswa::findOrFail($id) call is correctly retrieving the data for the specified $id, but you need to make sure that the $data variable is passed to the view correctly

    To fix the issue

    public function show($id)
    {
        $data = Mahasiswa::findOrFail($id);
        return view('daftar_mahasiswa', compact('data'));
    }
    

    Additionally you can add a null check in the view and handle the case when the $data variable is not available,

    <button class="action" style="background: #3C91E6">
        @if($data)
            <a href="{{ url('daftar_mahasiswa', $data->id) }}" style="color: inherit">
                <i class='bx bxs-detail'></i>
                Detail
            </a>
        @else
            <span>No data available</span>
        @endif
    </button>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search