DEV Community

codewitholgun
codewitholgun

Posted on

Laravel Eloquent Tutorial - Get only the fields (aka columns) we need from relation.

Laravel is a great framework to work with, and I use it every day for my 9-5 job. One of the greatest power of Laravel is, it has an ORM (Object Relational Mapping) as default called Eloquent.

I am not going to talk about what is Eloquent ORM, but I would like to just indicate that, it makes your life easier to deal with databases.

Below you can find some simple usages of eloquent;

$post = Post::find(1)
// That will run the following query in the database
// select * from posts where id = 1
// You see, it's so easy to use and powerful because we don't need to write a query anymore
Enter fullscreen mode Exit fullscreen mode

If you are using relational databases such as MySQL, MariaDB, PostgreSQL and etc, it becomes more powerful because you don't need to write complex join queries anymore.

For example, we want to get a specific post from the posts table but also we want to GET the author of the post as well. The following example, clearly explains that.

class Post extends Model {
 ....
 // that will assume that we have author_id column in the posts table
 public function author(): BelongsTo
{ 
   return $this->belongsTo(related: Author::class)
 }
}

 // Since the author relation is defined in Post model, we can load it using following code
$post = Post::with('author')->find(1);
// Now, the post data will have the author data from database
// This is called Eager loading and it is very important learn about it.
// Link: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading
Enter fullscreen mode Exit fullscreen mode

Since we used eager loading to get author data with the post, all columns in the author data is loaded. This is not a problem with a small amount of data, but if we get millions of posts, each post will have an author and probably that will run a little bit slower. So, instead of getting all columns in author data, let's get some specific columns.

$post = Post::with('author:id, name')->find(1);
// Now, the post data will have the author data from database but only specific columns id and name
// This will make your it more faster to load data
Enter fullscreen mode Exit fullscreen mode

In the example above, we have used :id, name, so, only those columns are going to be loaded from the database.

That's all for this tutorial :)

If you like to get more content similar to that, please follow me on Twitter and on my youtube channel.

Twitter: twitter.com/olgunsoftware

Youtube: youtube.com/channel/UCH-xplaz-cmloIUkYspcEhQ

Top comments (0)