cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
778 stars 109 forks source link

Single and filter user resource #602

Closed acrespo123 closed 3 years ago

acrespo123 commented 3 years ago

How use this library to define a route like 'student' and return the authenticated user with the relations of this. I have 'users' resource and route.

ben221199 commented 3 years ago

In route/api.php

JsonApi::register('v1')->routes(static function(ApiRegistrar $api){
    //Your /users endpoint
    $api->resource('users');
    //Your /student endpoint
    Route::get('/student',  [StudentController::class,'show'])->middleware('auth');
}

In app/Http/Controllers/StudentController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Response;

class StudentController{

    public function show(): Response{
        $student = Auth::user();
        return json_api()->response()->content($student);
    }

}
ben221199 commented 3 years ago

If you also want the relationships of the current student, then do this:

$student = Auth::user();

$include = ['roles'];
$parameters = new EncodingParameters($include);

return json_api()->response()->withEncodingParameters($parameters)->content($student);
acrespo123 commented 3 years ago

thank you very much, I will try

lindyhopchris commented 3 years ago

Closing this as I think the question has been answered.