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.
$user = User::create(['name' => 'Ali']);
echo $user->name; // Output: Ali
User::create([...])
does more than just insert a record.User
model.That’s why you can immediately use $user->name
after the create operation.
$user = DB::table('users')->insert(['name' => 'Ali']);
echo $user->name; // ❌ This will cause an error
insert()
only executes the insert query.true
or false
, indicating success or failure.So $user
here is just a boolean (true
), not an object. Trying to access $user->name
will result in an error.
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.
Feature | Eloquent Model::create() | Query Builder insert() |
---|---|---|
Returns full object | Yes | No |
Can access $result->name | Yes | Only after separate ->first() |
Comes with relationships & accessors | Yes | No |
Returns inserted ID | Yes (implicitly) | Only with insertGetId() |
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!