#database #development #eloquent #laravel #php

Imagine you have two tables posts and authors. Posts table has a column author_id which represents a belongsTo relationship on the authors table.

To get the author id of a post, we would normally do

1$post = Post::findOrFail(<post id>);
2$post->author->id;

This would result in two queries being executed.

1select * from posts where id = <post id> limit 1
2select * from authors where id = <post author id> limit 1

Instead, you can directly get the author id by doing the following.

1$post = Post::findOrFail(<post id>);
2$post->author_id; // posts table has a column author_id which stores id of the author

When can I use the above approach? You can use the above approach when you are confident that a row always exists in authors table if it is referenced in posts table.