简体   繁体   English

Laravel链式Eloquent Query无法返回结果数组

[英]Laravel chained Eloquent Query can't return result array

I am trying to make a chained Eloquent query on Laravel and bring the users from a users table with a conditional and that is, if they belong to determined house. 我正在尝试在Laravel上进行链式Eloquent查询,并使用条件带来用户表中的用户,即,如果它们属于确定的房子。 I am struggling a little to find the way to get that to work. 我正在努力寻找让它发挥作用的方法。 Can someone help me? 有人能帮我吗?

This is my controller method: 这是我的控制器方法:

public function create(){

        if(Auth::user()->role->id == 1){

            $house = House::findOrFail(Auth::user()->house->id);

            $jobs = Job::pluck('name', 'id')->all();
            $categories = Category::pluck('name', 'id')->all();
            $users = User::pluck('name', 'id')->where('house_id', $house)->get();

            return view('admin.tasks.create', compact('jobs', 'categories', 'users'));

        }else{

            return redirect('home');

        }

    }

The error been thrown to me when using the get() is: 使用get()时抛出的错误是:

Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in /Applications/MAMP/htdocs/Housing_around/app/Http/Controllers/AdminTasksController.php on line 55 and at least 1 expected

And as thought, the all() in the end doesnt bring me anything in the returned array 并且正如所想的那样,最后的all()并没有在返回的数组中带来任何东西

Does someone have a clue on how to proceed? 有人知道如何继续吗?

Thank you! 谢谢!

Use the correct syntax to avoid the error: 使用正确的语法来避免错误:

$jobs = Job::pluck('name', 'id');
$categories = Category::pluck('name', 'id');
$users = User::where('house_id', $house)->pluck('name', 'id');

You can't use get() after pluck() pluck()之后你不能使用get() ()

$jobs = Job::pluck('name', 'id');
$categories = Category::pluck('name', 'id');
$users = User::where('house_id', $house)->pluck('name', 'id');

A suggestion I would give you is to use policies to determine roles for the current authenticated user. 我给你的建议是使用策略来确定当前经过身份验证的用户的角色。 If you think that this method in your controller its handling authorization, fetching data from database and passing them to the view. 如果您认为控制器中的此方法具有处理权限,则从数据库中获取数据并将其传递给视图。

When the controller role its just a bridge between models(data structure) and presentation (views) 当控制器角色时它只是模型(数据结构)和表示(视图)之间的桥梁

Check out Laravel authorization. 查看Laravel授权。

Then pluck() method its a method that under the hood it calls get() so you cant call them both at the same time. 然后pluck()方法是一个方法,它在引擎盖下调用get()所以你不能同时调用它们。 Same for all() vs get() all has get method calling behind the scenes. 对于all()get()相同, all()都在后台调用get方法。

So do like $users = User::where('house_id', $house)->pluck('name', 'id'); 那就像$users = User::where('house_id', $house)->pluck('name', 'id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM