Laravel: Undefined variable: request - laravel

I don´t can find the problem. Where ist it? "Undefined variable: request"
public function login()
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'passwort' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'passwort' => $request->passwort], $remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(roue('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}

You need to inject Request object:
public function login(Request $request)
Also, add this line to the top of your class:
use Illuminate\Http\Request;
Alternatively, you can just use request() instead of $request in your code.

You have not defined the 'request' variable but you are using it in your code.
Edited Code
public function login(Request $request)
{
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'passwort' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'passwort' => $request->passwort], $remember)) {
// if successful, then redirect to their intended location
return redirect()->intended(roue('admin.dashboard'));
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'));
}
Also, add this line to the top of your class:
use Illuminate\Http\Request;

Related

Assigning the role while user registration Laravel

I'm trying to make a register page with role as a radio button(consumer, supplier, Admin)
but it show me this error when I test the query in postman
Error: Class "App\Http\Models\Role" not found in file
my controller:
public function register(Request $request)
{
$request->validate([
'first_name'=>'required|string',
'last_name'=>'required|string',
'email'=>'required|string|unique:users',
'password'=>'required|string|min:6',
'phone_number'=>'required|string|min:10',
'role_name'=>'required|string'
]);
$role_a = $request->role_name;
if ($role_a == 'صاحب متجر'){
$role=Role::select('role_id')->where('role_name','صاحب متجر')->first();
$user->roles()->attach($role);
return response()->json($user);
}
elseif ($role_a == 'مشتري'){
$role=Role::select('role_id')->where('role_name','مشتري')->first();
$user->roles()->attach($role);
return response()->json($user);
}
$user=User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'phone_number' => $request->phone_number,
]);
And my use statement:
use Illuminate\Http\Request;
use App\Http\Models\User;
use App\Http\Models\Role;
use Illuminate\Support\Facades\Hash;
And my route:
Route::post('/register','App\Http\Controllers\AuthController#register');
and this what I have in tables:
Note: I didn't use custom packages like spatie for example
Thank you for trying to help!
You miss adding the Request class as an argument into your method. Your method should look like this:
public function register(Request $request)
{
//after validation
$data = $request->validated();
}
Dont forget to add use Illuminate\Http\Request; in your use statement.

Laravel post request route

enter image description hereI have a following Controller in php laravel:
// .....
class RegisterController extends Controller
{
//...
//...
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
I use the following route:
Route::post('api/auth/register', 'Auth\RegisterController#create');
I am getting the following error: "Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected"
I need your help to pass Request parameters to my function (Form route properly)
Try changing your method parameter to Request $request
to obtain an instance of the current HTTP request via dependency
injection, you should type-hint the Illuminate\Http\Request class on
your controller method. The incoming request instance will
automatically be injected by the service container
and get the data from the request fields:
protected function create(Illuminate\Http\Request $request)
{
return User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
}
If you do not want to write all the Request namespace in the method parameter, add on the top of the file:
use Illuminate\Http\Request;
then, just use the name of the class:
protected function create(Request $request)
{
//...
}
You can do it in this way,
use Illuminate\Http\Request;
class RegisterController extends Controller
{
protected function create(Request $request)
{
$data = $request->all();
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}

Laravel - Can't upload the user in multiauth system

I am using multi auth login system. I made register, login and mail system. But i don't know how to make update function. Every member needs to update own profile. My problem is i can't get the related users details. id, name, etc...
In my auth.php customer guards was created:
'customer' => [
'driver' => 'session',
'provider' => 'customers',
]
Also this is the CustomerLoginController:
class CustomerLoginController extends Controller{
public function __construct()
{
$this->middleware('guest:customer')->except('logout', 'userLogout');
}
public function showLoginForm(){
return redirect()->route('homepage');
}
public function login(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required',
]);
if (Auth::guard('customer')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
return redirect()->intended(route('homepage'));
}
return redirect('/')->with('error_login', 'Login Fail');
}
public function logout(Request $request) {
Auth::guard('customer')->logout();
return redirect('/');
}
I added the function show($id) and function update(Request $request)
But as i told. Can't get the related user.
My last try is:
$user = Customer::find($id);
this is the right way to doing this i think. But i can't connect them.
ps: i am not using --resources (crud). I must do that manually.

Can Laravel Auth::attempt() handle relationships?

I'm using entrust for managing role based permissions in Laravel 5.3, and naturally using manual/custom logins for different user types. Is it possible for Auth::attempt() to handle foreign table relationships? Basically, I want to do something like this:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
But I keep getting the error that hasRole() is an undefined function. I have included use Zizaco\Entrust\Traits\EntrustUserTrait; and use EntrustUserTrait;, which I thought would provide me with access to the function, but apparently not.
I appreciate the fact that hasRole() is a method for user objects, and at the time of checking I don't have a user object but I can't do a role check after attempt has succeeded because then the user has already been logged in, and if the role was wrong I would need to log them out as their credentials are correct, but not for the role; which seems slow and not pragmatic.
How should I go about handling this? Is there an alternative to Auth::attempt that I can use that will not log in the user, but check the user exists with specified input, and then run the role check, and then use another function to start an authenticated session?
If useful my LoginController is here:
<?php
namespace App\Http\Controllers\Teacher;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class LoginController extends Controller {
use EntrustUserTrait;
public function showLoginForm() {
return view('teacher/login');
}
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
if(Auth::attempt(['email' => $request->email, 'password' => $request->password, hasRole('teacher') => true])) {
return redirect()->intended('teacher/dashboard');
}
return redirect('admin/login')->with('invalid', 'Invalid username or password');
}
}
Any help or direction would be much appreciated. Thanks.
what you can do is:
if(Auth::attempt(['email' => $request->email, 'password' => $request->password)) {
if($user = Auth::user()->hasRole('teacher')) {
return redirect()->intended('teacher/dashboard');
} else {
return redirect()->intended('teacher/dashboard');
}
}
so this is what I did on login check role
$user = User::whereEmail($request->email)->first();
// I added this is because the customer
// are not suppose to login from here
if(!$user || $user->hasRole(['customer'])){
return $this->sendFailedLoginResponse($request);
}
if ($this->guard()->attempt($credentials, $request->has('remember'))) {
return $this->sendLoginResponse($request);
}
then if you wanna to change the route base on user role you can try to replace the redirectPath method by simply
public function redirectPath()
{
$user = Auth::user();
if($user->hasRole(['admin', 'system_admin']))
return '/backend';
elseif($user->hasRole(['teacher']))
return '/teacher';
}
I ended up manually doing the authentication check and using Auth::login($user) to create the authenticated session. This way the user was only logged in provided they met the role requirements for the specific login portal and controller.
public function authenticate(Request $request) {
Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
])->validate();
$user = User::where('email', $request->email)->first();
if($user) {
if(Hash::check($request->password, $user->password) && $user->hasRole('teacher')) {
Auth::login($user);
return redirect()->intended('teacher/dashboard');
}
}
return redirect('teacher/login')->with('invalid', 'Invalid username or password');
}

Laravel 5 auth always results false?

Here its my controller for logging in. the register controller works well, it creates an user to database but when i try to log in with it fails it results always false pls help.
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
class loginController extends Controller
{
public function login(Request $request)
{
$_email = $request->input('emaillogin');
$_password = $request->input('passwordlogin');
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
Auth::login(Auth::user());
return redirect()->intended('/dashboard');
}
else {
return redirect()->intended('/');
}
}
}
Auth::attempt logs user into your application if passed, no need for second authentication
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
return redirect()->intended('/dashboard');
} else {
return redirect()->guest('/login');
}
As i said in the comment and i just tested it on my local pc, maybe it's wrong to you but for me it doesn't work if i use plain password save in database, here's my register file
protected function create(array $data)
{
$activation_code = str_random(60);
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'activation_code' => $activation_code
]);
if ($user->save()) {
$data = array(
'name' => $user->username,
'code' => $activation_code,
);
\Mail::queue('emails.activate', $data, function($message) use ($user) {
$message->to($user->email)->subject('Thank you for registering. Please activate your account!');
});
}
return $user;
}
you see i have crypted password
'password' => bcrypt($data['password']),
and if i test it just with:
'password' =>$data['password'],
The registration works but authentication fails because password must be encripted you should also remove Auth::login(Auth::user()); that is not necessary
if (Auth::attempt(['email' => $_email, 'password' => $_password])) {
return redirect()->intended('/dashboard');
}
This happens on my site when i don't use bcrypt on password in registration controller and try to login later
Whoops! There were some problems with your input.
These credentials do not match our records.
Also what i have seen from our login form inputs are not emaillogin and passwordlogin they are just email and password

Resources