spatie / laravel-translateable 5.6无法翻译子弹并抛出404

时间:2018-08-16 13:27:34

标签: php laravel laravel-5 laravel-5.6 laravel-translatable

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

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

现在,当我进入课程详细信息时,我会从头了解到课程详细信息。这是控制器:

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-azerbaijani

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

  

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

,它将引发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');
    });

1 个答案:

答案 0 :(得分:0)

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

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

    }