Search code examples
laravelapifilterresourceslaravel-passport

generating API and laravel passport


I'm new to Laravel and kindly answer my question, please.

I'm developing a system with Laravel 5.8 in which two user levels are included.

  1. user
  2. admin

  • Authenticated users can view and store the posts into database. (action: index, show and store)
  • And authenticated admins can view the posts that the users have posted and approve to publish. (action: index, show, store and destroy)
  • My database table:books is like below:

  • id
  • name
  • numbers_of_pages
  • type
  • author
  • and users table:

  • id
  • name
  • email
  • password
  • and admins table:

  • id
  • name
  • email
  • password
  • First Question:

    In my api.php

    Route::apiResource('books', 'BookController');
    

    Follow is my desired routes structrues.

    # index()
    // http://127.0.0.1:8000/api/v1/books/drama -> get all books where type is drama
    // http://127.0.0.1:8000/api/v1/books/novel -> get all books where type is novel
    // http://127.0.0.1:8000/api/v1/books/magazine -> get all books where type is magazine
    

    How can I achieve that with my BookController created by the command:

    php artisan make:controller BookController --api
    

    and how to prefix v1 in the route? I don't want to prefix that version number in RouteServiceProvider.php.

    Another Question:
    How to oauth that multiple users? Both admins and users are consumers of the api.


    Solution

  • For i am developing an api myself at this moment, i know some of your problems and have already succeded to complete this task, so i try to answer your questions.

    To the 'v1' prefix in URL: I have done this in my routes/api.php file with

    Route::prefix('/v1')->group(function () { 
    // my routes for version 1
    }
    

    One word for your user/admin stuff: I did not put this into 2 seperate tables. The idea is, that you have a bunch of users and only some of them are admins. So why don't flag them with an admin flag and give the users model (in your User.php) a method with is_admin to just return, if this flag is set to true or false. So you can see, is a logged in user an admin or not.

    With this, you can check this at any time in your app with auth()->user()->is_admin to see, if this is an admin or not.

    Hope, i could help you a little bit 😉

    Now, to your Books problem. I would simply put in another route into my routes/api.php like

    Route::get('books/{category}', 'BookController@category')->name('books.category');
    

    and create a new function called public function category(String $category) into my BookController. Within this, you can check if $category is a valid Category Name and handle the return.