Search code examples
phplaravellaravel-5laravel-5.6laravel-translatable

spatie/laravel-translatable 5.6 cannot translate slug and throws 404


I have 'courses' table in my database and JSON 'slug' column in it. For example:

| Slug                                                 | 
|------------------------------------------------------|
| {"az": "slug-in-azerbaijani", "ru": "slug-in-russian"|
| {"az": "another-slug-az", "ru": "another-slug-in-rus"|

Now, when I go into course details, I get course details by slug. Here is the controller:

public function detailed($slug) {

        $locale = app()->getLocale();

        $course = Course::where(\DB::raw( "json_extract(slug, '$." . $locale . "')" ), $slug)->firstOrFail();$popularCourses = Course::inRandomOrder()->limit(3)->get();

        if(!$course) {
            return abort(404);
        }

        $data = array(
            'course' => $course,
            'instructor' => $course->instructor
        );

        // Fetch detailed information about instructor and courses that belongs to him
        return view('courses.detailed')->with($data);
    }

However, there is one problem. If I am inside course details and the URL is:

http://localhost:8000/az/courses/slug-in-azerbaijani

then I change the website language to another language, it does not translate the slug. The URL becomes

http://localhost:8000/ru/courses/slug-in-azerbaijani

and it throws 404 page. However, it must be

http://localhost:8000/ru/courses/slug-in-russian

How can I solve this problem? Here is the route.php:

Route::group(
    [
        'prefix' => LaravelLocalization::setLocale(),
        'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
    ],
    function()
    {
        Route::get('/courses', 'CoursesController@index');
        Route::get('/courses/{slug}', 'CoursesController@detailed');
        Route::get('/courses/category/{slug}', 'CoursesController@getCoursesByCategory');
    });

Solution

  • Actually, I solved the issue. The logic is: When I am inside a detailed course (blog or smth), I get the id of the article. After that when I change the language of the page, I redirect to course/id, not course/slug, and after that I redirect to course/slug. Here is part of my code:

    public function routeById($type, $id) {
    
            if ($type == 'course') {
                $item = Course::find($id);
                $routeName = 'single_course';
    
            } else {
                $item = Category::find($id);
                $routeName = 'courses_by_category';
            }
    
            if (!$item) {
                return abort(404);
            }
    
            return redirect()->route($routeName, $item->slug);
    
        }