Home > Software engineering >  I am getting the 404 Not Found error even through the route is present
I am getting the 404 Not Found error even through the route is present

Time:08-10

I am getting the following error

404 NOT FOUND

even if the route exists.

Controller:

public function index($id = NULL)
{
if($id){
$tasks = Task::where('project_id', $id)->get();
} else {
$tasks = Task::all();
}

$project = Project::findOrFail($id)->load(['tasks']);
return view('task.index', compact('tasks','project'));
}

Route

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

When I am directed to this page I cannot see it due to the error written above.

Can anyone kindly tell me where the problem is?


Relationship defined in the Client model:

public function projects()
    {
        return $this->hasMany(Project::class);
    }

public function tasks()
    {
        return $this->hasManyThrough(Task::class, Project::class);
    }

Relationship defined in the Project model:

public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function tasks()
    {
        return $this->hasMany(Task::class);
    }

Relationship defined in the Task model:

public function project()
    {
        return $this->belongsTo(Project::class);
    }

TaskController:

public function index($id = NULL)
    {
        $tasks = Task::all();
        $project = Project::find($id)->load(['tasks']);     
        return view('task.index', compact('tasks','project'));
    }

clients id - integer name - string

projects id - integer client_id - integer name - string

tasks id - integer project_id - integer title - string

CodePudding user response:

Your route should be accessible via site.domain/task/index and not site.domain/task if you want to be able to access with /task your route should be Route::get('/task/{id?}', [TaskController::class, 'index'])->name('task.index'); Pay attention on the url you specified in your routes.

Update : in your controller

if($id){
  $tasks = Task::where('project_id', $id)->get();
  $tasks->load('project')
} else {
  $tasks = Task::with('project')->get();
}
return view('task.index', compact('tasks'));

then in your view may be something like this

@foreach($tasks as $task)
  display $task->project->name
@endforeach

(if i am not wrong analyzed i assumed 1 project has many task and 1 task belongs to 1 project)

  • Related