Mugluck Mugluck - 1 year ago 81
PHP Question

Why isn't this WHERE clause accepting a variable? Laravel 5.3

I have this function here:

public function move() {

$prefs = DB::table('users')->select('id', 'Preferences')->where('Preferences', '!=', '')->get();

foreach ($prefs as $pref) {
$tags = $pref->Preferences;
$tag = explode(',', $tags);
foreach ($tag as $t) {
$new = DB::table('prefs')->select('id', 'tag')->where('tag', '=', $t)->get();
$taguser = new Tag(array(
'user_id' => $pref->id,
'tag_id' => $t,
'tagsid' => $new->id
$taguser->save(); //save in table
return view('refactor');

It basically just grabs the data from an old database table which wasn't properly set up, splits up the data, compares it with a list of the preferences in another table and gets that data id, then prints the tag, the user id, and the preference id into a pivot table.

Or that's what it's supposed to do. Right now it's telling me the id from the prefs table is undefined. That last bit there
'tagsid' => $new->id
<= apparently that doesn't exist.

But it should. What did I do wrong?

Here's a piece of the error:

Undefined property: Illuminate\Support\Collection::$id
at HandleExceptions->handleError('8', 'Undefined property: Illuminate\Support\Collection::$id', 'C:\xampp\htdocs\Missionseek2\app\Http\Controllers\RefactorController.php', '29', array('prefs' => object(Collection), 'pref' => object(stdClass), 'tags' => '1-3,1-5,1-4,2-3,3-2,3-9,3-3,3-4,3A-5,3A-8,5-2,8-4,8-8,8-13,9-5,7A-2,7A-4,7A-10', 'tag' => array('1-3', '1-5', '1-4', '2-3', '3-2', '3-9', '3-3', '3-4', '3A-5', '3A-8', '5-2', '8-4', '8-8', '8-13', '9-5', '7A-2', '7A-4', '7A-10'), 't' => '1-3', 'new' => object(Collection))) in RefactorController.php line 29

Answer Source

When you do a ->get() it returns a Collection object. You will need to iterate it to get the underlying models.

I think you would need to use ->first() to get the first matching result, and it will return you the model itself, so you can access the ->id field.

In short, change this line:

$new = DB::table('prefs')->select('id', 'tag')->where('tag', '=', $t)->get();


$new = DB::table('prefs')
           ->select('id', 'tag')
           ->where('tag', $t)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download