Laravel Eloquent查询报错:无法将Collection转换为int,求排查
Alright, let's break down exactly what's causing this error and walk through the fixes step by step.
Core Issues
You've got two related problems here that are triggering the type conversion error:
1. Passing a Model Object Instead of an ID to where()
Looking at your controller code:
$users = User::where('house_id', $house)->pluck('name', 'id');
The $house variable is a full House model instance (from House::findOrFail(...)), but the house_id column in your users table expects an integer ID. When Eloquent tries to convert this model object to an integer to match the column type, it fails hard with the error you're seeing.
2. Merging an Array with a Collection
In your view, you're trying to combine an array with a Collection using the + operator:
{!! Form::select('user_id',[''=>'Chose user'] + $users,null,['class'=>'form-control']) !!}
PHP's + operator only works with arrays—you can't directly merge an array with an Illuminate\Support\Collection object. This also triggers a type conversion attempt that fails, compounding the first issue.
Step-by-Step Fixes
Fix 1: Use the House ID in the where() Clause
Replace $house with $house->id in your user query to pass the correct integer value:
$users = User::where('house_id', $house->id)->pluck('name', 'id');
Fix 2: Convert the Collection to an Array
Just like you did with $jobs and $categories, add the ->all() method to convert the plucked Collection to a plain array. This makes it compatible with the array merge in your view:
$users = User::where('house_id', $house->id)->pluck('name', 'id')->all();
Full Corrected Controller Code
$house = House::findOrFail(Auth::user()->house->id); $jobs = Job::pluck('name', 'id')->all(); $categories = Category::pluck('name', 'id')->all(); // Fixed query with ID and converted to array $users = User::where('house_id', $house->id)->pluck('name', 'id')->all();
Alternative: Convert Collection to Array in the View
If you prefer to keep the Collection in the controller, you can use ->toArray() in the view instead:
{!! Form::select('user_id',[''=>'Chose user'] + $users->toArray(),null,['class'=>'form-control']) !!}
But converting to an array in the controller keeps your view logic cleaner, which is generally better practice.
内容的提问来源于stack exchange,提问作者Luiz Wynne

