How add to database hash password in Laravel? - php

I make validation form registration using Laravel 9 and now I want to add correct data to database. This is my code in controller
public function store(RegistrationRequest $request)
{
return redirect(
route(
'index.store',
['registration' => User::create($request->validated())]
)
);
}
But my problem is that I want to insert to database hash password. In model I have function which hash password but I don't know how to insert to database.
class User extends Model
{
use HasFactory;
protected $fillable = [
'login', 'password', 'email'
];
public function opinions()
{
return $this->hasMany(Opinion::class);
}
public function setPassword($value)
{
$this->attributes['password'] = bcrypt($value);
}
}
I will gratefull if some help me how resolve this problem.

Since you are using laravel 9 you have two option to store hashed password .Add this mutator in model
protected function password(): Attribute
{
return Attribute::make(
set: fn($value) => bcrypt($value),
);
}
Ref :defining-a-mutator
or older way is
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
Ref: Defining A Mutator

Related

Laravel Eloquent method updateOrCreate exceeds execution time when updating

So the problem is that when I try to update my entity it finds it updates it but gets stuck in a loop probably and doesn't exit. When I check the database, even before the 60 seconds of execution time that I have expires, the values that I have changed are updated.
If i constantly refresh (and here is where it gets crazy) the updated at values for other lectures starts to change every second while it executes this loop.
When creating (not finding the id on the condition It creates it without a problem)
I have Lectures which looks like this:
class Lecture extends Model
{
use Searchable;
use SoftDeletes;
protected $primaryKey = 'id';
protected $touches = ['themes', 'educationTypes', 'subjects'];
protected $fillable= [
'name', 'description', 'user_id', 'field_id', 'approved'
];
public static function boot()
{
parent::boot();
static::saved(function ($model) {
$model->themes->filter(function ($item) {
return $item->shouldBeSearchable();
})->searchable();
});
}
public function user(){
return $this->belongsTo('App\User')->with('companies');
}
public function geographies(){
return $this->belongsToMany('App\Geography');
}
public function educationTypes(){
return $this->belongsToMany('App\EducationType', 'lecture_education_type')->withTimestamps();;
}
public function themes(){
return $this->belongsToMany('App\Theme','lecture_theme', 'lecture_id', 'theme_id')->withTimestamps();;
}
public function subjects(){
return $this->belongsToMany('App\Subject', 'lecture_subject')->withTimestamps();;
}
public function cases(){
return $this->belongsToMany(
'App\CompanyCase' ,
'case_company_lecture',
'lecture_id',
'case_id',
'id',
'id')->withTimestamps();
}
public function companies(){
return $this->belongsToMany(
'App\Company' ,
'case_company_lecture',
'lecture_id',
'company_id',
'id',
'id'
);
}
public function field(){
return $this->belongsTo('App\Field');
}
public function toSearchableArray()
{
$this->themes;
$this->user;
$this->educationTypes;
$this->subjects;
$this->geography;
return $this->toArray();
}
}
This is the controller:
public function storeLecture(Request $request) {
$lecture_id = $request->get('lecture_id');
// It gets stuck between the comments
$lecture = Lecture::updateOrCreate(['id' => $lecture_id],
[
'name'=> request('name'),
'description'=> request('description'),
'user_id'=> request('user_id')]
);
// and doesn't update the themes, edu types subjects and etc.
$company_id = $request->get('company_id');
$company = Company::find(request('company_id'));
$lecture->companies()->sync([$company->id]);
$eduTypes= $request->get('education_types');
$themes= $request->get('themes');
$subjects = $request->get('subjects');
$geographies = $request->get('geographies');
$lecture->themes()->sync($themes);
$lecture->educationTypes()->sync($eduTypes);
$lecture->subjects()->sync($subjects);
$lecture->geographies()->sync($geographies);
$n1 = new Notification();
$n1->send(request('user_id'), 1, 'new_lecture', $lecture->id);
$user = User::where('id', $request->id)->first();
$user_with_companies = $user->load('companies');
$slug = $user_with_companies->companies->first()->slug;
return response(['success' => true]);
}
This is the frontend method sending the request (in between I have a middleware checking if the user is admin (possible to create a lecture) based on the this.selectedExpert.id, which doesn't interfere).
createUpdateLecture() {
const url = `${window.location.origin}/lecture/create/${
this.selectedExpert.id
}`;
this.$http
.post(url, {
education_types: this.allEducationTypes
.filter(el => el.checked)
.map(a => a.id),
themes: this.allThemes.filter(el => el.checked).map(a => a.id),
geographies: this.allGeographies
.filter(el => el.checked)
.map(a => a.id),
subjects: this.allSubjects.filter(el => el.checked).map(a => a.id),
name: this.lecture.name,
description: this.lecture.description,
user_id: this.selectedExpert.id,
company_id: this.company.id,
lecture_id: this.lecture.id
})
.then(res => {
console.log(res);
this.$parent.showLectureCreateModal = false;
// window.location.reload();
});
}
As I can see what is happening I probably use the method really badly but I just want to understand it better for further usage.
After a few days of researching and testing it turns out that it is not the updateOrCreate method causing the problem because I tried with two different functions for creating and updating and the update function was still having the same problem.
The problem is created from Algolia which is used for searching based on different fields in the platform. Fx. in Themes
class Theme extends Model
{
use SoftDeletes;
use Searchable;
protected $touches = ['lectures'];
public function lectures(){
return $this->belongsToMany('App\Lecture');
}
public function toSearchableArray()
{
$this->lectures;
return $this->toArray();
}
}
Removing the searchable from the models did the trick!

Laravel 5.2 - Using SetIdAttribute() Mutator To Set Other Value

I am currently creating a blog where each Post row in my database will have a unique hash attribute that is based of the post's id (incrementing, always unique).
This my Post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Hashids;
class Post extends Model
{
public function setTitleAttribute($value)
{
$this->attributes['title'] = $value;
if (! $this->exists) {
$this->attributes['slug'] = str_slug($value);
}
}
public function setIdAttribute($value) {
$this->attributes['id'] = $value;
$this->attributes['hash'] = Hashids::encode($value);
}
}
When I run this factory
$factory->define(App\Post::class, function (Faker\Generator $faker) {
return [
'title' => $faker->sentence(mt_rand(3, 10)),
'content' => join("\n\n", $faker->paragraphs(mt_rand(3, 6))),
'author' => $faker->name,
'category' => rand(1, 20),
];
});
The setIdAttribute($value) function is getting called, but my hash attribute is not being set. I am not sure if it is getting overwritten or what.
If I move the line
$this->attributes['hash'] = Hashids::encode($value);
to the function
public function setTitleAttribute($value)
and encode the title attribute it works fine, but I want to encode the 'id' attribute. Any idea how I would do this?
You can add the following to your model:
/**
* Events
*/
public static function boot()
{
parent::boot();
static::created(function($model)
{
$model->hash = Hashids::encode($model->id);
$model->slug = str_slug($model->title);
}
}
It's likely setIdAttribute($value) isn't being called until after the insert runs because it doesn't know the ID until then.
The real issue is you can't set a hash of the id in the same query because the id isn't going to be known (assuming it's auto_incrementing) until after the insert.
Because of this, the best you can probably do here is fire some code on the model's saved event.
In that model, you can probably do something like...
public static function boot()
{
parent::boot();
static::flushEventListeners(); // Without this I think we have an infinite loop
static::saved(function($post) {
$post->hash = Hashids:encode($post->id);
$post->save();
});
}

Laravel 4.2: After checking “remember me” checkbox user's login doesn't get remembered in database, only in cookie, thus remember me not working

I am using laravel 4.2
I have a login form where I am trying to implement the remember me functionality. I have used Auth::attempt() to implement the above. Here's my code.
public function logintest()
{
// set the remember me cookie if the user check the box
$remember = (Input::has('remember')) ? true : false;
// attempt to do the login
$auth=Auth::attempt(
[
'username' => Input::get('username'),
'password' => put::get('password')
], $remember);
if ($auth)
{
// The user is active, not suspended, and exists.
$id = Auth::user()->id;
return Redirect::to("example/$id");
}
else
{
return Redirect::to('example')
->with('flash_error', 'Incorrect Username or Password!');
}
}
I have also created a column "remember_token"(a nullable string with 255 chars) in registration table. And also added below 3 methods in the model MyModel.php
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
Yes it does sets the cookie named remember_xxxxxx, but it doesn't add anything to the remember_token column. It's not working. Is there something i missed ?
Please notice that remember_token only makes sure that the user won't be logged out after 2 hours (or any other amount of time that has been given in the config file).
You need to have a user model before it will work.
The fillable variable tells the model which fields may be mass assigned (changed).
class Users extends Eloquent {
protected $fillable = array('username', 'password', 'remember_token');
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
}
This name of the model needs to have the exact same name as the table in the database or you can specify the table name in a variable called table. I think you want to store the remember_token in the same table as where the users are.
In the controller you should add
use Location\To\Model;
So assuming you created a Model directory inside the app directory
use App\Model\Users;
To authenticate users by their remember token you should use
if (Auth::viaRemember())
{
//
}

laravel Auth::check() fails

Auth::check() fails after successful Auth:attempt(). I am just following laracast.com tutorials to make a simple authentication. This specific tutorial https://laracasts.com/series/laravel-from-scratch/episodes/15 . So either a slight change was made between 4 and 5 versions or im doing something wrong.
This is a function that does auth and the second one does the checking. Both of them are in the same class.
public function store()
{
$credentials = Input::only('user_displayname');
$credentials['password'] = Input::get('user_password');
if (Auth::attempt($credentials))
{
return Auth::user();
}
return 'not logged';
}
public function status()
{
return dd(Auth::check());
}
This is User model:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'user';
protected $hidden = array('user_password', 'remember_token');
protected $fillable = ['user_displayname', 'user_fname', 'user_lname', 'user_email', 'user_password'];
public $errors;
public static $rules = array(
'user_displayname' => 'required|unique:user,user_displayName',
'user_fname' => 'required',
'user_lname' => 'required',
'user_email' => 'required|unique:user,user_email',
'user_password' => 'required'
);
public function isValid($data)
{
$validation = Validator::make($data, static::$rules);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
}
public function getAuthPassword()
{
return $this->user_password;
}
}
Second question. Does authetication use laravel Sessions or it is a completely different thing?
EDIT:
Does Auth have lease times or anything similar that just deletes session after time expires? Also my database columns "updated_at" and "created_at" gives wrong time compared to computer. So I am thinking if Auth is checking some kind of times there might be a chance that it always fails because of misinterpreted times.
P.S already looked over other solutions in stackoverflow.
Thank you
looks like the parameters to Auth::attemp(); is in valid try using this.
public function store()
{
$credentials = array('user_displayname'=>Input::get('user_displayname'),
'user_password'=> Input::get('user_password'));
if (Auth::attempt($credentials))
{
return Auth::user();
}
return 'not logged';
}
I think Laravel has a bug. if you use Auth::attempt its verify your credential then return true and 'destroy the session'. So we redirect our url and use Auth::check() so its return false. because session is destroy and you lost you data to check.
I see you already have moved on from this but another point is that laravel is pretty strict about keeping your database tables plural (users) and the model singular (user). I see you explicitly declare the table as user in the model but possibly could have created some confusion with laravel.

Auth::attempt doesn't work [Laravel]

I've looked through all other questions on this...
So I set up a userSeeder which autopopulates my User table:
public function run()
{
$users = [
[
"email" => "email#myemail.co.uk",
"fname" => "Nicola",
"sname" => "Elvin",
"password"=>Hash::make("password")
]
];
foreach ($users as $user)
{
User::create($user);
}
}
My table shows this is stored, and password has been hashed.
In my login function:
$credentials = [
"email" => Input::get("email"),
"password" => Input::get("password")
];
if (Auth::attempt($credentials)) {
return Redirect::route("user/profile");
}else{
echo 'wrong';
}
I did a print_r of $credentials and it correctly displays my email address and password.
Yet it always shows up as wrong. It doesn't ever validate.
USER MODEL
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'user';
protected $hidden = array('password');
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
I figured it out. Embarrassingly, I had white space at the end of my email address...so it wasn't actually correct as I hadn't trimmed it...
Although the way I figured this out was by seeing the sql query that auth:attempt was running by installing a Laravel 4 profiler

Categories