Laravel with relationship but use join instead

Laravel’s with() is an easy to use query builder tool to fetch relationship. Once you’ve established the relationship in your model file you can do this.

Book::with('publication')->where('title','The Hobbit')->first();

// returns
=> App\Models\Book {#4587
     id: 23,
     isbn: "12345ABCD",
     title: "The Hobbit",
     publication_id: 43
     publication: App\Models\Book {#5527
          id: 43,
          name: "Penguin"
     }
   }

But this query has the downside of hitting the database twice, or however many relationships you query. And if you’re running it on a big scale application, it can be inefficient.

Check and see how to count how many time your query touches the database here.

This is where you can use the join() function, which is still quite easy to use and hits the database only once.

Book::join('publications', 'books.publication_id', '=', 'publications.id')
->where('title','The Hobbit')
->first();

// returns
=> App\Models\Book {#4587
     id: 23,
     isbn: "12345ABCD",
     title: "The Hobbit",
     publication_id: 43
     name: "Penguin"
   }

You can even run select statements on this like so.

Book::join('publications', 'books.publication_id', '=', 'publications.id')
->select('books.title','publications.name', 'publications.id AS bilbo')
->where('title','The Hobbit')
->first();

// returns
=> App\Models\Book {#4587
     title: "The Hobbit",
     name: "Penguin",
     bilbo: 43
   }

It’s something I wish I learned sooner. As the returned object is cleaner and easier to use, and more efficient!

Leave a Comment