Override attempt auth method in laravel 5 - laravel

I'm having a big problem with Auth:attempt method in laravel 5.2, and I wish I can override it.
I have the class users, by default, but doesn't containt the attribut 'email', this last one is containing in an other class user_contacts, with relation one to one with users.
Can I override this function? because by default, it takes 'email', which is not in users in my case
I tried to make that in the model, but not working:
lass User extends Authenticatable
{
public function __construct(array $attr = array())
{
parent::__construct($attr);
$this->email = $this->user_contacts()->email;
}
/**
* 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',
];
public function user_contacts()
{
return $this->hasOne('App\UserContact', 'user_id', 'id');
}
}
It just says that the email field is not defined.
Any suggestion plz?
Thanks alot.

Manually authenticating user https://laravel.com/docs/5.3/authentication#authenticating-users
You can use any field you want, 'email' field is just the default.
Something like this will work perfectly fine:
if(Auth::attempt(['username' => $username, 'password' => $password])){
return redirect()->intended('admin');
}

Related

Cannot sava data in database in notification file in Laravel

I'm using Laravel Notification and i want to save data in my database table if i write my insert query then i'm getting following error otherwise Notification are running :
TypeError: Return value of App\User::getLogNameToUse() must be of the
type string, null
This is the query
public function toMail($notifiable)
{
$users = User::find($notifiable->id);
$users->verification_link=$link;
$users->save();
...
...
}
Model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Notifications\ResetPasswordNotification;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Activitylog\Traits\LogsActivity;
class User extends Authenticatable
{
use Notifiable, LogsActivity;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'role_id', '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',
];
public function role()
{
return $this->belongsTo(Models\Role::class);
}
}
Seems like the error is with the logName and without looking at more code and data it is difficult to pinpoint exactly what is wrong.
Following could work
/**
* Get the log name to use for the model.
*
* #param string $eventName
* #return string
*/
public function getLogNameToUse(string $eventName = ''): string
{
return Str::kebab(Str::plural(class_basename($this)));
}
This is just overriding the piece of code causing issue. Give it a try.

Laravel 5.8 cannot generate api_token when new user register

I am playing around with Laravel Authentication.
On a freshly created Laravel app with Composer, I followed literally the instructions until this point (included)
https://laravel.com/docs/5.8/api-authentication#generating-tokens
When I register a new user, however, the api_token field is NULL.
What else do I need to do in order to start generating the api token when a user registers??
Create method in RegisterController:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
}
Migration (I called it Token) updating the users table:
class Token extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}
App\User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use 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',
];
}
In your user model add 'api_token' to your fillables
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'api_token'
];
After creating migration , run the migrate Artisan command:
php artisan migrate
If you are using the Homestead virtual machine, you should run this command from within your virtual machine:
php artisan migrate --force

Laravel getting information from other table

I have the following tables user table, post table and profile table. the post belongs to a user and the profile belongs to a user. I also have a forum were people can post I want the users username to show instead of their name. But The username is in the profiles table and I don't know how to get it.
here is my code
class Post extends Model
{
//
public function users(){
return $this->belongsToMany('App\User','posted_by');
}
class Profile extends Model
{
//
public function users(){
return $this->belongsTo('App\User','whos_profile');
}
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname','lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile(){
return $this->hasOne('App\Profile');
}
public function post(){
return $this->hasMany('App\Post');
}
}`enter code here`
You can get it as follows
$user = User::find($id);
if($user->profile){
echo $user->profile->username;
}
You should try this:
$rsltUsers = User::with(['profile','post'])->where('id',$id)->get();
foreach($rsltUsers as $rsltUsers){
dd($user->profile->username);
}

Laravel 5.2 - Registration

I'm building a simple user registration on Laravel 5.2 and it's really driving me crazy.
I started from the default Laravel built-in registration system and added some extra fields.
My case involves the following files:
routes.php
// Registration routes...
Route::get('auth/register', function(){
$organisations = Organization::all();
return view('auth.register', ['organizations' => $organisations]);
});
Route::post('auth/register', 'Auth\AuthController#postRegister');
User.php
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['organization_id', 'team_id', 'lastname', 'firstname', 'login', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Get the user's organisation.
*/
public function organization(){
return $this->belongsTo('App\Organization');
}
/**
* Get the user's team.
*/
public function team(){
return $this->belongsTo('App\Team');
}
}
Organization.php
class Organization extends Model
{
protected $table = 'organizations';
public $timestamps = false;
protected $fillable = ['name'];
/**
* Get the authors for the organization.
*/
public function users()
{
return $this->hasMany('App\Users');
}
/**
* Get the teams for the organization.
*/
public function teams()
{
return $this->hasMany('App\Teams');
}
}
Team.php
class Team extends Model
{
protected $table = 'teams';
public $timestamps = false;
/**
* Get the team's organisation
*/
public function organisation()
{
return $this->belongsTo('App\Organisation');
}
/**
* Get the authors for the team.
*/
public function users()
{
return $this->hasMany('App\Users');
}
}
AuthController.php
/
/.......
/......
/
/**
* 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, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'login' => 'required|max:255',
'organization' => 'required|max:255',
'team' => 'required|max:255',
'password' => 'required|confirmed|min:4',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'login' => $data['login'],
'organization_id' => $data['organization'],
'team_id' => $data['team'],
'password' => bcrypt($data['password']),
]);
}
I won't post my view code, my inputs are correct.
My problem is that I can store only ONE new user.
What's happening is:
my users table is empty
I fill up my form and then submit it to create my first user
it works (yay), I am correctly redirected to my home page
I want to create a second user
The new user isn't stored in my table
I am redirected to the home page however
If I delete my user entry in my table (so it means I empty my table), then I can create a new user again. But I can ALWAYS have one and only one entry. I can't add more.
Just out of curiosity I tried this in my routes file:
Route::get('/lol', function () {
return User::create([
'firstname' => 'what',
'lastname' => 'the',
'login' => 'f***',
'organization_id' => 1,
'team_id' => 4,
'password' => 'blabla',
]);
});
and of course it works like a charm each time I am calling the route /lol
So what the hell is going on in this AuthController? Am I out of my mind?
Alright the problem is that after my registration Laravel automatically logs the user in -.- (which is quite nice actually but I didn't know it). So now my problem is solved.
I went back to Laravel 5.1 (I was under 5.2), the authenticate and register system is better handled, in my opinion.

Laravel Eloquent Create

Hello so I've started using Laravel and it is useful and easy. For now I have a CRUD in which is working. In my AccountController#store the code is:
public function store(Request $request)
{
$input = $request->all();
Accounts::create($un);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
This basically adds a new account in my table. My problem is, I have a password textbox and I can't hash it since this code automatically gets every input in the form. How can I get it one by one? Like username, email and password only so I can hash the password.
You could get the input one by one and then hash the password and save it to the database. But that would require extra code.
You could also add an extra function to your Account model that will take care of this automatically.
Take a look at the example I use to create my management users.
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Hash;
class Management extends Model implements AuthenticatableContract {
use Authenticatable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'Management';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* Automatic hash function for the password.
*
* #var array
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
}
Regarding your code, you could do this:
public function store(Request $request)
{
Accounts::create($request->all());
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
Make sure to modify the example model above to your own needs!
You can also do:
public function store(Request $request)
{
$input = $request->all();
Accounts::create([
'username' => $input['username'],
'password' => bcrypt($input['password']),
]);
Session::flash('flash_message', 'Account successfully added!');
return redirect()->route('accounts.index');
}
You call Input::all() to get all the attributes passed in, and Input:get('key') to get a specific key.
So you should call:
$account = new Accounts;
$account->username = Input::get('username');
$account->password = Hash::make(Input::get('password'));
//key with a default
$account->password = Input::get('age', 20);
//optional field
if (Input::has('optional')) {
$account->optional = Input::get('optional');
}
//any other fields that account needs
$account->save()

Resources