Am I the only one that want to use a simple admin section by a flag TRUE/FALSE in users TABLE? :)
When you're running artisan from CLI there is no user in the session. Auth::user()->id will throw Trying to get property of non-object because Auth::user() is null
Is there a way to fix this or should I test if the user is admin in all methods of the controller?
Right now I have:
class TestController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
protected $rules = [
'name' => ['required', 'min:5'],
'address' => ['required'],
];
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
if (Auth::user()->is_admin)
{
// ok
}
else
{
return Redirect::route('home');
}
}
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
if (Auth::user()->is_admin)
{
// ok
}
else
{
return Redirect::route('home');
}
}
/**
* Store a newly created resource in storage.
*
* @return Response
*/
public function store(Request $request)
{
if (Auth::user()->is_admin)
{
// ok
}
else
{
return Redirect::route('home');
}
}
}
I get the feeling that isn''t very nice but I do not know how to fix it better as I am very new to Laravel.
Thanks!
You could create a new request handler, then in your controller it's as simple as running
<?php namespace App\Http\Controllers;
use App\Http\Requests\AuthRequest;
class testController extends Controller {
public function index(AuthRequest $request)
{
//Dostuff
}
}
Create App/Http/Requests/AuthRequest.php
<?php namespace App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class AuthRequest extends Request {
public function authorize()
{
return (Auth::user()->is_admin) ? true : false;
}
public function rules()
{
return [];
}
}
If someone tries to access that controller it will reject the request and redirect back to the previous page.
Is there a way to create a new middleware and "cut" the request from there using this is_admin() function?
The problem is here. Instead of doing
if (Auth::user()->is_admin) {
do this, so you're getting property is_admin from an actual object
if (($user = Auth::user()) instanceOf User && $user->is_admin) {
haha.. much cleaner :).. i have this habit of comparing objects with their types.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community