Laravel 5 Auth::attempt() always failing - php

my Auth::attempt() returning fail everytime, I'm using my own subscribers table, i have already changed settings in config/auth.php to use subscribers table.
below is my logincontroller
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Subscriber;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class LoginController extends Controller
{
public function login()
{
$email = Input::get('email');
$password = Input::get('password');
// $subscriber = Subscriber::where('email', $email)->first();
// $checked = Hash::check($password, $subscriber->pass);
if (Auth::attempt(['email' => $email, 'pass' => $password]))
{
return 'it workedddd.';
}
else
return 'failed';
}
}
subscriber model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subscriber extends Model
{
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['password', 'remember_token'];
}
subscriber controller
<?php
namespace App\Http\Controllers;
use App\Subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Requests;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
class SubscribersController extends Controller
{
public function newSubscriber(Request $request) //function to register new subscriber
{
$validator = Validator::make($request->all(), [
'firstname' => 'required',
'lastname' => 'required',
'email' => 'required|email|unique:subscribers,email',
'password' => 'required|min:5',
'address' => 'required',
'city' => 'required',
'state' => 'required',
'zip' => 'required',
'phone' => 'required|unique:subscribers,phone'
]);
if ($validator->fails()) {
return redirect('/register')
->withErrors($validator)
->withInput();
}
$subscriber = new Subscriber();
$subscriber->firstname = Input::get('firstname');
$subscriber->lastname = Input::get('lastname');
$subscriber->email = Input::get('email');
$subscriber->pass = Hash::make(Input::get('password'));
$subscriber->address = Input::get('address');
$subscriber->city = Input::get('city');
$subscriber->state = Input::get('state');
$subscriber->zip = Input::get('zip');
$subscriber->phone = Input::get('phone');
$subscriber->trial_time = 30;
$subscriber->date_signed_up = Carbon::now();
$subscriber->next_bill_date =Carbon::now()->addMonth(1);
$subscriber->account_status = 'trial';
$subscriber->save();
return $subscriber;
}
}
routes
Route::get('/', function () {
return view('home');
});
Route::post('/', 'LoginController#login');
Route::get('contact', function() {
return view('contact');
});
Route::get('register', function() {
return view('register');
});
Route::post('register', 'SubscribersController#newSubscriber');
Route::get('feedback', function() {
return view('feedback');
});
Route::get('dashboard', array(
'before' => 'auth.basic',
function(){
return view('dashboard.user');
}));

When using Auth::attemp()You can't do:
Auth::attempt(['email' => $email, 'pass' => $password])
It should be:
Auth::attempt(['email' => $email, 'password' => $password])
So in your case you should add the following to your User model:
public function getAuthPassword()
{
return $this->attributes['pass'];
}

In your newSubscriber method change
$subscriber->pass = Hash::make(Input::get('password'));
to
$subscriber->pass = bcrypt(Input::get('password'));
Your Subscriber model should look like this..
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Subscriber extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
protected $fillable = [
'firstname',
'lastname',
'email',
'pass',
'phone',
'address',
'city',
'state',
'zip'
];
protected $hidden = ['pass', 'remember_token'];
public function getAuthPassword()
{
return $this->pass;
}
}
Hope this will work.

Related

Spatie assignRole not working (Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync())

Spatie user role permissions not working
Here is my RoleController.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
public function saveUserRoles(Request $request)
{
$validator = Validator::make($request->all(), [
'role_name' => 'required|string|unique:roles,name',
]);
if ($validator->fails()) {
alert()->error(trans($validator->messages()->all()[0]));
return back();
}
$role = new Role;
$role->name = $request->role_name;
$role->guard_name = config('auth.defaults.guard');
$role->save();
alert()->success(trans('New Role Created Successfully!'));
return redirect()->route('admin.add.user.roles');
}
User Model
User.php
use Spatie\Permission\Models\Role;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class User extends Authenticatable
{
use Notifiable;
use SoftDeletes, HasApiTokens;
use HasRoles;
protected $fillable = [
'user_id', 'profile_image', 'name', 'email', 'address','phone','location','role_id','auth_type', 'password','status'
];
protected $hidden = [
'password', 'remember_token',
];
public function role()
{
return $this->belongsToMany(Role::class, 'role_id');
}
}
UserController
UserController.php
use Spatie\Permission\Models\Role;
use App\Http\Requests\UserCreateRequest;
public function saveUser(UserCreateRequest $request)
{
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role_id' => $request->role_id,
'status' =>0,
]);
$role = Role::find($request->role_id);
$user->assignRole([$role->name]);
}
When i try to create a new user it shows an error
BadMethodCallException
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::sync()
Here only need role option without any permissions
Here is your solution, as given in the documentation.

How to validate nested relation in request class in laravel

I have two model that are related.
Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'city',
'post_code',
'street',
'country'
];
protected $hidden = [
'created_at',
'updated_at',
'addressable_id',
'addressable_type'
];
public function addressable(): MorphTo
{
return $this->morphTo();
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Club extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
'phone',
'description',
'user_id'
];
protected $hidden = [
'created_at',
'updated_at'
];
public function address()
{
return $this->morphMany(Address::class, 'addressable');
}
}
For that models i've got Request class with validator rules.
Requests
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreAddressRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'city' => 'required|string|max:125',
'post_code' => 'required|string',
'street' => 'required|string',
'country' => 'required|string| max:125'
];
}
}
<?php
namespace App\Http\Requests;
use App\Traits\FailedValidation;
use Illuminate\Foundation\Http\FormRequest;
class StoreClubRequest extends FormRequest
{
use FailedValidation;
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|max:125',
'description' => 'required|string',
'email' => 'email:dns',
'phone' => 'string|max:125',
// 'address' => (new StoreAddressRequest)->rules(), ???
'images' => 'required|image'
];
}
}
Trying to create new club with address.
I'm sending request to API like that:
[
"name":"dfsdf",
"dsfsdf":"sdfsdf",
"address": {
"city": "name",
"post_code":"46-454"
}
]
Address may be added standalone or from other model that are related too.
Now only fields from club request are validated.
How to validate club and address request?

Laravel 7 change name of login credentials

I have a fresh installation of Laravel 7 without composer require laravel / ui. My goal is to change the default login as username/email and password.
Controller AuthController.php :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator,Redirect,Response;
Use App\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Session;
class AuthController extends Controller
{
public function index()
{
return view('login');
}
public function registration()
{
return view('registration');
}
public function getAuthPassword()
{
return 'sms_code';
}
public function postLogin(Request $request)
{
request()->validate([
'id_message' => 'required',
'sms_code' => 'required',
]);
$credentials = $request->only('id_message', 'sms_code');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard');
}
return Redirect::to("login");
}
public function postRegistration(Request $request)
{
request()->validate([
'id_message' => 'required',
'sms_code' => 'required|min:6',
'url_attribute' => 'required|min:6',
'mail_from' => 'required',
'mail_to' => 'required',
]);
$data = $request->all();
$check = $this->create($data);
return Redirect::to("dashboard");
}
public function dashboard()
{
if(Auth::check())
{
return view('dashboard');
}
return Redirect::to("login");
}
public function create(array $data)
{
return User::create([
'id_message' => $data['id_message'],
'sms_code' => Hash::make($data['sms_code']),
'url_attribute' => $data['url_attribute'],
'mail_from' => $data['mail_from'],
'mail_to' => $data['mail_to'],
]);
}
public function logout()
{
Session::flush();
Auth::logout();
return Redirect('login');
}
}
Metod App\Http\User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'mail_from',
'mail_to',
'url_attribute',
'sms_code',
'id_message',
];
protected $hidden = [
'sms_code', 'remember_token',
];
protected $casts = [
];
}
When i try fill login form with datas from database -> username as id_message and password as sms_code
Return this error:
ErrorException
Undefined index: password
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError
vendor/laravel/framework/src/Illuminate/Auth/EloquentUserProvider.php:156
line 156 of EloquentUserProvider.php->
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
Did i missing something ?
you can use simple login by this way :
public function postLogin(Request $request)
{
request()->validate([
'id_message' => 'required',
'sms_code' => 'required',
]);
$credentials = $request->only('id_message', 'sms_code');
if ($user=User::where($credentials)->first()) {
auth()->login($user)
return redirect()->intended('dashboard');
}
return Redirect::to("login");
}

404 error when submitting user form in the registrationController laravel

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.

Call to undefined relationship [] on model []

I have made hasOne relationship in my Model and it is working fine with following query in driver controller:
$drivers = Driver::with('vehicleInfo')->first()->toArray();
Driver Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Driver extends Model
{
// from_location_id
public function vehicleInfo()
{
return $this->hasOne('App\Vehicle','id','vehicle_id');
}
}
But when I try to use same code in AuthController which is generated by Laravel Auth it is giving me error of undefined relationship.
I have included model in AuthController. Which is as follows:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Carbon\Carbon;
use App\User;
use App\Role;
use App\Driver;
class AuthController extends Controller
{
public function login(Request $request)
{
$request->validate([
'mobile' => 'required|string',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['mobile', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
// print_r($user);
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$user_details = User::find($user->id);
if($user_details->actual_user_id>0){
// find driver details
// var_dump(Driver::with('vehicleInfo'));
$driver_details = Driver::with('vehicleInfo')->first()->toArray();
// var_dump($driver_details);
}else{
$driver_details = "";
}
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
'user_details'=>$user_details->toArray(),
'driver_details'=>$driver_details
]);
}
}
My relationship is public.
Please help.

Categories