【问题标题】:Laravel Route Model Binding Dynamic Error MessageLaravel 路由模型绑定动态错误信息
【发布时间】:2020-12-20 14:26:11
【问题描述】:

给定/routes/api.php 这样的文件

// Article
Route::get('article/{article}', 'ArticleController@retrieve');
// Category
Route::get('category/{category}', 'CategoryController@retrieve');

还有两个这样的控制器:

class ArticleController extends Controller
{
    public function retrieve(Article $article)
    {
        return $article;
    }
}
class CategoryController extends Controller
{
    public function retrieve(Category $category)
    {
        return $category;
    }
}

现在在/app/Exceptions/Handler.php 上是这样的:

class Handler extends ExceptionHandler
{
    public function render($request, Throwable $exception)
    {
        if ($exception instanceof ModelNotFoundException &&
            $request->wantsJson())
        {
            return response()->json([
                'error' => 'Resource not found'
            ], 404);
        }

        return parent::render($request, $exception);
    }
}

当我搜索不存在的资源时,两个端点都会这样响应:

{ "error": "Resource not found" }

那么,如何传递自定义消息以便处理程序可以将该消息作为响应输出?

例如,当文章未找到时,它将返回如下:

{ "error": "Article not found" }

当没有找到类别时,它会像这样返回:

{ "error": "Category not found" }

*对不起,如果标题误导,据我从this文章中了解到,它被称为“Route Model Binding”

【问题讨论】:

  • 你可以通过getModel方法从ModelNotFoundException获取模型名称

标签: php laravel


【解决方案1】:

您可以使用数组中返回的$request->route()->parameterNames();request()->route()->parameterNames(); 值,如果路由需要多个参数,则使用您的逻辑

例如:结果是array['category'] 然后你可以这样修改

$param = $request->route()->parameterNames()[0];//to get parameter

//modifying message
return response()->json([
  'error' => "{ucfirst($param)} not found"
], 404);

【讨论】:

    猜你喜欢
    • 2017-06-22
    • 2018-04-05
    • 1970-01-01
    • 2021-05-24
    • 2016-06-04
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多