Home > Blockchain >  I get the error of Undefined variable $id even if it is passed
I get the error of Undefined variable $id even if it is passed

Time:08-02

I am using an optional parameter and am encountering the following error:

Undefined variable $id

even if it is passed in the route correctly.

Why am I getting this error? Can you help me please?

Route

Route::get('/project/index/{id?}', [ProjectController::class, 'index'])->name('project.index');

ProjectController

public function index($id=null)
    {           
        if($id){
            $projects = Project::withCount(['tasks'=> function (Builder $query){
                $query->where('project_id', $id);
            }])->get();
        } else {
            $projects = Project::withCount('tasks')->get();
        }
        return view('project.index', compact('projects'));
    }

View

<tr>
      <th>ID</th>
      <th>Name</th>
      <th>N. Task</th>
      <th>Azione</th>
</tr>
      @foreach ($projects as $project)
          <tr>
              <td>{{ $project->id }}</td>
              <td>{{ $project->name }}</td>
              <td><a href="{{route('task.index' , ['id' => $project->id])}}" >{{ $project->tasks_count }}</a></td>
              @endif
          </tr>
      @endforeach

CodePudding user response:

You need to pass the $id to the withCount method with use()

$projects = Project::withCount(['tasks'=> function (Builder $query) use ($id){
    $query->where('project_id', $id);
}])->get();

CodePudding user response:

First learn about route: Routing

Remove ? from route

Route::get('/project/index/{id}', [ProjectController::class, 'index'])->name('project.index');

change ProjectController function parmeter from

public function index($id=null)

to

public function index($id)

Done!!

  • Related