Support the ongoing development of Laravel.io →
Database Eloquent Blade
Last updated 2 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!

Eventy

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.

© 2024 Laravel.io - All rights reserved.