Search code examples
phpdatabaselaravel-5dingo-api

Laravel Dingo FindOrFail returns empty array


I have a table sites with list of sites with following columns ('id', 'path', 'site_link'). I've written in a Site model public $timestamps = false; so that it won't try to work with time what I don't need.

Also I have the following routes

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
   $api->get('sites', 'App\Http\Controllers\SiteController@index');
   $api->get('sites/{site}', 'App\Http\Controllers\SiteController@show');
});

The first one is working fine and returning all the data, however the second one is returning just []. I have a controller which is below

namespace App\Http\Controllers;

use Illuminate\Http\Request;

Use App\Site;

class SiteController extends Controller
{
    public function index()
    {
        return Site::all();
    }

    public function show(Site $site)
    {
        return Site::findOrFail($site);
    }

    public function store(Request $request)
    {
        $site = Site::create($request->all());

        return response()->json($site, 201);
    }

    public function update(Request $request, Site $site)
    {
        $site->update($request->all());

        return response()->json($site, 200);
    }

    public function delete(Site $site)
    {
        $site->delete();

        return response()->json(null, 204);
    }
}

Solution

  • The show method in your SiteController is taking a Site object. However the route is set up to only take the siteId. The code below should work for you based on how you've set up your routes.

    public function show($site)
    {
        return Site::findOrFail($site);
    }
    

    Apply same to all your other controller methods since you want pass the site id via the url to the controller methods.