Why You Can Use $user->name After User::create([…]), But Not With Query Builder

If you’re learning Laravel, you’ve probably encountered both Eloquent Models and the Query Builder. While both are powerful tools to interact with the database, they behave very differently, especially in how they return data after inserting a new record.

Let’s break it down with a simple example and explain why this behavior happens.

The Eloquent Way

$user = User::create(['name' => 'Ali']);
echo $user->name; // Output: Ali

What’s Happening Here?

  • User::create([...]) does more than just insert a record.
  • It returns a fully loaded instance of the User model.
  • You get access to all model methods, relationships, accessors, and attributes.

That’s why you can immediately use $user->name after the create operation.

The Query Builder Way

$user = DB::table('users')->insert(['name' => 'Ali']);
echo $user->name; // ❌ This will cause an error

Why Doesn’t This Work?

  • insert() only executes the insert query.
  • It returns a simple true or false, indicating success or failure.
  • It does not return any data about the inserted row — not even the ID.

So $user here is just a boolean (true), not an object. Trying to access $user->name will result in an error.

How to Get Similar Behavior with Query Builder

If you must use Query Builder and want the inserted data, you’ll need to do it manually:

$id = DB::table('users')->insertGetId(['name' => 'Ali']);
$user = DB::table('users')->where('id', $id)->first();
echo $user->name; // Works, but $user is a StdClass object

Even then, $user is an instance of StdClass, not the User model. So you don’t get model features like relationships or accessors.

Summary Table

FeatureEloquent Model::create()Query Builder insert()
Returns full objectYesNo
Can access $result->nameYesOnly after separate ->first()
Comes with relationships & accessorsYesNo
Returns inserted IDYes (implicitly)Only with insertGetId()

Final Thoughts

Use Eloquent when you need rich data handling and want access to model features. Use Query Builder for performance-sensitive, raw, or batch operations.

Understanding this difference is key to avoiding confusion – and those pesky errors some of my Laravel students run into.

Happy coding!

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Copyright © 2012 - 2025 Amirol Zolkifli. All Rights Reserved.