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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community