I am working on a Laravel 5.1 based system. I have a route resource:
Route::resource('applicant', 'ApplicantController');
So as we expect it has the following functions in the controller:
index, create, store, edit, update, delete
And what I want is to apply the middleware auth in the index function only. Normally, if you want to apply Auth on the entire controller, you need to do:
public function __construct()
{
$this->middleware('auth');
}
But when I remove it and just do:
public function index()
{
$this->middleware('auth');
return view('applicant.index');
}
It doesn't work. I've done this before and works fine.
This is in my ApplicantController I want the create function to be public and only apply login authentication on index. I won't be using edit, update, delete
can you try
public function __construct()
{
$this->middleware('auth', ['only' => 'index']);
}
You can also do the reverse
public function __construct()
{
$this->middleware('auth', ['except' => ['create', 'store', 'edit', 'update', 'delete']]);
}
Related
I am trying to call middle-ware in constructor of my controller.
My PostController class is below
class PostController extends Controller
{
public function __construct()
{
$this->middleware( ['auth:admin', ['only'=> ['store', 'update']]], ['auth:client', ['only'=> ['index', 'view']]]);
}
}
Please suggestion or correct me if I am wrong.
I think the best way do it in routes
Route::post('path', 'IndexController#store')->middleware(['auth:admin']);
Route::get('path', 'IndexController#index')->middleware(['auth:client]);
Or in group, for example:
Route::group(['middleware' => ['auth:admin']], function ($route) {
$route->post('storePath', 'IndexController#store');
$route->put('updatePath', 'IndexController#update');
});
Yes, you can call the middleware function multiple times.
class PostController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin', ['only'=> ['store', 'update']])
$this->middleware('auth:client', ['only'=> ['index', 'view']]);
}
}
Been searching hours for solution online but could not find a solution to this problem:
BadMethodCallException in RedirectResponse.php line 228:
Method [guest] does not exist on Redirect.
This is my controller:
class MemberController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('member.home');
}
}
class SessionController extends Controller
{
public function __construct()
{
$this->middleware('guest', ['except' => 'destroy']);
}
public function create()
{
return view('session.create');
}
}
This is my routes/web.php:
Route::get('/member', 'MemberController#index');
Route::get('/login', 'SessionController#create')->name('login');
When I try to access 127.0.0.1/member, the above error pops up.
Any idea?
you are setting your /member route to point to create method, which is not exists in your member controller object,
this line:
Route::get('/member', 'MemberController#create');
you may need to change it to :
Route::get('/member', 'MemberController#index');
OR
by changing your index method name in your member controller, or creating new method called create if you are using index method in another context:
public function index()
to be :
public function create()
I cant seem to get my edit function to work in my resourceful controller. This is my controller:
class UserController extends Controller{
public function index()
{
return view('testindex');
}
public function test(){
return 'test';
}
public function edit(User $user){
return 'test2';
}
public function create(){
return 'test3';
}
}
And my routes:
Route::post('test','UserController#test');
Route::resource('/','UserController');
Which mean that edit should be in the resource controller.
Create works but edit isn't, it gives me a
NotFoundHttpException
This is the form:
Edit
And yes, the variable $id works and is showing in the url.
What am I doing wrong here?
This is because you're not naming the resource i.e.
Route::resource('user', 'UserController');
To get around this you will need to change you route to be:
Route::resource('/', 'UserController', ['parameters' => [
'' => 'user'
]]);
(The above will allow you to keep your urls the same).
Please note that you will have to keep this Route at the bottom of your file.
Hope this helps!
I want to create authentication on laravel, but i have a problem.
when i want to access another page, the page has redirected to login page.
Here is my routes
Route::auth();
Route::get('/news/getid/{id_category}', 'NewsController#getid');
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('news', 'NewsController', ['except' => ['getid']]);
Route::resource('category', 'CategoryController');
});
and here is my LoginController
protected $redirectTo = '/news';
public function username()
{
return 'username';
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
You have to comment $this->middleware('auth'); line from constructor of your "NewsController". It should be
public function __construct()
{
// $this->middleware('auth');
}
Note: By commenting this line, Never check authentication for all view page that return from this controller.
Route::auth(); should be in web middleware group as auth routes use session to remember logged in user.
You need to remove this line in every page that you don't want to be protected by the authentication:
$this->middleware('auth');
so basically remove it from the "another page"s controller that you mentioned above.
In your Route file(Maybe web.php). Remove the auth middleware from the group
Like this:
Route::group(['middleware' => ['web' , 'auth']], function () {
Route::resource('news', 'NewsController', ['except' => ['getid']]);
Route::resource('category', 'CategoryController');
});
to become like this:
Route::group('middleware' => 'web', function () {
Route::resource('news', 'NewsController', ['except' => ['getid']]);
Route::resource('category', 'CategoryController');
});
But be sure you really don't need to protect that route.
I'm trying to use the __constructor from the extended class (AdminController extends AdminBaseController) but aparently it's not working and I have no idea of what can be, here you can see both of my classes:
AdminBaseController.php
class AdminBaseController extends Controller
{
public function __construct(){
if (!Auth::user()){
return view('admin.pages.login.index');
}
}
}
AdminController.php
class AdminController extends AdminBaseController
{
public function __construct(){
parent::__construct();
}
public function index()
{
return view('admin.pages.admin.index');
}
public function ajuda()
{
return view('admin.pages.admin.ajuda');
}
}
EDIT
This is my admin route group:
Route::group([
'prefix' => 'admin',
'middleware' => 'auth'
], function () {
Route::get('/', 'Admin\AdminController#index');
Route::get('login', 'Admin\AuthController#getLogin');
Route::post('login', 'Admin\AuthController#postLogin');
Route::get('logout', 'Admin\AuthController#getLogout');
Route::group(['prefix' => 'configuracoes'], function () {
Route::get('geral', 'Admin\AdminConfiguracoesController#geral');
Route::get('social', 'Admin\AdminConfiguracoesController#social');
Route::get('analytics', 'Admin\AdminConfiguracoesController#analytics');
});
Route::get('ajuda', 'Admin\AdminController#ajuda');
});
The controller is not the right place to check if a user is authenticated or not. You should use a middleware for that. To get info on what a middleware is check here
Let's see how you can use the default Laravel's auth middleware for this purpose:
First of all get rid of your AdminBaseController and use only AdminController
Then you have to check that the auth middleware is enabled in the file app\Http\Kernel.php
You should have the line:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
This means that the middleware is active and usable for your routes.
Now let's go inside the middleware class in app\Http\Middleware\Authenticate.php to specify the middleware's behaviour :
//this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
//check here if the user is authenticated
if ( ! $this->auth->user() )
{
// here you should redirect to login
}
return $next($request);
}
Now the only thing left to do is to decide for what routes you should apply the middleware. Let's suppose you have two routes that you want to be only accessible from authenticated users, you should specify to use the middleware for these two routes in this way:
Route::group( ['middleware' => 'auth' ], function()
{
Route::get('admin/index', 'AdminController#index');
Route::get('admin/ajuda', 'AdminController#ajuda');
});
Use middleware for this purpose and then in controller constructor use it as in example below.
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
And then you need to secure routes where you want from user to be logged in to access.
Route::group(['middleware' => 'auth'], function() {
Route::get('/dashboard', 'DashboardController#index');
});
In Laravel 5.5 , an unauthenticated user will cause the Authenticate middleware to throw a AuthenticationException exception.
protected function authenticate(array $guards)
{
if (empty($guards))
{
return $this->auth->authenticate();
}
foreach ($guards as $guard) {
if ($this->auth->guard($guard)->check()) {
return $this->auth->shouldUse($guard);
}
}
throw new AuthenticationException('Unauthenticated.', $guards);
}
This will be caught by the app/Exceptions/Handler class which will call its render method which is responsible for converting a given exception into a HTTP response.
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
App/Exceptions/Handler extends 'Illuminate\Foundation\Exceptions\Handler', located inside '/vendor/laravel/src/Illuminate/Foundation/Exceptions/Handler'. It has its own render method. Within that render method, there's a if else statement that says.
elseif ($e instanceof AuthenticationException)
{
return $this->unauthenticated($request, $e);
}
Below is the ‘unauthenticated‘ method that is called by the above within the same class
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson() ? response()->json(['message' => $exception->getMessage()], 401) : redirect()->guest(route('login'));
}
within this method is where you redirect an unauthenticated user.
As far as I can see, this is what goes on behind the scenes.
The way you extends and execute the parent constrictor is right, however
returning a view to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send().
for you purpose I think you should use before for filter http://laravel.com/docs/4.2/routing#route-filters