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?
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
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?
take a look at the package https://github.com/gathercontent/laravel-fractal i use this in all of my projects
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community