Tinkerwell 4 is out now! See what's new or buy now.
Tinkerwell background image
Tinkerwell Logo Tinkerwell
Go back to Blog

Laravel Eloquent – create, update and query your database with joy

Laravel Eloquent ist an object-relational-mapper, an ORM, that makes working with databases a joy. While you still need a basic understanding about your database and how writing queries works, Laravel Eloquent provides convenient methos to insert, update and query this data.

Eloquent uses the active record pattern where every column in the database table is accessible via a magic method of the related Eloquent Model. So you can access the name column of your user model with $user->name.

Project Setup
#

For this guide, we use a standard implementation of a blog. The blog has Users, the Users have Posts and these have Comments. Posts and Comments are always connected to a User and this is how our database looks like.

The Eloquent relationships on the User model for this setup looks as simple as that:

public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
 
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}

As an example, the Post relationships are similar:

public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
 
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}

In the next, step, we use Laravel Eloquent Factories to create test data for our implementation. If you only do this every now and then, you can use Tinkerwell to run these factories, simply create 25 users with generated fake data.

use App\Models\User;
use App\Models\Post;
use App\Models\Comment;
 
// create 25 users
$users = User::factory()
->times(25)
->create();
 
// create 50 posts from these users
$posts = Post::factory()
->times(50)
->recycle($users)
->create();
 
// use existing users and posts to create comments
Comment::factory()
->times(100)
->recycle($users)
->recycle($posts)
->create();

Create Laravel Eloquent models manually
#

While we use factories for our demo application locally, you can also use the create method of Laravel Eloquent to create records in your normal application. So if you want to create a user manually, you can simply connect to your application with Tinkerwell and create the user via Eloquent.

User::create([
'name' => 'Sebastian',
'email' => '[email protected]',
'password' => bcrypt('secret'),
]);

This creates a user with the password secret. When using the create method with a mass assignment where you add all values within an array, make sure that the properties of the model are either explicitely listed in the $fillable array of the model or that the whole model is unguarded.

Select Laravel Eloquent models with multiple where conditions
#

When you query your database with Laravel Eloquent, you can add as many where conditions to the query as you want. They filter the results with an AND condition, so if we want to get all users of our blog that have a premium account and haven't added their company name to their account, we can do this with the Eloquent query below. Tinkerwell has Magic Comments that you can use within a query to run additional methods on the query – in our case, we run the database count function to see how many results we'll get.

User::query()
->where("company", null)
->where("premium", true)
/*?->count()*/
->get();

If we want to use the OR within our where conditions, we can use the orWhere selector.

User::query()
->where("company", null)
->orWhere("premium", true)
/*?->count()*/
->get();

This query returns all users who haven't set a company name in their profile or who have a premium account.

For convenience, you can use the whereNull or whereNotNull method to improve the readability of your Eloquent query.

User::query()
->whereNotNull("company")
->where("premium", true)
/*?->count()*/
->get();

Using whereHas to get all Users with Posts
#

Laravel Eloquent is very powerful, especially if you start querying relationships or just their existence.

In the next Example, we use the has method of Eloquent to filter our existing results even further and return only users who have written at least 3 posts.

User::query()
->whereNotNull("company")
->where("premium", true)
->has('posts', '>=', 3)
/*?->count()*/
->get();

We can become more specific with our query by using the whereHas method and insert a function into the query that creates a subquery on the actual comments of these users.

User::query()
->whereNotNull("company")
->where("premium", true)
->has('posts', '>=', 3)
->whereHas('posts', function($query) {
$query->where('title', 'like', '%eloquent%');
})
/*?->count()*/
->get();

As you can see, Laravel Eloquent has a powerful query builder that allows you to use multiple where conditions as well as the option to query relationships, their existence and even their content.

Tinkerwell on the other hand is a powerful code runner that makes writing complex Laravel Eloquent queries enjoyable because you can easily test them during development. It speeds up your workflow so much that you will use it all the time, sometimes for things that are as easy as querying your production database so count how many users have a premium account with User::wherePremium(true)->count() or select a user and update their values without touching your database management tool.

User::wherePremium(true)
->get()
->each(function ($user) {
$user->update([
"name" => $user->name . " 🚀"
]);
});
Eric L. Barnes, Creator of Laravel News
“I use Tinkerwell all the time now. Love that app.”

Eric L. Barnes

Creator of Laravel News

Rishab Kapadia, Developer
“It's a horror to even think working without it. The defacto standard to test code logic in PHP. Save the mental juggle. Get it now.”
Rishab Kapadia

Developer

Tinkerwell: The PHP Scratchpad

The must-have companion to your favorite IDE. Quickly iterate on PHP code within the context of your web application.

Buy now Learn more