I have viewed a lot off documents already. I am trying to do my login, but its not working. Showing errors. I don't know the reason.i am very new in laravel
This is my controller code
public function do_login()
{
$credentials = [
'username'=>Input::get('username'),
'password'=>Input::get('password')
];
$rules = [
'username' => 'required',
'password'=>'required'
];
//validating the credentials.
$validator = Validator::make($credentials,$rules);
//in case the credentials are valid. Try to login the user.
if($validator->passes())
{
if (Auth::attempt($credentials))
{
//if successfull redirect the user
return Redirect::to('home');
}
else
{
//else send back the login failure message.
return Redirect::back()->withInput()->with('failure','username or password is invalid!');
}
}
else
{
//send back the validation errors.
return Redirect::back()->withErrors($validator)->withInput();
}
}
this is my model code:
<?php namespace LARAVEL\laravel_1st_project\models\UserModel;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class UserModel extends \Eloquent implements UserInterface , RemindableInterface
{
public $table = "user";
protected $primaryKey = 'employee_id';
//public $timestamps = false;
}
this is my app\config\auth.php :
'model' => 'LARAVEL\laravel_1st_project\UserModel',
'table' => 'user',
'reminder' => array(
'email' => 'email.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
Error :
Related
I'm doing something wrong?
My If (Auth::attempt($validated)) {} always fails when I change default user. But work with default user. Maybe i forgot any config in my new user 'personal'?
config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Personal::class,
],
App/Models/Personal.php
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Personal extends Authenticatable
{
use HasFactory;
protected $table = 'personals';
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
App\Http\Requests\AuthRequest.php
use Illuminate\Foundation\Http\FormRequest;
class AuthRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required'
];
}
}
App\Http\Controller\AuthController.php
public function login(AuthRequest $request)
{
$validated = $request->validated();
if ($validated) {
\Log::info($validated); //<- so far it works
if (Auth::attempt($validated)) { //<- this if always fails with personal model, but it work with default user model
\Log::info('test');
$personal = Auth::user();
return redirect()->route('dashboard');
}
return redirect()->back()->withInput()->withErrors(['algo deu errado']);
}
return redirect()->back()->withInput()->withErrors(['Preencha todos os campos']);
}
$validated = [ 'email' => 'teste#outlook.com', 'password' => 'teste123', ];
I get a 404 error when I try to insert user's details into multiple tables during registration
my user model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username','accno', 'email', 'password', 'role', 'status', 'activation_code'
];
protected $guarded = [];
/**
* 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',
];
// a mutator for the email attribute of our model with email validation check and check to avoid duplicate email entries.
protected $table = 'users';
public $timestamps = false;
public $incrementing = false;
public function setEmailAttribute($email)
{
// Ensure valid email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \Exception("Invalid email address.");
}
// Ensure email does not exist
elseif (static::whereEmail($email)->count() > 0) {
throw new \Exception("Email already exists.");
}
$this->attributes['email'] = $email;
}
public function setPasswordAttribute($password)
{
$this->attributes['password'] = Hash::make($password);
}
public function profiles()
{
return $this->hasOne(profiles::class);
}
public function accounts()
{
return $this->hasOne(accounts::class);
}
public function transactions()
{
return $this->hasMany(transactions::class);
}
}
I try refactoring by separating my validation code from my logic using RegisterUserTrait
<?php
namespace App\Traits;
use App\User;
use App\Profile;
use App\Account;
use Keygen;
trait RegisterUser
{
public function registerUser($fields)
{
$user = User::create([
'username' => $fields->username,
'accno' => $this->generateAccountNumber(),
'email' => $fields->email,
'password' => $fields->password = bcrypt(request('password')),
'roles' => $fields->roles,
'activation_code' => $this->generateToken()
]);
Profile::create([
'accno' => $user->accno,
'username' => $user->username,
'acc_type' => $fields->acc_type,
'firstname' => $fields->firstname,
'lastname' => $fields->lastname,
'nationality' => $fields->nationality,
'occupation' => $fields->occupation,
'address' => $fields->address,
'city' => $fields->city,
'state' => $fields->state,
'zipcode' => $fields->zipcode,
'phoneno' => $fields->phoneno,
'dob' => $fields->dob,
'gender' => $fields->gender,
'martial_status' => $fields->martial_status,
'user_image' => $fields->user_image,
]);
Account::create([
'accno' => $user->accno,
'username' => $user->username,
]);
return $user;
}
then storing the data using my registrationController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\RegistrationRequest;
use App\Traits\RegisterUser;
class RegistrationController extends Controller
{
use RegisterUser;
public function show()
{
return view('auth/register');
}
public function register(RegistrationRequest $requestFields)
{
//calling the registerUser method inside RegisterUser trait.
$user = $this->registerUser($requestFields);
return redirect('/login');
}
}
but when I register the user, the data is only saved in the create_user_table and return a 404 page not found error. How can I save the data to the selected table and redirect to the login page?
As fa as i can see this is not true for foreign key relations in User Model
public function profiles()
{
return $this->hasOne(profiles::class);
}
public function accounts()
{
return $this->hasOne(accounts::class);
}
public function transactions()
{
return $this->hasMany(transactions::class);
}
it should be as follows;
public function profiles()
{
return $this->hasOne(Profile::class);
}
public function accounts()
{
return $this->hasOne(Account::class);
}
public function transactions()
{
return $this->hasMany(Transaction::class);
}
Try this
public function registerUser($fields)
{
$user = User::create([
'username' => $fields->username,
'accno' => $this->generateAccountNumber(),
'email' => $fields->email,
'password' => $fields->password = bcrypt(request('password')),
'roles' => $fields->roles,
'activation_code' => $this->generateToken()
]);
$user->userprofile =Profile::create([
'accno' => $user->accno,
'username' => $user->username,
'acc_type' => $fields->acc_type,
'firstname' => $fields->firstname,
'lastname' => $fields->lastname,
'nationality' => $fields->nationality,
'occupation' => $fields->occupation,
'address' => $fields->address,
'city' => $fields->city,
'state' => $fields->state,
'zipcode' => $fields->zipcode,
'phoneno' => $fields->phoneno,
'dob' => $fields->dob,
'gender' => $fields->gender,
'martial_status' => $fields->martial_status,
'user_image' => $fields->user_image,
]);
$user->useraccount = Account::create([
'accno' => $user->accno,
'username' => $user->username,
]);
return $user;
}
If you are using a voyager package then there is a log file where you will find error messages that can help you understand the exact problem .
the log interface existe in voyager admin panel in :
Tools => Compass => Logs
look at this image :
Try this in your User model
protected static function boot()
{
protected static function boot()
parent::boot();
static::created(function ($user){
$user->profiles()->create([
'accno' => $user->accno,
'username' => $user->username,
.... => ....
]);
$user->accounts()->create([
'accno' => $user->accno,
'username' => $user->username,
]);
});
}
An error 404 is often a problem with a route.
As requested by Christos Lytras in a comment, we need to see your routes/web.php and the output of php artisan route:list to verify.
I believe the redirect in your registrationController is not pointing to a valid url:
return redirect('/login');
Without seeing your routes I can't say for sure but if your login route name is defined, you can do:
return redirect()->route('login');
Please share your routes file to confirm.
create() method is used for mass assignment. you will need to specify either a fillable or guarded attribute on the model. So check the fillable attribute on Profile and Account Model.
I do have trouble in setting password reset facility for custom user table (suppose 'customers' table). It was successful to generate a token for password reset but unable to do the reset because of Laravel considering its default table 'users', not the table I suppose to do reset. Changing default table users to customers in Config\Auth.php generate validation error
Passwords must be at least six characters and match the confirmation.
I just copy/pasting what I did so far
<?php
/*
Code Done by Arun
*/
namespace App\Http\Controllers\API\ResetPassword;
use App\Http\Controllers\API\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Password;
use App\Model\Customer;
use Laravel\Passport\Client;
use Illuminate\Support\Facades\Auth;
class ResetPasswordController extends Controller
{
use ResetsPasswords;
public function __construct()
{
$this->middleware('api');
}
protected function guard()
{
return Auth::guard('api');
}
public function ResetPassword(Request $request)
{
$v = validator($request->only('email', 'token', 'password','confirm_password'), [
'token' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string',
'confirm_password' => 'required|string|min:6',
]);
if ($v->fails()) {
return response()->json(["error"=>$v->errors()->all()], 400);
}
else
{
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
});
}
return $response == Password::PASSWORD_RESET
? $this->sendResetResponse($response)
: $this->customResetFailedResponse($request, $response);
// $client = Client::where('password_client', 1)->first();
// $request->request->add([
// 'grant_type' => 'password',
// 'client_id' => $client->id,
// 'client_secret' => $client->secret,
// 'username' => $request->email,
// 'password' => $request->password,
// 'scope' => null,
// ]);
// // Fire off the internal request.
// $proxy = Request::create(
// 'oauth/token',
// 'POST'
// );
// return $response ;
}
}
Any Laravel expert can help me with the problem?
Im finally able to figure this out, im just posting answer may help others come across the same problem.
<?php
namespace App\Http\Controllers\API\Auth;
use App\Http\Controllers\API\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Password;
use App\Model\Customer;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Client;
use DB;
class ResetPasswordController extends Controller
{
use ResetsPasswords;
protected $confirmEmail = false;
public function __construct()
{
}
public function resetPasswordCustomer(Request $request)
{
//Custome password reset mail has done in customer model
$v = validator($request->only('token', 'password','password_confirmation'), [
'token' => 'required|string|max:255',
'password' => 'required|string',
'password_confirmation' => 'required|string|min:6',
]);
if ($v->fails()) {
return response()->json(["error"=>$v->errors()->all()], 400);
}
else
{
$request->merge(['email'=> $this->checkTokenAgainstHashedValue($request->token)]);//Add new property to request..
$response = $this->broker()->reset(
$this->credentials($request), function ($user, $password) {
$this->resetPassword($user, $password);
});
}
return $response == Password::PASSWORD_RESET
? $this->authToken($request)
: $this->customResetFailedResponse($request, $response);
return $response ;
}
protected function checkTokenAgainstHashedValue($token)
{
$resetTable = DB::table('password_reset_customers')->select('token','email')->get();
foreach ($resetTable as $value) {
if (Hash::check($token, $value->token)) {
return $value->email;
}
}
return null;
}
protected function authToken(Request $request)
{
$http = new Client();
$response = $http->post('http://abcd.com/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 2,
'client_secret' =>'qazrxGbDwrwbYXwbEbbkUFNO1zGB3eFYQN3AbG3m',
'username' => Auth::user()->email,
'password' => $request->password,
'scope' => '',
],
]);
return json_decode((string) $response->getBody(), true);
}
public function broker()
{
return Password::broker('customers');
}
}
I am using Laravel 4.2 and I'm trying to auth my own model (I don't use User model).
The problem appears when pass the mail and password, then I use the method Auth::attempt and enters to else (that it corresponds to the error)
Usuario Controller
class UsuarioController extends BaseController{
function doLogin(){
$userdata = array(
'Correo' => Input::get('correo'),
'Contrasena' => Input::get('contrasena')
);
if(Auth::attempt($userdata)){
echo 'SUCCESS!';
}else{
echo 'Error!';
}
} ...
Usuario Model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Usuario extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $fillable = array(
'Nombre',
'Apellido',
'Rol',
'Correo',
'Contarsena',
'Cumpleanos',
'Foto',
'Pais',
'Comuna',
'Profesion_idProfesion',
'Institucion_idInstitucion',
'remember_token'
);
function profesion(){
return $this->belongsTo('Profesion', 'idProfesion');
}
public function getPasswordAttribute()
{
return $this->Contrasena;
}
public function setPasswordAttribute($Contrasena)
{
$this->Contrasena= $Contrasena;
}
public function getReminderEmail()
{
return $this->Correo;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword() {
return $this->Contrasena;
}
}
Auth.php
return array(
'driver' => 'eloquent', //database or eloquent
'model' => 'Usuario',
'table' => 'Usuario',
'username' => 'Correo',
'password' => 'Contrasena',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
Usuario Table
The application never crash but in the If Condition always enter to the ''else'' returns Error!
You have a typo in your fillable array:
protected $fillable = array(
'Nombre',
'Apellido',
'Rol',
'Correo',
'Contarsena',
'Cumpleanos',
'Foto',
'Pais',
'Comuna',
'Profesion_idProfesion',
'Institucion_idInstitucion',
'remember_token'
);
Contarsena should be Contrasena
And your auth array should contain a email and password key:
$userdata = array(
'correo' => Input::get('correo'),
'password' => Input::get('contrasena')
);
try
dd(DB::getQueryLog());
to get the the SQL executed. That makes troubleshooting easier.
My guess is that there's no 'password' field, which the attempt method will automatically hash
I'm trying to do a basic authentication which considers email and password. My problem comes when I call the method Auth :: attempt I get the following error.
Model
class Usuario extends Eloquent{
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $fillable = array('Nombre',
'Apellido',
'TipoUsuario',
'Contrasena',
'Correo',
'Telefono');
}
Controller
class UsuarioController extends BaseController{
public function doLogin(){
$rules = array('correo' => 'required|email',
'contrasena' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::to('usuario')
->withErrors($validator)// manda los errores al login
->withInput(Input::except('contrasena')); //
}else{
$userData = array(
'Correo' => Input::get('correo'),
'Contrasena' => Input::get('contrasena')
);
if(Auth::attempt($userData)){
echo 'bien';
}else{
return Redirect::to('login');
}
}
}
public function showLogin(){
return View::make('login');
}
}
Routte
Route::get('usuario', array('uses' => 'UsuarioController#showLogin'));
Route::post('usuario', array('uses' => 'UsuarioController#doLogin'));
Auth.php
return array(
'driver' => 'database',
'model' => 'User',
'table' => 'Usuario',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
In the process of checking user credentials Laravel calls validateCredentials method when Auth::attempt gets called and in this function (given below) Laravel checks for the password key in the passed array and in your case you are not passing a password key so the error happens.
public function validateCredentials(UserInterface $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
Change the key in the $userData array:
$userData = array(
'email' => Input::get('correo'), // If correo means email
'password' => Input::get('contrasena') // If contrasena means password
);
Also make changes in your database table's field names which represents users table, I think it's your Usuario table.
I'd check to make sure you're passing the correct info to Auth::attempt() in your controller. I use something more like:
$userData = array('email' => Input::get('email'), 'password' => Input::get('password'));