Ahmed Adel
Ahmed Adel

Reputation: 39

Model binding in Laravel

I am trying to fetch data from database in Laravel using Model binding in Controller but it returns empty $task array instead

here is my routes.php :

<?php

Route::get('/tasks','TasksController@index');
Route::get('/tasks/{task}','TasksController@show');

and this the TasksController :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Task;

class TasksController extends Controller
{
    public function show(Task $task)
    {
        return $task;
    }
}

Upvotes: 0

Views: 1804

Answers (2)

Option
Option

Reputation: 2645

Without seeing other code it's hard to answer however your function index() should look similar to this:

 public function index(Task $task)
    {
        $tasks = $task->all();

        return view('page', compact('tasks'));
    }

Now, assuming you're gathering the ID's via a foreach loop your controller code should look like this:

 public function show($id, Task $task)
    {
        $task = $task->find($id);

        return view('somePage', compact('task'));
    }

This will then pass $task back to a page of your choosing to display the specific task you are getting.

Your Routing is fine providing you're passing the:

<a href="/tasks/{{ $task->id}}">Something</a>

back within the blade.

Upvotes: 0

athulpraj
athulpraj

Reputation: 1577

 Route::get('/tasks/{id}','TasksController@show');

in route model binding you can pass the id in the route and handle it in the show function

 public function show($id)
 {
    $task = Task::find($id);
    return $task;
 }

This will directly return the task

Upvotes: 1

Related Questions