【问题标题】:laravel api routing - how to return 404 when received unexpected url?laravel api 路由 - 收到意外 url 时如何返回 404?
【发布时间】:2020-07-11 11:19:44
【问题描述】:

我想解决一些问题..

在 api 调用中, 我想返回 404 页面,但它总是允许任何 url。

例如,我想要两个我想要的 url localhost/api/kr/[something]localhost/api/en/[something]。 但是当我请求localhost/api/dwkwdkwjdq/[someting] 时,它不会返回 404 页面..

首先,

  1. RouteServiceProvider/mapApiResource
public function api(){

    $works = Work::select('some datas')
            ->where('locale', app()->getLocale())
            ->get();

    foreach ($works as $work){
        $work -> url = env('APP_URL') . '/api/' . app()->getLocale() . '/works/' . 
        $work->id;
    }

    $product_information = collect();

    $product_information->put('works', $works);

    return response()->json($product_information, 200);
}
  1. api.php Route::get('/kvtext', 'Admin\AdminKvController@api');

  2. Admin\AdminKvController@api

  3. 和 app\Http\Middlewar\SetLocale.php

public function handle($request, Closure $next){

    $locale = $request->segment(2);

    app()->setLocale($locale);

    return $next($request);
}

我错过了什么..?

非常感谢您阅读这个问题。

【问题讨论】:

    标签: laravel api http-status-code-404


    【解决方案1】:

    在您的RouteServiceProviderboot 方法中为允许的语言环境添加绑定

    protected $locales = ['kr', ... ];
    
    public function boot()
    {
        parent::boot();
    
        Route::bind('locale', function ($locale) { abort_unless(in_array($locale, $this->locales), 404) });
    }
    

    然后你可以在你的路由上使用{locale}绑定。

    Route::get('{locale}/something', 'Controller@action')->name('...');
    
    # Controller
    public function action($locale)
    {
        // ... 
    }
    

    【讨论】:

    • 感谢您的帮助!有用!但是有没有其他方法不改变 api.php..?
    • 可能,但这是我能想到的最简单的方法。
    • 顺便说一句,我真的很感激 :)
    猜你喜欢
    • 2018-02-11
    • 2021-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2021-04-12
    相关资源
    最近更新 更多