Laravel 5.2 PHP Build a social network - Middleware & Route Protection
HTML-код
- Опубликовано: 30 сен 2024
- Build a complete Social Network Web Application with PHP Laravel. In this video you will learn how to apply middleware to routes and how to use it to make certain routes only accessible to authenticated users.
Complete source code: github.com/msc...
Complete Laravel-course on Udemy: www.udemy.com/... (Coupon: RUclips1)
In this course we'll build a neat little social network and cover the basics of developing with Laravel.
You can follow me on Twitter (@maxedapps), Facebook ( / academindchannel ) or visit our Website (www.academind.com).
See you in the videos!
if after doing all this you still can access the dashboard page then you need to clear the cookies as the user session is already made when we tried to login earlier and we never logged out as we dont have that functionality yet.
DO THIS, i was driving crazy and I changed the browser and it worked
How do I clear the cookies?
Thank you so much!!
Akbar khan you a lifesaver!!!
@@patrickhally9249 probably dont do it better use another browser like edge or some browser that you dont use frequently
How check do i login when we not have logout function? Try this:controller: public function getDashboard(){
$user = Auth::user(); return view('dashboard')->with('user', $user);
}
dashboard view{!! $user !!}
+Konrad Wójcik
Logout function is implemented in one of the next videos. You may implement a provisional one with Auth::logout() if you need it
+Mindspace Yes i know. Thank you for answer.
Hey Max! I'm really happy to find your channel. You are an awesome teacher. These Laravel tutorials are fantastic and have helped a lot. I can't wait to dig into your Angular 2 stuff. I previewed it, feeling pretty excited.
For anyone who has issues with the Dashboard still being accessible it's more than likely because the Test Users you created at the beginning are still logged in. Because Max hasn't covered a Logout Session yet. For those who don't want to mess around with the Laravel code. Just delete all your test users from your MySQL database and you should see the Redirect work. Then you can create new test users as we go along. Cheers!!!
+Derek Shanks
Wow, thanks a lot! I'm very happy my teaching style helps you and I got a lot to come in this channel :).
Also thanks for your explanation, should've covered it in the video but ... yea... didn't :D.
+Mindspace No worries Max! You're covering so much awesome material and you're very organized. It's going to happen that you can't remember to say and cover everything. You're only human! But that's also how we learn too.
agrreeeedddd
For the guys having isses with Laravel 5.5.
i took a look at the docs, and here is the solution:
we have to add write the dashboard Route like this:
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
])->middleware('auth');;
and also change the Route::group(['middleware' ..
name('home); to name('login');
i needed following:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
])->middleware('auth');
in app/Exceptions/Handler.php
add following
/**
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Illuminate\Http\Response
*/
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['message' => $exception->getMessage()], 401)
: redirect()->guest(route('home'));
}
also scheck if you have imported everything in this file:
use Exception;
use Request;
use Illuminate\Auth\AuthenticationException;
use Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
Thanks so much. The bug almost burst my mind.
Greate solution MrUmfi, thank you. But you didn't must change the route
It's work with too:
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Thanks! worked just with changing home to login
Yes!
This is in RedirectIfAuthentificated.php file
public function handle($request, Closure $next, $guard = null)
{
if (!Auth::guard($guard)->check(){
return redirect()->route('home');
}
return $next($request);
}
for the most of you, it doesn't work just because the session still exists, I think that is the right method to do it.
//This the route code that you have to include in you're web.php file
Route::get( '/dashboard', 'UserController@getDashboard')->name('dashboard')->middleware('guest');
'angular 2, I said it again!!', that makes me laugh every time :)
nice tutorial series.
It's everywhere! ;)
Happy to hear you're liking it
For laravel 5.4 (5.3, maybe) ,Change in code for everyone having problem authenticating users :
### web.php
// Group of routes which require a user to be logged in . (Keep all other routes : signin, signup. etc. ....... outside this group)
Route::group(['middleware' => ['auth']], function() {
Route::get('/dashboard', [
'uses'=>'UserController@getDashBoard',
'as'=>'dashboard'
]);
});
### App\Exceptions\handler.php
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('home')); //change from login to home
}
There are examples of authorization using tweeter accounts, facebook accounts, gmail accounts?
This method is not working on Laravel 5.4
The SOLUTION is to go on app/Exceptions/Handlers.php and
change the last line of code:
return redirect()->guest(route('login'));
to
return redirect()->guest(route('home'));
And this should WORK!
it does not work. can you help me please? The Error is:
(1/1) InvalidArgumentException
Route [login] not defined.
Can you copy and paste your code of your Routes;
can you look please?
Handler.php
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->guest(route('home'));
}
Route.php
Route::get('/', function () {
return view('welcome');
});
Route::post('/singup', 'UserController@postSingUp');
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
]);
Route::post('/singin', [
'uses' => 'UserController@postSingIn',
'as' => 'singin',
]);
Route::get('/login', function (){
echo "Hello";
});
change the Route.php file to this:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/singup', 'UserController@postSingUp');
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
]);
Route::post('/singin', [
'uses' => 'UserController@postSingIn',
'as' => 'singin',
]);
Route::get('/login', function (){
echo "Hello";
});
it does not work. do i have to change anything else?
Hi this has changed in laravel 5.3 the files are not the same. please help. I guess I stop here if there is no way around this because I am sure the rest of the videos pretty much depends on Authentication
for people using laravel 5.3 instead of trying to find the authenticate.php file go into app/Exceptions/Handler.php
once there scroll to the bottom and edit the bottom part into this
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('home');
}
also make sure your using web.php for routes instead of routes.php for laravel 5.3
Ty =D
Thank you very much =)
Thank you so much it worked like charm... :-)
What about Laravel 5.5?
what is the difference when you use inside route.php 'as' and '->name()'
There is no difference, just two different ways.
help needed...... my routing protection does not work?
*****route class*****
Route::get('/', function () {
return view('welcome');
})->name('home');
and
Route::get('/dashboard',[
'uses' => 'UserController@getDashboard',
'as' =>'dashboard',
'middleware'=> 'auth'
]);
*** Authenticate class******
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('home');
}
}
What "does not work" mean? Do you get an error? Are you redirect when you shouldn't be? Are you able to access the route despite not being logged in?
In the latter case, make sure that you really are logged out, because that is the number-1 issue I found to be the case when encountering this problem ;)
I'm also having the same problem. My problem is that i keep getting redirected to the welcome page again. I cleared my browser cache, used php artisan cache:clear, but still. Any help?
So logging in does not work. Check if you're encrypting the pw when signin up, because Laravel will try to log you in against an encrypted password.
If that's the case, throw in some dd (e.g. dd($request['password']) in your sign in controller, to check if the data gets passed there correctly.
I want to ask something rly basic, what if I want to redirect to a page without that 'uses' => 'blah blah blah' line, i dont get what it excactly does and what will happen if i dont use something like that. cuz when I creat a page and than try to create route for it and use that line, it basicly crashes and says: Method App\Http\Controllers\UserController::SOMETHING() does not exist
i have a problem, it's not working, i use laravel 5.8
User is not redirected to dashboard view after successful sign up. what could be the problem ?
what is for if we visit welcome page with login, this not redirecting to dashboard, because user already logged in they should not see the welcome page again
for people using laravel 5.3 instead of trying to find the authenticate.php file go into app/Exceptions/Handler.php
once there scroll to the bottom and edit the bottom part into this
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('home');
}
also make sure your using web.php for routes instead of routes.php for laravel 5.3
I am using Laravel 5.4 and i am not able to do authentication when going to dashboard.The
Exceptions\Handler.php last function looks like this
protected function unauthenticated($request, AuthenticationException $exception)
{
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
return redirect()->route('home');
}
and in my Routes\web.php, i have this
Route::get('/dashboard',[
'uses' => 'UserController@getDashboard',
'as' => 'dashboard'
])->middleware('auth');
its working now... :D
cool and how did you do that?
Sajjad have you resolve the problem?
Hey Guys, im using the newest version of Laravel (5.6.27) and i dont have the Authenticate.php file in my project tree. Maybe on the beggining it is optional and i have to create it somehow?
Found it, but instead of the construction of the file that we can see ie in 3:47 i have something like this:
public function handle($request, Closure $next, ...$guards)
{
$this->authenticate($guards);
return $next($request);
}
ps. the file Aythenticate.php is localized in yourproject/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php
To redirect to the route you want when trying to access the dashboard unauthenticated in laravel 5.5 do the following:
protected function unauthenticated($request, AuthenticationException $exception)
{
return $request->expectsJson()
? response()->json(['message' => 'Unauthenticated.'], 401)
: redirect()->guest(route('home')); //Set this route to where ever you want
}
I missed the edit made @2:31 while I was looking at my IDE and couldn't figure out what was going wrong. At first I had the problem with previous cookies keeping me logged in -- so authentication succeeded (failed to lock me out) anyway and there was no difference until I cleared them, but I was getting an exception. I searched the comments to see if anyone else had the same problem and saw the:
"redirect()->route('home')"
edit in a reply to someone's question. Not knowing that this was what I was supposed to have done in the first place. So I looked up the difference between RedirectResponse::guest() & RedirectResponse::route(). It looks as though guest() is intended to record where they were *trying* to go before being caught by the authentication. I imagines this is for redirecting them back there after authentication.
Anyway, I started experimenting, so to those that are interested; here's what I have in my Laravel v5.2 - App\Http\Middleware\Authenticate::handle()
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
//original code below. Does not work as intended.
// return redirect()->guest('home');
//throws NotFoundHttpException in RouteCollection.php line 161:
//experiments
// return redirect()->guest();//500 Error
// return redirect()->guest('');//works -> home / index.php
// return redirect()->guest('/');//works -> home / index.php
//manually added redirects that work as intended
// return redirect()->home();//works as was intended (send to home route)
return redirect()->route('home');//works as intended.
}
}
return $next($request);
}
I have followed your steps. When I go for a signup, data got inserted in the database successfully, but it is not redirecting me to the Dashboard View. Will you please help me out? +Mindspace
Which view is instead getting returned?
You should have
return redirect()->route('dashboard');
...in your SignUp controller.
i can't protect my routes because am using laravel 5.3
i used the ''auth 'middleware in the Exceptions/Handle.php buh still not working
please help me
Grate work Max really appreciate it. But I have one question about authentication. Why in this app are you not displaying an error message when logging authentication failed ? Thanks
+Dushyant Patel
Hi Dushyant, really only for simplicity reasons. Of course you would show such errors in a real app, but I try to put a focus on a specific logic or block of code in my tutorials. And I do explain (in other videos of this series) how to add a message to a request and how to show it in a view, therefore I left it out here.
hi max, i'm having trouble with middleware, i did what you did in this video but i still redirect to dashboard, please reply as soon as your read this, thank you.
+Kurt Dela Rosa
Hi Kurt,
I always reply but only as soon as I have time, because you're not the only one commenting on my videos. So please stay away from comments like 'please reply as soon as your read this', because I really hate to read stuff like this.
And of course I can't fix any problem without more details. Please post your code or a link to your github repo.
hello sir in my laravel application not work Middleware & Route Protection.
Does it work restricting users to view pdf files? thanks :)
I cant make it to work, whenever i type "localhost/test/public/dashboard" it keeps landing in dashboard
1. im on laravel 5.3 and theres no authenticate but i found this RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
return redirect()->route('home');
}
return $next($request);
}
can still make it to work
2. I saw that i can use handler.php but i still cant make it work
please help me thanks
an update i tried clearing the session and now my problem is this error is appearing
"NotFoundHttpException in RouteCollection.php line 161:"
:(
This basically is a 404 error, looks like you're accessing some route which doesn't exist. Did you compare your code to mine (link in description) - maybe some small typo?
github.com/mschwarzmueller/laravel-basics-youtube/blob/master/app/Http/routes.php
Route::get('/dashboard', [
'uses' => 'PostController@getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
here is my route
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
im totally lost right now, somehow whenever i access dashboard error 404 still persist
and should i create an authenticate.php file, (im currently using laravel 5.3) or handler.php?
No, use the Exception handler file - I do have a video explaining this on this channel: ruclips.net/video/QlZ6QrlK29g/видео.html
there is no authenticate.php in laravel 5.4 how can I adapt it to it
You can find it at 'app/exceptions/handler.php'
+Mindspace , not getting into the Dashboard through signin & signup process. Pls help me out of this. route file:-
Route::group(['middleware' => ['web']], function(){
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup',[
'uses' => 'UserController@postSignUp',
'as' => 'signup'
]);
Route::post('/signin',[
'uses' => 'UserController@postSignIn',
'as' => 'signin'
]);
});
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Puh, that code is unreadable unfortunately :/
But I do see, that you still use the "web" middleware. That isn't needed anymore, so you should remove it. Maybe this fixes your problem, otherwise I need a bit better formatted code in order to be able to help ;)
thanks
cool
Hey Max.....Thanks for making this kind of video...it is very very easy for beginners..Thanks a lot Max.!!
Awesome to hear that, thanks so much for your great feedback!
Hahaha you have angular 2 on your mind.You are my new favourite teacher.It took me months to just get started with laravel. I started tonight and with other videos i nearly through my pc through window just by trying to install laravel. Thank you for great videos.Will buy your udemy course.
+Jacques van Wyk
Yes, the transition from Angular 2 to Laravel was kind of difficult (regarding the naming) after doing a lot of Angular 2 videos ;D. I'm very happy to hear that you're liking my content! :)
laravel 5.3 users clean your cache.
Can you help with that Laravel 5.3 Authenticate.php problem? I'm stuck so badly -_-
Also see the other comment :)
I am currently using laravel 5.3 . I cant find the Authenticate.php under middleware? DO i have to create it manually or there is another file here that i can use that has the same function from 5.2?
nvm i found the answer on the comments section. cheers*
i need the answer too
Hi,
I'm using the Laravel 5.3 and I am on the chapter 6 middleware and route. I don't find the Authenticate.php to change the routing. Where is it??
app/exceptions/handler.php
Thanks for the tutorial :)
So for a multi-level user system I just need to define middlewares for filtering users' role (e.g. "admin" middleware filters user in 'admin' role) and put it in the specified routes. Ahh never thought about that.. I usually filter roles in action methods in the controller, which makes my controllers fat and ugly :D
and I just realized that 'web' middleware group is actually mandatory for web routes.
Great to hear that this video was helpful to you! :)
Regarding the web middleware: That was only required during one Laravel version - with the most recent version, this group is no longer necessary (and actually shouldn't be used anymore)
If i had do the same for 5.4 ?
Nice video bro ;)
I like your angular2 php laravel video
heheh :D
+Igor Birjukov
Certainly something which will come, no worries ;)
I am new to laravel and I must say that your videos are awesome and are easy to follow. Keep up the great job! You earned yourself a new subscriber :)
Thanks so much Martin - and welcome on board of the channel! :)
It's not working.the dashboard still connecting when adding dashboard in the url. What could be the reason?
Maybe you are still logged in? Try clearing your session or call Auth::logout() in some method/ controller action to make sure you are not logged in.
ya..that was the problem and it fixed now.But thanks for replying so fast..you doing great job.can you make a video on making an search function.that will be very helpful to us
Certainly something which I might do in the future - it's on the list of ideas ;)
Hmmm. I'm having a problem here. I followed your step exactly but when I added the 'middleware' => 'auth' I keep on getting redirected when I logged in - before it was working.
+Anthony Dale Chua +Arman Balgatai Sorry, didn't see this comment until now... So you're redirected back even though you log in with the correct credentials? Did you try logging out (Auth::logout() somewhere in your code which gets called) and login again?
Can you share a github repo with code?
All the folders are missing in this repo
I'm using laravel 5.5 how can i adapt?
For the guys having isses with Laravel 5.5.
i took a look at the docs, and here is the solution:
we have to add write the dashboard Route like this:
Route::get('/dashboard', [
'uses' => 'UserController@getDashboard',
'as' => 'dashboard',
])->middleware('auth');;
and also change the Route::group(['middleware' ..
name('home); to name('login');
Awesome ...
+ARNAB MUNSHI
Great to hear you like it!
Hey +Mindspace . Loving the tutorials, they're great. Sorry to bother you but I'm not being redirected to my dashboard when logging in but being redirected to the login page. The dashboard is inaccessible when typing the URL directly so it's working to an extent but just I'm not able to login. I'm using laravel 5.4 and the web.php and Handler.php files. I've tried logging in via chrome's incognito mode and this still doesn't work so I'm not certain what is happening. Any help would be great :) Thank you.
Did you have a look at my code (link in video description => pick the right github branch there)? I unfortunately can't dive into your code but by comparing it, you should be able to find out what's going wrong.
+Mindspace Thank you for the prompt response 😊 I haven't yet looked at this but I will. I get what's going on and change what I believe I think is not working but nothing happens. I'll let you know if anything changes once I've compared and amended according to you git repository. Thanks you, great videos, I'm enjoying the German accent. :)
github.com/Baz8706/MyVape/pull/2/files
In one of the previous videos in this playlist, you have an annotation that says not to put your routes into middleware groups with laravel 5.2+ as aren't needed any more. does that effect how this video works then? because you are doing middleware things in this video?
+Enkari7
The annotation only refers to the "web" middleware group which is no longer needed, not route grouping/ middleware groups in general. Such groups are still supported and necessary/ helpful :)
+Mindspace Thanks for the reply man. That leaves me slightly confused, though. Do I still need to place any of my routes in `Route::group(['middleware' => ['web']], function(){ }` at all? Or should it change to something like: `Route::group(function(){ }`?
No, you don't need this group anymore. I know that the videos are kind of confusing here, but that is something that simply changed a few weeks ago. No more web middleware needed :)
I really love this part 1:46
Yes we will view all your videos!!You are great teacher...
Great to have you on board Roland!
I'm getting this error for some reason..
NotFoundHttpException in RouteCollection.php line 161
+Abhishek Acharya never mind... I hadn't changed the redirect->guest to redirect->route in Authenticate.php...
Even after I corrected it, it kept giving me the same error.. till i cleared my cache...
you got to name the routes like
'as' => 'dashboard' for dashboard and
'as' => '/' for the root
angular2 again lul
I stopped following after this video, simply because things are getting really different in 5.5. Which is really a shame, coz I really like this tutorial and teachers style.
Why things have to change so fast?? ))
Sorry to hear that but yes, Laravel changed. I might cover 5.5+ in the future though :)
dude its quite easy, just check out the laravel docs.
otherwise, i just posted the solution to fix the errors.
I used your method for route protection. Works fine but when I logout and press browser's back button I am redirected again to the dashboard however this shouldn't be the case. How to fix?
+hamza nasim
That happens because the browser caches the page, you shouldn't be able to do anything on that page. If you want to disable the caching, check out this thread which discusses the very same issue you're describing here: stackoverflow.com/questions/31334306/how-i-prevent-browsers-back-button-login-after-logout
+Mindspace Thanks for reply. I have ran into another problem. All my facades have stopped working. It is saying,'Undefined class route'. All the facedes are giving underlined warnings.
Is the app still working (IDE only errors) or are you getting errors when running the app? Make sure that you import the Facades (e.g. "use Auth" at the top of the file for the Auth facade)
Resolved
Hai sir,
Till the login process it works great :-) and now am in confusion sir..
As u told in earlier tutorial about group middleware is not needed anymore I've removed my 'group middleware['web']' without that it works fine
and now in this tutorial should I want to include the '26th line'? which is in your tutorial ? as middleware
Reference & Routing
(NOTE:Refresh after visited the link)
tinypic.com/view.php?pic=k173vk&s=9#.V5Ncd0Z94dU
tinypic.com/view.php?pic=28vww&s=9#.V5NboUZ94dU
Yes, web middleware isn't needed anymore. Of course that doesn't affect any other middlewares which do totally different things
I've done all which u have done It run's perfectly with no error :-) Happy
N finally my dashboard is not protecting sir May i know the reason
oi65.tinypic.com/n2b9e1.jpg
Because it doesn't have the "auth" middleware. You may need to re-watch the video to fully understand what the "auth" middleware is doing. => It is protecting routes from unauthorized access. Routes which don't have it (like the dashboard) route therefore of course aren't protected :)
Again Thanks for your response sir :-)
Feeling happy
After Checking the video again I'll back to U sir ;-)
How can I do the same in laravel 5.6
same probleme i need help
@@zikooo31 plzz give the solution if you get it and I will provide if i get the solution
Just check the other comments you ll find the solutions
In my Middleware folder I don't have Authenticate.php! Doing a search in my directory I have an Authenticate.php in vendor/laravel/framework/src..etc. I haven't seen anyone else have this problem in the comments so far.. Everything else works except it tries to redirect to /login by default I suppose.
This was changed with 5.3 (I assume you're using Laravel 5.3). You should now go to app/Exceptions/Handler.php and there (at the bottom) you can set the route to redirect to.
Handle.php doesnt have the funcion called handle. Do I need to write everything in that file at the bottom of handle.php file?
You don't need a "handle" function but it should have an "unauthenticated" function at the bottom. Change the redirection route there.
Thanks for replaying. And I did so, I changed the redirection, It says, Route.php not found.
Oh yeah I solved It :D . Thanks Sir
Lieber Maximilian, danke sehr fuer deine Tutorien!
Die sind so gut detaliert, dass man wirklich eine Menge davon lernen kann!
Freut mich sehr das zu hören Garik! Danke für das tolle Feedback!
thanks man great job
Many thanks to you! I'm glad that you're liking it!
Your videos are so much helpful for me. Thanks for all your videos.
I am using laravel 5.4 , in middleware folder you have mentioned about the authenticate.php but I can't locate this file in this folder. can you help me?
Thanks in advance
the tutorial is based on Laravel 5.2. so that folder and file structure is different
Mohnazim Uddin , thanks for the reply.
Can you tell me where I can locate that authenticate.php file in laravel 5.4
App>Http>Middleware>redirectauthintcated.php
Mohnazim Uddin , thanks a lot.
welcome dear
How can you prevent the user from accessing the sign in page when you're authenticated already?
You can use the "guest" middleware for that. It does exactly the opposite of the "auth" middleware.
Thanks man, your tutorials are awesome! I watched your laravel beginners step by step, it really helped me to start using laravel.
That's awesome to hear Kenneth, thank you! :)
I have another question, when I'm authenticated and I enter the sign in url manually, I'm being redirected to the dashboard which is what I want, but when I logout, sign in again and click back, I can still see the sign in page, how can I prevent this?
That's simply your browser cache. You won't be able to do anything on the old page.
I placed the route codes outside middleware group for that I get back error message successfully as your previous tutorial but in this video you are showing that inside middleware .now I am confused how to solve this problem.please suggest how to restrict unwanted entrance keeping the route outside the middleware group.
+arfin miah
This video still shows the old code because it was recorded with an older version of Laravel. That's why I placed the annotation in the older video => Keep your routes outside of the web middleware group
+Mindspace Thanks for reply!!
but I placed the codes outside the middleware yet It does not work.
here is my route code.::
Route::group(['middleware' => ['web']], function(){
});
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::post('/signup', [
'uses' => 'userController@postSignup',
'as' => 'signup'
]);
Route::post('/signin', [
'uses' => 'userController@postSignIn',
'as' => 'signin'
]);
Route::get('/dashboard',[
'uses' => 'userController@getDashboard',
'as' => 'dashboard',
'middleware'=>'auth'
]);
+arfin miah please mention where my error is.
Okay, I got your point now. The comment regarding placing routes outside of middleware was only referring to the "web" middleware, not middleware in general! Absolutely use route groups with middleware for things like auth etc.
+Mindspace
Me also getting the same problem but didn't get this line :- please brief. "use route groups with middleware for things like auth etc."
Hi there.
I've been following your tutorials, which are awesome by the way, but on this one, things didn't went as the should.
I did everything like you, believe I did it a bunch of times, and saw it even more, but it just don't work. Everytime I go to the dashboard, he just lets me, even without being logged in. No error messages on the console, nothing. It's like the isn't even there
Can you give some lights? I'm really desperate right now.
Thanks in advance.
+Carla Sousa
Hi, thanks for the nice words, I'm happy that you like it!
Now regarding your issue: Always hard to diagnose from the distance. By the description it seems most probable that that something's wrong with the middleware. Here are some ideas: 1) Maybe a dumb question, but just to be sure: Is the middleware applied to the dashboard route (i.e. 'middleware' => 'auth')?
2) Are all your routes within the 'web' middleware group?
3) Is your User-Model correctly set up?
If all these steps are a 'yes', then maybe it's a good idea to check if the user login is working. One possibility would be to add an if-statement to the dashboard blade template like the following: @if(Auth::check)User is logged in@endif.
If this works, then we know that user login etc. works correctly.
If nothing helps, it's best if you could copy & paste the code of your routes.php, the kernel.php and the authentication.php (middleware)
+Mindspace
Tried to check if the user was logged, but he didn't liked the "Auth::check" said he didn';t recognized the "check". But anyway, I really tested my login before, because I wanted to make sure that it was sending out all the error messages.
Those are my routes:
Route::group(['middleware' => ['web']], function () {
Route::get('/', [
'uses' => 'UserController@login',
'as' => 'login'
])->name('login');
Route::get('/register', [
'uses' => "UserController@register",
'as' => "register"
]);
Route::post('/registeUser', [
'uses' => "UserController@registUser",
'as' => 'registeUser'
]);
Route::post('/loginUser', [
'uses' => "UserController@loginUser",
'as' => 'loginUser'
]);
Route::get('/dashboard', [
'uses' => "UserController@viewDash",
'as' => 'dashboard',
'middleware' => 'auth'
]);
});
The authenticate (middleware)
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('login');
}
}
return $next($request);
}
And the Kernel
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
+Carla Sousa
Hi, my bad it would be Auth:check() (with parentheses).
All the code seems fine to me...would be good if you could run this check, because maybe you ARE logged in (we haven't implemented a logout feature yet).
If you want to logout the user you could try this with Auth::logout() (e.g. on the login action in your UserController, which returns the login view)...maybe it will then work.
+Mindspace
yeah now it worked, should have noticed that..
Yes the user is logged.
So I did the logout stuff, and it gave me an SQL error, missing 'remember_token' column on the database, is that why the middleware is not working ?
Well that is pretty nasty and hidden "error" ;-)
Hello there, really nice lessons you've got. I have a problem with protecting my "page" from unauthorized access. It passes through anyway. Is there any way you can help me ? :) tried all i knew..
or maybe auth cached or whatever. I've been trying to restart my xampp server and to clear chrome cache. Nothing helps..
+Олександр Брико Great to hear, you're enjoying the lessons. Your issue sounds like some middleware is missing or maybe you're still logged in? I made the error of not implementing the logout-functionality in this video, therefore there is no chance of logging out. Another user hat the same "issue". Try running "Auth::logout()" somewhere in your Controller and see if you can still access the protected routes.
+Mindspace Was hard to do this in the morning, but after few mistakes in code it WORKED ! Thank you alot, dude. You've got +1 fan from Ukraine :)
Awesome man! See you in the other videos! :)
+Олександр Брико I had the same problem. Add this function in your UserController:
public function signOut()
{
Auth::logout();
return redirect()->route('home');
}