首页 > 解决方案 > Laravel Backpack 如何反弹到精确匹配而不是在表格中只显示 1 个结果

问题描述

在我的 Laravel 5.7 应用程序中,我目前使用“q”参数浏览到诸如https://example.com/admin/contact?q=john@example.com这样的 URL,这样我就可以直接搜索联系人表而无需在 DataTables ajax 搜索字段中键入。

这很好用,只是我希望它直接跳到编辑页面(对于只有 1 个结果的完全匹配)。

在我的ContactCrudController setup(),我有:

$q = $this->request->query->get('q');
if ($q) {// if there is an exact email match, redirect to the Edit page of that Contact.
    $matchingContact = \App\Models\Contact::where('emailAddress', $q)->first();
    if ($matchingContact) {
        return redirect(url('/admin/contact/' . $matchingContact->id . '/edit'));
    }
}

但这不起作用,因为setup()不期望return redirect().

我怎样才能实现我的目标?

标签: laravellaravel-5laravel-backpack

解决方案


尝试在控制器的构造函数中使用中间件:

class ContactCrudController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->middleware(function ($request, $next) {
            if ($contact = \App\Models\Contact::where('emailAddress', $request->query->get('q'))->first()) {
                 return redirect(url('/admin/contact/' . $contact->id . '/edit'));
            }

            return $next($request);
        });
    }
}

推荐阅读