Support the ongoing development of Laravel.io →
Database Eloquent Blade

Hello,

when i need to use joins(), how to use it? Belongs it model or in controller?

Can anyone give me an example therefore? I dont find a solution with google :/


DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.id', 'contacts.phone', 'orders.price')
            ->get();

Last updated 3 years ago.
0

You can use Eloquent ORM and specify relationships between your models.

Then your code will transform into something like this:

//gets all users and their associated contacts and orders
$users = User::with('contacts', 'orders')->get(); //returns a Collection object

//same for a single user
$user = User::with('contacts', 'orders')->find($user_id); 
echo "User's phone: ".$user->contacts->first()->phone;
echo "User has made ".count($user->orders)." orders ";

To make this work you define relationship in your models. Say, User class will have these methods added:

use Illuminate\Database\Eloquent\Model;

class User extends Model {
  function contacts() {
    return $this->hasMany('App\Contact');
  }

  function orders() {
    return $this->hasMany('App\Order');
  }
}

And you need respective relationship in your App\Order and App\Contact models:

class Order extends Model {
  function user() {
    return $this->belongsTo('App\User');
  }
}
class Contact extends Model {
  function user() {
    return $this->belongsTo('App\User');
  }
}

Maybe watch Eloquent 101 and Eloquent Relationship to get a basic understanding of the topic.

0

Sign in to participate in this thread!

PHPverse

Your banner here too?

muellernm muellernm Joined 15 Apr 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.