jeudi 19 septembre 2019

Laravel paginate with only first result

i'm kinda new to Laravel so I hope the question is clear enough.

I have a table with Users and another table with Tasks.

In my User model I have the following :

public function tasks() {
    return $this->hasMany('App\User' , 'id');
}

I can do the following to retrieve a single user from the DB

$users = \App\User::find(1)->tasks()->paginate();

but i get

{"current_page":1,"data":[{"id":1,"name":"Ed","email":"mail@weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[{"id":1,"name":"Ed","email":"mail@weqweqeq.com","email_verified_at":null,"created_at":null,"updated_at":null}]},{"id":2,"name":"Alyse","email":"mail@rxygewe.com","email_verified_at":null,"created_at":null,"updated_at":null,"tasks":[]}],"first_page_url":"http:\/\/127.0.0.1:8000?page=1","from":1,"last_page":1,"last_page_url":"http:\/\/127.0.0.1:8000?page=1","next_page_url":null,"path":"http:\/\/127.0.0.1:8000","per_page":15,"prev_page_url":null,"to":2,"total":2}

I've also tried :

    $users = \App\User::with(['tasks' => function($q) {
        $q->first();
    }])->paginate();

but the tasks property is empty

My question is how I can get all the users but only with first task and paginate to work?

Tasks table

1   id(Primary) bigint(20)      UNSIGNED    No  None        AUTO_INCREMENT
2   created_at  timestamp           Yes NULL        
3   updated_at  timestamp           Yes NULL        
4   task_name   varchar(255)    utf8mb4_unicode_ci      No  None        
5   user_id(Index)  bigint(20)      UNSIGNED    No  None        




via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire