user5405648
user5405648

Reputation:

Explicit route model binding in Laravel?

So up until recently this has worked, until I wanted to change it slightly. I have a route

Route::get('/courses/{course}/lessons/{lesson}', 'CourseLessonController@show')->name('frontend.course.lesson');

I want the {lesson} to now refer to order_number, not the id column.

I've tried this in my RouteServiceProvider

Route::bind('lessons', function ($course, $lesson) {
    return App\CourseLesson::where('order_number', $lesson)
    ->where('course_id', $course->id)
    ->first();
});

I also tried going the getRouteKeyName route, this could be working, except for the fact that it doesn't ensure the lesson record is part of the course {course} is binding to.

public function getRouteKeyName() {
    return 'order_number';
}

None of them work, it still seems to link to the id column. It isn't even ensuring the column course_id in the lessons table is the same as the {course} passed to the route...

Here is my controller method:

public function show(Course $course, CourseLesson $lesson) {
    return view('frontend.lessons.show', compact('lesson', 'course'));
}

Upvotes: 0

Views: 138

Answers (1)

LeigerGaming
LeigerGaming

Reputation: 508

Welcome to StackOverflow :)

Just going to respond to these:

I also tried going the getRouteKeyName route, this could be working, except for the fact that it doesn't ensure the lesson record is part of the course {course} is binding to.

and

None of them work, it still seems to link to the id column. It isn't even ensuring the column course_id in the lessons table is the same as the {course} passed to the route...

It sounds like you've got it working with getRouteKeyName (great!), but your concern is that it doesn't validate that the lesson is part of the course.

This isn't the purpose behind the route - you should handle that logic in your controller.

For example:

public function show(Course $course, CourseLesson $lesson) {

    // Confirm that this course/lesson combination is valid
    if ($lesson->course_id == $course->id) {
        return view('frontend.lessons.show', compact('lesson', 'course'));
    }

    // The lesson is not in this course
    return redirect(route('home'));
}

Upvotes: 2

Related Questions