Reputation: 727
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
Upvotes: 0
Views: 2109
Reputation: 1439
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:
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,
];
Upvotes: 2