Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sheldonscott's avatar

Outputting multiple rows of data connected to other tables

I feel like I am almost ready to throw in the towel with Laravel. I have spent so much time trying to understand it and battling what I feel should be simple tasks. I know there are hardcore Laravel enthusiasts out there and I truly want to be one but of all the official documentation and books I've read, as well as Laracasts and other videos I've watched, I am missing something. (I'm guessing much of it has to do with the fact that I am a hobbyist programmer and have zero exposure to OOP/MVC prior to wade in the Laravel waters.)

I would greatly appreciate hearing from someone who can make sense of this rather simple problem in layman terms (if possible).

I am trying to output all of the records from my DB, each of them having a relationship with other sets of data.

resources table

| id | name               | write_up                                       | author_id |
|----|--------------------|------------------------------------------------|-----------|
| 1  | The First Resource | This is the write up for the first resource.   | 2         |
| 2  | Resource 2        | Some kind of write up for the second resource. | 4         |

users table

| id | first_name | last_name | email           | username |
|----|------------|-----------|-----------------|----------|
| 1  | Harry      | Henderson | [email protected]    | harryh   |
| 2  | Sally      | Ann       | [email protected] | sally    |

grades table

| id | number | name         |
|----|--------|--------------|
| 1  | 0      | Kindergarten |
| 2  | 1      | Grade 1      |
| 3  | 2      | Grade 2      |

resource_grade table

| resource_id | grade_id |
|-------------|----------|
| 1           | 5        |
| 1           | 6        |
| 2           | 3        |

How would I output each resource with its corresponding user and grade(s)?

Within my Resource controller, I defined a couple relationships:

public function user()
{
    return $this->belongsTo('App\User', 'author_id');
}

public function grades()
{
    return $this->belongsToMany('App\Grade', 'resource_grades');
}

I can output each of the two resources by using:

$resources = Resource::all();

If I do it this way:

$resources = Resource::with('subjects')->get();

I can see the output as follows:

{"id":1,"name":"The First Resource","slug":"the-first-resource","write_up":"This is the write up for this particular item, as provided by the user. Macaroon jujubes cotton candy gingerbread fruitcake ice cream caramels gingerbread. Donut wafer cake gummies. Chocolate jelly jujubes dessert. Candy jujubes jujubes liquorice jujubes chocolate bar jelly-o. Cupcake marzipan jelly-o sweet tiramisu pastry jelly apple pie gummi bears. Icing halvah cheesecake bonbon sugar plum cupcake sweet cookie. \n\nSouffl\u00e9 cake cookie halvah pudding. Powder chocolate danish cake muffin pastry lemon drops. Muffin bear claw chocolate cake cake apple pie ice cream. Sweet sugar plum oat cake jelly-o cake pie. Bonbon gingerbread apple pie. Jelly-o jelly beans bonbon muffin chocolate bar bonbon oat cake sweet roll souffl\u00e9. Apple pie cake apple pie sweet roll oat cake danish. Biscuit candy chupa chups candy.","author":2,"created_at":"2017-07-21 08:00:05","updated_at":"2017-07-21 08:00:05","subjects":[{"id":1,"name":"Aboriginal Studies","created_at":"2017-06-12 12:10:04","updated_at":"2017-06-12 12:10:04","pivot":{"resource_id":1,"subject_id":1}},{"id":5,"name":"English as a Second Language","created_at":"2017-06-12 12:10:04","updated_at":"2017-06-12 12:10:04","pivot":{"resource_id":1,"subject_id":5}},{"id":8,"name":"Ethics","created_at":"2017-06-12 12:10:04","updated_at":"2017-06-12 12:10:04","pivot":{"resource_id":1,"subject_id":8}},{"id":2,"name":"Career and Life Management","created_at":"2017-06-12 12:10:04","updated_at":"2017-06-12 12:10:04","pivot":{"resource_id":1,"subject_id":2}}]}

{"id":2,"name":"The Second Resource","slug":"the-second-resource","write_up":"Some kind of write up for the resource.","author":4,"created_at":"2017-07-21 16:08:08","updated_at":"2017-07-21 16:08:08","subjects":[{"id":3,"name":"Career and Technology Foundations","created_at":"2017-06-12 12:10:04","updated_at":"2017-06-12 12:10:04","pivot":{"resource_id":2,"subject_id":3}}]}

How do I pull out and display the subjects name, for example? Trying $resources->subjects->name within the view throws up an error.

I feel like I am close, but I also know I am missing some pretty simple/basic stuff to you veterans.

Please help me to better understand this.

0 likes
6 replies
sheldonscott's avatar

@edoc

Thanks for the quick reply. That gives me a Property [subjects] does not exist on this collection instance. error.

I was under the impression that get() returns collections and find() or first() returns objects. I am using get():

$resources = Resource::with('subjects')->get();
Snapey's avatar
Snapey
Best Answer
Level 122

Where does subjects come into it, you did not mention subjects when you explained your tables?

How would I output each resource with its corresponding user and grade(s)?

$resources = Resource::with('grades','user')->get();

and then you should have multiple resources and each will have relations of the user and multiple grades

You can iterate over the resources and then within each resource, iterate over the grades, and display the user. For instance in blade, using a table

@foreach ($resources as $resource)

    <h3>{{ $resource->name }}</h3>
    <p>{{ $resource->write_up }}</p>
    <p><em>{{ $resource->user->first_name }}</em></p>

    <table>
        @foreach($resource->grades as $grade)
        <tr>
            <td>{{ $grade->number }}</td>
            <td>{{ $grade->name }}</td>
        </tr>
        @endforeach
    </table>

@endforeach 

sheldonscott's avatar

@Snapey Thank you so very much!

I do have a 'subjects' table but had left it out of my explanation (hence the confusion).

Your solution worked great!!! Can't thank you enough.

Snapey's avatar

ok, but its important you understand why it works.

dd($resources) and explore attributes and relations of the result so you can see how they are nested in with eager loading.

1 like

Please or to participate in this conversation.