简体   繁体   中英

Binding several inherited models to the same route laravel

I've got 3 models, all of which inherit an abstract Plan model, BehaviourPlan , AffirmationPlan and ProfilePlan

Is it possible to have all of them served by the same route? This is what I've got so far, but because Plan is abstract it throws Target [App\\Plan] is not instantiable.

Route::prefix('plans')->group(function () {
    Route::get('/{plan}', function (\App\Plan $plan) {
        dd($plan);
    });
});

I've solved this by altering the slugs of each plan to be prefixed with their type, and then just running an if statement to retrieve the plan within a controller, like:

public function show(Student $student, string $plan_id)
    {
        $plan = null;
        if(starts_with($plan_id, "behaviour"))
        {
            $plan = BehaviourPlan::where('slug', $plan_id)->first();
        }
        else if(starts_with($plan_id, "affirmation"))
        {
            $plan = AffirmationPlan::where('slug', $plan_id)->first();
        }
        else if(starts_with($plan_id, "profile"))
        {
            $plan = ProfilePlan::where('slug', $plan_id)->first();
        }

        if ($plan == null)
            return abort('404');

        dd($plan);
    }

It seems a bit rough-and-ready though, so I'm still on the lookout for a neater way to fix this issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM