0

我的数据库中有“课程”表,其中有 JSON 的“slug”列。例如:

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

现在,当我进入课程详细信息时,我会通过 slug 获取课程详细信息。这是控制器:

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);
    }

但是,有一个问题。如果我在课程详细信息中并且 URL 是:

http://localhost:8000/az/courses/slug-in-阿塞拜疆

然后我将网站语言更改为另一种语言,它不会翻译 slug。网址变成

http://localhost:8000/ru/courses/slug-in-阿塞拜疆

它会抛出 404 页面。然而,它必须是

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

我怎么解决这个问题?这是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');
    });
4

1 回答 1

0

实际上,我解决了这个问题。逻辑是:当我在一个详细的课程(博客或smth)中时,我得到了文章的ID。之后,当我更改页面的语言时,我重定向到 course/id,而不是 course/slug,然后我重定向到 course/slug。这是我的代码的一部分:

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);

    }
于 2018-08-19T20:40:29.797 回答