Support the ongoing development of Laravel.io →
Database Eloquent Installation
Last updated 2 years ago.
0

I found a way, given the models structure I described. This way I can access the data. Please let me know if there's a different easier way:

public function index()
    {

        $id = Auth::id();

        $user = User::find($id);

        $results = array();

        foreach ($user->owned_item as $i) {

            $results [] = array(

                "type" => $i->Item_type->type,
                "color" => $i->Item_color->color

        );

        }

        dd ($results);

    }

This, for example, results in:

array:3 [▼
  0 => array:2 [▼
    "type" => "Type A"
    "color" => "black"
  ]
  1 => array:2 [▼
    "type" => "Type B"
    "color" => "red"
  ]
  2 => array:2 [▼
    "type" => "Type C"
    "color" => "green"
  ]
]

So I can pass this results to my view, is that correct? I can't think of any other method to create an array with the data I need. Does eloquent permit something better?

0

you don't need to do that. What you are looking for is a presenter patters. The returned collection can be presented anyway you want with collection methods. http://laravel.com/docs/5.1/collections#available-methods

0

do you mean presenter pattern? I am looking at the methods and I don't see which one should work for me. How would you rewrite the function?

Last updated 8 years ago.
0

take a look at the package https://github.com/gathercontent/laravel-fractal i use this in all of my projects

0

what about the package? You told there is no need to define the array the way I wrote, that I need to use collection methods, there's no collection methods that will work the way I need. If you can rewrite the code using collection method please do if not don't add confusion.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

chriz74x chriz74x Joined 8 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.