Getting Values from Nested Relationships in Laravel

May 4, 2018 By - Usama Muneer | 136

    Maintaining Database Relationships in Laravel is quite a task but when it comes to nested relationships, things get a bit tangled up to handle.

    In the below example, we’ll look on how to handle nested relationships situation in Laravel.

    Please note, this example will not include any steps for creating database migrations and seeders.

    Scenario

    Let’s take an example for customers & products and their corresponding types. The Relation between Customer and Product &¬†between Product and Type is hasMany respectively. We’ll go through these below.

    Customer Model

    public function product() {
       //foreign_key, local_key
       return $this->hasMany( 'App\Product', 'customer_id', 'id' );
    }

    Product Model

    public function type() {
       return $this->hasMany( 'App\Type' );
    }

    Now with the simple setup for our relationship we’re ready to get data from our DB.

    Getting data from nested relationship

    Consider that we’ll be needing to fetch customer’s selected type name for some product.

    $customer = Customer::with('product.type')->findOrFail($customer_id);
    $items = collect();
    $m->product->each(function($q) use(&$items) {
     $items = $items->concat($q->type);
    });
    $name = $items->pluck('name');
    dd($name);

    Conclusion

    If you’ve any questions or feedback regarding this code. Please leave us a comment below or you can also follow us on Twitter.

    blog user
    Usama Muneer

    A web enthusiastic, self-motivated & detail-oriented professional Full-Stack Web Developer from Karachi, Pakistan with experience in developing applications using JavaScript, WordPress & Laravel specifically. Loves to write on different web technologies with an equally useful skill to make some sense out of it.

    Related Posts

    If you're on MacOSX & use Laravel valet for managing your development environment. Then this issue might arouse when you try to upgrade your PHP version or even Laravel Valet. But there's an easy fix for that.

    When it comes to validation in Laravel. Developers often refer to using separate Requests to achieve it. Now for creating and updating, rules might get a little bit tricky. But we've got you covered.

    While Developing applications in Laravel, there comes situations where you have date in simple string format. For instance getting raw response from an API. But you want to convert that string into Carbon instance and use the Carbon helpers on it. Well there's a simple solution to it.

    Laravel ships in with the awesomeness of Database Migrations which allows you to version control your database. But there are number of events when you are required to change the datatypes or attributes assigned to your table columns inside of your migrations.