0

I want to access an Array, which is saved inside another array.

I have an Author Model which looks like this:

public function chapters() {
    return $this->hasManyThrough('Chapter', 'Book');
}    

Then I want to go ahead and grab all chapters, that are written by an author:

$chapters = Author::with('chapters')->where('id', $author->id()->get());

But when I want to return the chapters, they are saved within an array.

return dd($chapters->toArray());

Which looks like this:

array (size=1)
0 => 
  array (size=15)
    'id' => int 4
    'email' => string '[email protected]' (length=18)
    'chapters' => 
      array (size=7)
        0 => 
          array (size=15)
            ...
        1 => 
          array (size=15)
            ...
        2 => 
          array (size=15)
            ...
        3 => 
          array (size=15)
            ...
        4 => 
          array (size=15)
            ...
        5 => 
          array (size=15)
            ...
        6 => 
          array (size=15)
            ...    

But I want my array to look actually something like this:

array (size=4)
0 => 
  array (size=15)
    'id' => int 504
    'rating1' => int 48
    'rating2' => int 51
1 => 
  array (size=15)
    'id' => int 505
    'rating1' => int 96
    'rating2' => int 96

2 => 
  array (size=15)
    'id' => int 506
    'rating1' => int 7
    'rating2' => int 5
3 => 
  array (size=15)
    'id' => int 507
    'rating1' => int 21
    'rating2' => int 21

So that I could actually do this:

 return dd($chapters->lists('rating1'));

How can I currently get an accessible array of the chapters?

Thanks and kind regards, george

4
  • 1
    Not an array but a Collection, and simply do this instead of Author::with... -> $author->chapters->lists('rating1'); Commented Jul 6, 2014 at 13:25
  • Could you elaborate on this? I did this: $author = User::with('chapters')->where('id', $user->id)->get(); $author = $author->chapters->lists('rating1'); And I get an Error Exception: Undefined property: Illuminate\Database\Eloquent\Collection::$scores Commented Jul 6, 2014 at 14:26
  • 1
    get returns a collection, while you want first or find to fetch single model. So User::with('chapters')->find($id); Commented Jul 6, 2014 at 14:53
  • Thank you, you're awesome. Could you write your comment as an answer, so that I could give it a 'solution' tag. Thanks again. Commented Jul 6, 2014 at 17:22

1 Answer 1

1

What you need is this:

$author = User::with('chapters')->find($id);

$chapters = $author->chapters;

// then:
$chapters->lists('rating1');
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.