I created another authentication as Admin in Laravel 5.7 Additionally to its default authentication. They both function correctly but, the new authentication that I have created does no show error messages
For fault login attempts as default authentication does.
here the code I used for LoginController created for Admin model.
public function showLoginForm(){
return view('admin.login');
}
//Validate the form data
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|string',
]);
//Attempt to lo the Admin in
$credential = [
'email' => $request->email,
'password' => $request->password,
];
//Attempt to log the Admin in
if(Auth::guard('admin')->attempt($credential, $request->member)){
return redirect()->intended(route('admin.home'));
}
//If unscuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email','remember'));
}
Please tell me how to fix this. Thanks.
you need to validate those data
// taken from the default auth controller
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
}
and in the blade file show the errors
such as
to diaplay all the errors
#if ($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
#endif
and to display the specific errors
<input type="text" name="firstname">
#if ($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
#endif
if you are not clear about that just watch the tutorial at
https://pusher.com/tutorials/multiple-authentication-guards-laravel
Related
I made a manual login system in a Laravel 9 API that it's works correctly, but when I try to use Auth::user() in another controller, I get it as null, but when I return the auth->user() to the Vue SPA, I get it correctly. Is there a way to it is setting Auth::user() null after a successfull login? Here's are my api.php (api routes):
route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
route::controller(UserController::class)->group(function () {
route::post('/register', 'register');
route::post('/login', 'login');
route::get('/logout', 'logout');
});
route::resource('book', BookController::class);
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
As you can see in the image above, I can get the authenticated user after try login it, here's my login method:
public function login(Request $request)
{
$validate = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
if ($validate) {
$credentials = $request->only('email', 'password');
return Auth::attempt($credentials)
? Auth::user() :
response()->json('No se ha podido iniciar sesiĆ³n', 500);
}
return response()->json($validate->errors, 422);
}
But when I'm going to store a new book, I get the following error:
Here's the error, when I try to use the auth()->user() method to get the logged in user's id:
public function store(Request $request)
{
$validate = $request->validate([
'title' => 'required',
'genre' => 'required'
]);
if ($validate) {
$book = Book::create([
'title' => $request->title,
'author' => $request->author,
'genre' => $request->genre,
'subgenre' => $request->subgenre,
'opinion' => $request->opinion,
]);
$user = User::find(auth()->user()->id);
if ($request->cover) {
$this->uploadImage($request, 'cover', $book);
}
$user->books()->save($book);
return new BooksResource($book);
}
I don't know why it's happening, and I'd like any idea or possible solution. Thanks in advance:
From laravel 9 documentation
// Get the currently authenticated user's ID...
$id = Auth::id();
Also, you should describe your
route::get('/my_books/{user_id}', [BookController::class, 'myBooks']);
route before resource route.
I guess, you dont need this assign $user = User::find(auth()->user()->id); just use auth()->user
To get the Authenticated user, put the book route inside the auth:sanctum middleware.
I'm trying to register a user in my application and log him in automatically after successfully registering.
What i'm doing:
Sending an HTTP request from the front-end using axios:
register() {
this.loading = true
axios.post('/api/v1/list/register', {
email: this.data.email,
password: this.data.password
}).then((re) => {
this.loading = false
})
}
Back-end controller:
public function register() {
$data = request()->validate([
'email' => ['required', 'string', 'email', 'unique:users'],
'password' => ['required', 'string', 'min:7',],
]);
$user = User::create([
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Auth::login( $user );
return response()->json([
'user' => Auth::user(),
]);
}
The user get's registered successfully and the server returns the user just fine, although when i refresh the page Auth::check() returns false as a result to display the register page again
<list-property :auth="{{ json_encode(Auth::check()) }}"></list-property>
#if(!Auth::check())
<login-dialog></login-dialog>
#endif
Routes web.php file
Route::get('/list-property', [App\Http\Controllers\MainController::class, 'listProperty']);
I used FILESYSTEM_DRIVER file and database, both had the same issue, what could be the problem?
For anyone who might be experiencing the same issue, the registration was happening through an API route which is incorrect, API routes are stateless, i moved the registration method inside web.php and it worked just fine.
My project is, after a user come registered redirect to verification page.
public function register(Request $request)
{
Session::put('mobile',$mobile)
$code = rand(10000,99999);
$user = User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'gender' => $request->gender,
'mobile' => $request->mobile,
//continue code
}
return redirect()->route('verification/?session'.$session);
}
To get the value of Session use
Session::get('mobile')
anywhere in the controller or in blade file or anywhere where Session::class accessible.
I am using the auth system that comes with laravel 5 and would like to send notification email after registration. I tried adding a method that sends email(and it works I tested) in postReigster method of AuthenticatesAndRegistersUsrers.php but it doesn't work.
Please help
The code I tried adding in registrar create and authandregister postRegister
$email = EmailTemplate::all()->first();
Mail::raw($email->topic, function($message) use ($data, $email)
{
$message->from($email->sender, $email->sender);
$message->to($data->email);
});
You must add your code in this file:
/app/Services/Registrar.php
to this function before return you must add something like:
public function create(array $data)
{
your_mail_function($data['email'], 'towhom', 'subject' );
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
I have a registration form and it was working until it just didn't. I am sure I did something with the code because I am new to laravel 4 so I am unable to identify my wrong doing. Now I am getting
This webpage has a redirect loop.
This is the route file:
Route::get('/','MainController#index');
Route::get('/login', 'MembersController#login');
Route::get('/signup', 'MembersController#signup');
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');
/* Handle authenticating a user when loggin in*/
Route::post('register', array(
'uses' => 'MembersController#register',
'as' => 'members.register'
));
and this is the form opening:
#section('content')
{{ Form::open(array('route' => 'members.register')) }}
......
{{ Form::close() }}
#stop
and this is the validation where if there is an error, it used to redirect to the sign-up page again and show them (and it did until it broke)
public function register()
{
$rules = array(
# place-holder for validation rules
'firstname' => 'Required|Min:3|Max:40|Alpha',
'lastname' => 'Required|Min:3|Max:40|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'country' => 'Required',
'password' =>'Required|AlphaNum|Between:7,15|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:7,15'
);
/*Create new user if no user with entered email exists. Use validator to ensure all fields are completed*/
$user = new User;
$validator = $this->validate(Input::all(), $rules);
if ($validator->fails())
{
return Redirect::to('register')->withErrors($validator);
}else{
echo "Success";
}
}
Thanks for the help :)
Change the following line
return Redirect::to('register')->withErrors($validator);
with this
return Redirect::back()->withInput()->withErrors($validator);
You are calling the route register infinite times.
Remove this route as well. You only need post route.
/*handled by controller to register the user that signed up*/
Route::get('/register', 'MembersController#register');