33
Easy way to build admin login into a Laravel 5
Authorization can be tricky. There are thousands of posts about how to perform authentication, but actually verifying who someone is and managing user permissions can be a whole can of worms. Fortunately, Laravel has systems in place that make a tiered login system very easy to implement.
php artisan make:auth
Easy solution for making a Laravel admin page using custom middleware
I am using Laravel 5.5 right now, the latest release. The only specific Laravel 5.5 thing going on is the @guest helper in the frontend Blade directives. In the HTML section of the application, these helpers allow us to easily check if the user is logged in or not:
@auth
// The user is authenticated...
@endauth
@guest
// The user is not authenticated...
@endguest
If you’re not using Laravel 5.5 there are other workarounds but you might as well upgrade to the latest version for the new features!
✌ How we achieve this is to add a type column on the users table and check if a user has that type via custom middleware. It sounds fancy but it’s pretty easy!
/* app/User.php */
const ADMIN_TYPE = 'admin';
const DEFAULT_TYPE = 'default';
public function isAdmin() {
return $this->type === self::ADMIN_TYPE;
}
/* database/migrations/2014_10_12_000000_create_users_table.php */
$table->string('type')->default('default');
</code></pre>
#### 3) Add a type value to the create method in register controller
<pre><code class="language-php">
/* app/Http/Controllers/Auth/RegisterController.php */
protected function create(array $data) {
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'type' => User::DEFAULT_TYPE,
]);
}
php artisan make:middleware IsAdmin
namespace App\Http\Middleware;
use Closure;
class IsAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if(auth()->user()->isAdmin()) {
return $next($request);
}
return redirect('home');
}
}
/* app/Http/Kernel.php */
'is_admin' => \App\Http\Middleware\IsAdmin::class,
/* routes/web.php */
Route::view('/', 'welcome');
Auth::routes();
Route::get('/home', 'HomeController@index')
->name('home');
Route::get('/admin', 'AdminController@admin')
->middleware('is_admin')
->name('admin');
php artisan make:controller AdminController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function admin()
{
return view('admin');
}
}
🎉 That’s pretty much it!
Now if you visit /admin and you’re not logged in or logged in as an administrator you won’t be able to access the page. In order to create an admin user you can use the tinker artisan command:
$ php artisan tinker
>>> use App\User;
>>>User::where('email', '[email protected]')->update(['type' => 'admin']);
33