Skip to content
Advertisement

Query One to Many Relation in Laravel 8

I have one to many relation for User and Student.

Model User.php

public function students()
{
    return $this->hasMany(Student::class);
}

Model Student.php

public function user(){
    return $this->belongsTo(User::class);
}

and in Controller.php

public function show(){
    $users = User::with('students')find(5);
    return response()->json($users);
}

it will run and return json

{
"id": 5,
"email": "student1@test.com",
"email_verified_at": null,
"created_at": "2021-06-27T01:52:28.000000Z",
"updated_at": "2021-06-27T01:52:28.000000Z",
"students": [
    {
        "id": 1,
        "user_id": 5,
        "firstname": "Ms",
        "lastname": "Zee",
        "studentPhone": "08515xxxxxxx",
        "studentAddress": "my address"
    },
    {
        "id": 5,
        "user_id": 5,
        "firstname": "my Name",
        "lastname": "k",,
        "studentPhone": "085xxxxxx",
        "studentAddress": "my address",
        
    }
]
}

can I custom select in Students, only show firstname and lastname ?

Advertisement

Answer

You should use API Resources for this. Here’s a link to the official documentation: https://laravel.com/docs/8.x/eloquent-resources

Your student collection could look something like this:

<?php

namespace AppHttpResources;

use IlluminateHttpResourcesJsonResourceCollection;

class StudentCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  IlluminateHttpRequest  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'firstname' => $this->firstname,
            'lastname' => $this->lastname,
        ];
    }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement