在Laravel中对函数执行两个操作,可能吗? [英] Two actions on a function in Laravel, possible?

查看:53
本文介绍了在Laravel中对函数执行两个操作,可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在应用程序中有2个用户角色,分别是 admin 前者.

I have 2 users roles in my application, admin and former.

管理员可以创建多个前者...

The admin can create several formers...

如果我将ID 1与我联系起来?我检索了前者的信息.

If, I connect me with the ID 1 ? I retrieve the information of the former.

因此,我的函数index()允许检索用户的ID

So, my function index() allows to retrieve id of the user

public function index()
{   
    if($has_role = auth()->user()->hasRole('admin')){
        $formers = Former::first()->paginate(5);
        return view('admin.formers.index', compact('formers'));
    } else{
        $formers = Former::where('email', Auth::user()->email)->paginate(5);
        return view('admin.formers.index', compact('formers'));
    }
}

好吧,对于用户 admin ,我想创建一个搜索栏...

Well, for the user admin, I would like to create a search bar...

我在之前创建了一个函数index()并且有效

I had created before a function index() and which worked

public function index(Request $req)
{
    if ($req->search == "") {
        $formers = Former::paginate(5);
        return view('admin.formers.index', compact('formers'));
    } else {
        $validated = $req->validate([
            'search' => 'alpha', 
        ]);

        $formers = Former::where('nom', 'LIKE', '%' . $validated['search'] . '%')->paginate(5);
        $formers->appends($req->only('search'));
        return view('admin.formers.index', compact('formers'));
    }
}

现在,我想在一个函数中适应我的2个动作,有可能吗?

Now, I would like to adapte my 2 actions in a function, is it possible according you?

您认为我可以在同一功能中获得 user_id 并创建一个搜索栏吗?

Do you think that I can get the user_id and make a search bar in the same function?

谢谢

推荐答案

我将执行以下操作:

  • 添加一个同时担当数据和角色角色的动作.
  • 仅向管理员显示搜索,但在服务器端忽略此事实,因为从安全角度来看,非管理员是否可以搜索都无关紧要.无论如何,他们仅限于他们的结果.

基本上,这可以通过以下方式实现:

Basically, this is achievable in the following way:

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

public function index(Request $request)
{   
    $user = $request->user();

    $formers = Former::query()
        ->when($user->hasRole('admin') !== true, function (Builder $query) use ($user) {
            $query->where('email', $user->email);
        })
        ->when($request->has('s'), function (Builder $query) use ($request) {
            $query->where('nom', 'like', '%'.$request->input('s').'%');
        })
        ->paginate(5);

    return view('admin.formers.index', compact('formers'))
        ->with('display_search', $user->hasRole('admin'));
}

然后,您可以在视图中简单地使用$display_search变量来决定是否要显示搜索:

You can then in your view simply use the $display_search variable to decide whether or not you want to display the search:

@if($display_search)
  <form method="post" action="...">
    <input type="text" name="s" placeholder="Type to search...">
  </form>
@endif

这篇关于在Laravel中对函数执行两个操作,可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆