How do I fix the Laravel page not found error? - laravel

After registering, it redirects to / home. But I get a 404 error. When I set the route to / home, I get 302 continuous routing errors.
RegisterController.php
use RegistersUsers;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest');
}
Route.php
Auth::routes(['verify' => true]);
Route::get('/', 'HomeController#index')->name('home');
HomeController
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}

if you have in your HomeController's construct a middleware that requires the user to be logged in then what you are getting is normal.
You should have a login page wich use the "guest" middleware.
or
login the user automatically once he registers before redirecting him to your home route.
Auth::login($user)
//or
Auth::loginUsingId($userId);

Remove guest middleware.
public function __construct()
{
$this->middleware('guest');
}
Your HomeController should look like
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
}
your route.php Look like
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
RegisterController should look like
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
make sure you're following laravel authentication.

Related

Laravel jwt returns 500, on unauthorized

I use jwt for my api authentication. when I use wrong token it returns 500 and I get the error that rout login is not defiend!
I'm using laravel 8 and "tymon/jwt-auth": "^1.0". my default guard is api and api driver is jwt.
I tried name login route as login, bu then I get error that get method is not supported for this route but I'm using Post method!
rout : api.php:
Route::group(['prefix'=>'v1'],function (){
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'App\Http\Controllers\AuthController#login');
Route::post('logout', 'App\Http\Controllers\AuthController#logout');
Route::post('refresh', 'App\Http\Controllers\AuthController#refresh');
Route::post('me', 'App\Http\Controllers\AuthController#me');
});
});
AuthController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}
/**
* Get a JWT via given credentials.
*
* #return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
user model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
error that I get:
Symfony\Component\Routing\Exception\RouteNotFoundException: Route [login] not defined. in file C:\wamp64\www\medrep-app\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 444
🧨 Route [login] not defined
Try to change your routes, by adding a route name, and Add a GET request for route.
Route::group(['prefix'=>'v1'],function (){
Route::group([
'middleware' => 'api',
'as' => 'api.',
'prefix' => 'auth'
], function ($router) {
Route::post('login', 'App\Http\Controllers\AuthController#login')->name('login');
Route::get('login', 'App\Http\Controllers\AuthController#sessionExpired')->name('sessionExpired');
Route::post('logout', 'App\Http\Controllers\AuthController#logout')->name('logout');
Route::post('refresh', 'App\Http\Controllers\AuthController#refresh')->name('refresh');
Route::post('me', 'App\Http\Controllers\AuthController#me')->name('me');
});
});
The login & sessionExpired function may have this code as exemple:
public function login()
{
dd('test token');
$credentials = request(['email', 'password']);
if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function sessionExpired()
{
return response()->json(['error' => 'session expired'],401);
}
In Postman make sure you are using POST method:

Send email when user registering in Laravel

I would like to send an email to a user that kinda says "Account created successfully" when user registration is done. I use tailwindcss ui. Below you can see pictures of controllers. I think I should write the code in the RegisterController. So, when someone registers, the system will automatically send mail to the new user.
Controllers
RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
What should I do here?
you can send an email by using the Mail facade with the ::send method. Here follows an example:
$to = 'receiver_name';
$email = 'receiver_address';
$mail_data = array(
//here you can pass data to the email blade view
);
Mail::send('viewname', $mail_data, function ($message) use ($to, $email) {
$message->to($email, $to)->subject('subject text');
$message->from('Sender name');
});
you can send a mail using notification. notify the user when he/she registers to the system. in your RegisterController
use App\Notifications\WelcomeEmail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user->notify(new WelcomeEmail($user));
return $user;
}
now make the notification class with the artisan command
php artisan make:notification WelcomeEmail
and content for your notification class is
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class WelcomeEmail extends Notification
{
use Queueable;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($user)
{
$this->user = $user;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->view(
'welcome_email', ['user' => $this->user]
)
->from('support#yourcompany.com', 'Your Company Name')
->subject('Welcome Aboard');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
and finally make a blade file in the views folder welcome_email.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
</head
<body>
<h1>Hello {{ $user->name }}, Account created successfully</h1>
</body>
</html>
if you don't want to use notification, you can use the Mail facade to send a mail.
use Illuminate\Support\Facades\Mail;
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Mail::send('welcome_email', compact('user'), function ($message) use ($user) {
$message->to($user->email, $user->name)->subject('Welcome Aboard');
$message->from('support#yourcompany.com', 'Your Company Name');
});
return $user;
}
if you have set MAIL_FROM_ADDRESS in your env file you can skip the from part in the mail send function.

Change login rules at Laravel 5.6

I have a fresh project of Laravel 5.6 installed. I changed create_users_migration, added $table->boolean('is_active'); field. Now, I want when user is trying to login, to check if is_active field is set to true.
I tried to rewrite standard AuthenticatesUsers method :
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
After password I added line 'is_active' => true, , and now, when I press Log In button, it returns me an array_map(): Argument #2 should be an array error.
I tried to just copy-paste this method in LoginController, but it gives me same error. Any ideas, or may be is here another solution?
Full LoginController code :
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* Validate the user login request.
*
* #param \Illuminate\Http\Request $request
* #return void
*/
protected function validateLogin(Request $request)
{
$this->validate($request, [
$this->username() => 'required|string',
'password' => 'required|string',
'is_active' => true,
]);
}
}
You are editing the wrong method. This method validates the request and "true" is not a validation rule, that's why you are getting the error.
Here is a simple solution. Override the credentials method on your LoginController as below.
protected function credentials(Request $request)
{
$data = $request->only($this->username(), 'password');
$data['is_active'] = true;
return $data;
}
So this way only active users can login.
You can also create a middleware and use it to send the users that have not activated their account to activation page.
I did this for one project with a middleware :
<?php
namespace App\Http\Middleware;
use Closure;
class isActiv
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if($request->user()->isActiv()){
return $next($request);
}else{
return redirect()->route('dashboard')->with('errors', 'Votre compte utilisateur n\'est pas activé sur le site. Veuillez contacter un administrateur pour résoudre le problème.');
}
}
}
Then in my route file web.php :
Route::group(['middleware' => ['isActiv'] ], function(){
And in my user model :
public function isActiv(){
if($this->is_activ == 1 || $this->is_admin == 1){
return true;
}
return false;
}

User authentication in laravel using middleware

I have a question about the built in user authentication functionality in laravel. I got the authentication part to work but it doesn't seem like a user is stored in the session.
Admin Controler Code:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator, Input, Redirect;
use DB;
use Session;
class AdminController extends Controller
{
public function index(Request $request)
{
if(isset($_POST['submit'])){
$v = Validator::make($request->all(), [
'email' => 'required',
'password' => 'required',
],
[
'required' => 'This field is required.'
]);
if ($v->fails())
{
$messages = $v->messages();
return redirect()->back()->withErrors($v)->withInput();
}
else
{
$email = $request->input('email');
$pass = $request->input('password');
$whereData = [
['email',$email],
['password',md5($pass)]
];
$res = DB::table('tbl_admin_users')->where($whereData)->get();
if(!empty($res)){
$userid=$res[0]->id;
$fname=$res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
return Redirect('admin/dashboard-listing');
}
else
{
Session::flash('message', 'Email/Password is invalid!');
Session::flash('alert-class', 'alert-danger');
return Redirect('admin/login');
}
}
}
else{
return view('admin.admin-login');
}
}
public function logout()
{
Session::flush();
return Redirect('admin/login');
}
}
Middleware Authentication.php code:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class Authenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}
return $next($request);
}
}
AuthController I have:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Route after correct details and login page route:
Route::get('/admin/dashboard-listing',array('uses'=>'Admin\AdminDashboardController#index'));
After logout redirect route:
Route::get('/admin/login',array('uses'=>'Admin\AdminController#index'));
My question is that how can i use middleware in this code. because
after logout i can easily access the url .back button is also worrking
i want laravel user authentication through middleware ..
You need to manually login user with auth()->login():
$res = DB::table('tbl_admin_users')->where($whereData)->first();
if(!empty($res)) {
$userid = $res[0]->id;
$fname = $res[0]->fname;
Session::put('userid', $userid);
Session::put('fname', $fname);
auth()->login($res);
return Redirect('admin/dashboard-listing');
}
Alternatively, you can use the auth()->loginById($res->id) method.

Limit login attempts in Laravel 5.2

I am created a Laravel 5.2 application; I need to limit failure login attempts.I am created a AuthController with following code; But not working logging attempt lock.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Auth;
use URL;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
protected $maxLoginAttempts=5;
protected $lockoutTime=300;
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
$this->loginPath = URL::route('login');
$this->redirectTo = URL::route('dashboard'); //url after login
$this->redirectAfterLogout = URL::route('home');
}
public function index()
{
return 'Login Page';
}
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(Request $request)
{
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::attempt($credentials, $request->has('remember'))) {
return redirect()->intended($this->redirectPath());
}
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return redirect($this->loginPath)
->withInput($request->only('username', 'remember'))
->withErrors([
'username' => $this->getFailedLoginMessage(),
]);
}
/**
* Get the needed authorization credentials from the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
protected function getCredentials(Request $request)
{
return $request->only('username', 'password');
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'password' => bcrypt($data['password']),
]);
}
}
After many failure login their is no error message displayed. I am added some line to display error in login.blade.php file
Assuming you have implemented the make:auth artisan command of laravel.
Inside of the loginController, change the properties:
protected $maxLoginAttempts=5; to protected $maxAttempts = 5;
and
protected $lockoutTime=300; to protected $decayMinutes = 5; //in minutes
you need to use ThrottlesLogins trait in your controller
....
use AuthenticatesAndRegistersUsers, ThrottlesLogins ;
...
take a look here https://github.com/GrahamCampbell/Laravel-Throttle
and here https://mattstauffer.co/blog/login-throttling-in-laravel-5.1
Second link is for L5.1, but I think shouldnt be different for L5.2
Hope it helps!
Have a nice day.
Just overriding the following 2 functions maxAttempts and decayMinutes will be good to go. This 2 functions belong to Illuminate\Foundation\Auth\ThrottlesLogins.php file. I have tested on Laravel 5.6 version and working fine.
public function maxAttempts()
{
//Lock on 4th Failed Login Attempt
return 3;
}
public function decayMinutes()
{
//Lock for 2 minutes
return 2;
}

Resources