dimanche 31 juillet 2016

Laravel routing with model as string

I am trying to simplify my routing for my models using Laravel 5.1. I have two resources, Questions and Categories, which inherit from ResourceController.

$router->get('/categories', 'Resources\Categories@index');
$router->get('/questions', 'Resources\Questions@index');

In ResourceController.php, my resource classes use this index method:

public function index(Request $request, Route $route)
{
    // Converts route name into namespaced Model string
    // E.g: App\Http\Controllers\Resources\Questions@index -> App\Question
    $model = $this->getModelClass($route->getActionName());

    return $model::all();
}

This SO post says I can call a eloquent methods using a fully qualified string:

$model_name = 'App\Model\User';
$model_name::where('id', $id)->first();

If I return $model, I get App\Category and App\Question for the respective routes I hit. This is good!

If I return $model::all(), I get a 500 error with no data.

I checked my sequel pro query logger and saw that both questions and categories were called about 20+ times even though I'm making a request to only one route at a time.

enter image description here

Why is this happening? This could explain the 500 error. I was able to get the models when only one resource was using this parent index method.

When both Questions and Categories relied on the same index, the errors started. I don't see why this is a conflict as the route sends the specific call to the index with the model name.


EDIT: I think this is related to how I am specifying eager loading:

Category.php Model:

protected $with = ['questions'];

Question.php Model:

protected $with = ['category'];

So it seems to be a circular reference where loading questions will come with categories, which will in turn load related questions, and so on.

But I do in fact need each to load with the relation. How can I fix this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2aI6l1D
via IFTTT

Aucun commentaire:

Enregistrer un commentaire