Steve Steve - 3 years ago 242
reST (reStructuredText) Question

Auth and user management in laravel rest api

I'm writing a rest API for a mobile app. I don't know how to auth users and admins in my app.
I have a table named "users" and have a field called "isAdmin" that is 0 or 1.
now when admin sends posts, users can see posts.how do you recommend auth for both of these?
thank you

Answer Source

I recommend you read the documentation about authentication on laravel: https://laravel.com/docs/5.5/authentication

What you have to setup is the following:

  • Middleware (what routes can the user use and what routes can the admin use)
  • Edit your model with an isAdmin() function to determine if an user is user or admin

Example of a AdminMiddleware file - create by command line: php artisan make:middleware AdminMiddleware

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check() && Auth::user()->isAdmin()){
            return $next($request);
        }
        else{
            return view('your_view')->withErrors('You are not logged in');
        }
    }
}

Example of an User Model isAdmin function - create by command line: php artisan make:model User

public function isAdmin(){
    if($this->isAdmin == 1){
        return true;
    } else {
        return false;
    }
}

Example of your route file

// @TODO: Set routes for user and admin here...

Route::group(['middleware' => ['admin']], function () {
    // @TODO: Set admin routes here, only admin can use this routes.
});

You also have to edit your Kernel.php a bit:

protected $routeMiddleware = [
    // ... add this line
    'admin' => \App\Http\Middleware\AdminMiddleware::class,
];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download