Make hash password laravel 5.1 - laravel

I have problem to my apps this input password hash.
$simpan['password']=Request::input('password');
how make hash in my code?

You have two options
Call make method on Hash facade
Hash::make('string_here')
Or use global helper function bcrypt('string_here')
Example:
//Hash facade example
$simpan['password']= Hash::make(Request::input('password'));
//bcrypt global helper function
$simpan['password']= bcrypt(Request::input('password'));
Resource:
https://laravel.com/docs/5.1/hashing

In Laravel we can handle it a very intelligent and efficient way by using Mutators in Model Class.
use Illuminate\Support\Facades\Hash;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
// Password hassing by default to all new users,
public function setPasswordAttribute($pass)
{
// here you can make any opration as you like
$this->attributes['password'] = Hash::make($pass);
}
}
now you don't have to do manually password hashing every time
just store user in table by create or any other method
$created_user = User::create(request()->all());

Related

What effect does $hidden have exactly in eloquent model?

I'm currently fiddling around with Lumen and Im using eloquent for my DB interaction.
I've read through the docs of Eloquent and there was this explanation about hidden attributes:
Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden property to your model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = ['password'];
}
Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON representation. All other attributes will be hidden when the model is converted to an array or JSON:
I don't understand what implications this has. If I have a query where a password is being inserted, should I hide it? Or will this cause the password not to appear at all inside my model instance?
For example, I have the following User Model:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
//protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'role'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password'];
public $timestamps = false;
}
I'm now running a controller which shall insert name, email, password and role of a new user into users table.
Here you can see the table:
https://imgur.com/8r2JjPh
Now, when accessing my model to insert a new row like this:
User::create($requestData);
something goes wrong...
The password doesnt get inserted.
I debugged the input, the data is there, the JSON String of the input right before the insertion takes place looks like this:
{"name":"tester1","email":"test.tester1#tested.de","password":"3627909a29c31381a071ec27f7c9ca97726182aed29a7ddd2e54353322cfb30abb9e3a6df2ac2c20fe23436311d678564d0c8d305930575f60e2d3d048184d79","role":"Benutzer"}
the password was hashed using php function hash("sha512", $password);. Its based on "12345", just for testing :D :P
The hashed password has, as expected, the required length of 128 characters.
Any idea if this behavior is caused by the password attribute being defined as hidden in the model?
EDIT:
This is how I hash my password:
$requestData["password"] = hash("sha512", $requestData["password"]);
The password won't get inserted as you don't have password in your $fillable array.
The $fillable array is to protect against mass assignment. If you are "filling" the models attributes from an array you will need to add the attribute name to this array.
That being said I would actually recommend you don't add password to the $fillable array and instead explicitly set the password on the model:
$user = new User($requestData);
$user->password = $requestData["password"];
$user->save();
As mentioned in the comments, the $hidden attribute is purely for when the model is cast to an array or converted to JSON so it shouldn't have an affect on inserts (or anything else).
protected $hidden is an array and is a Model class parameter, that what it does is hide that columns (in the array) from the database in the queries results. In your example, $hidden = ['password'] make invisible 'password' column in user results.
https://laravel.com/api/6.x/Illuminate/Database/Eloquent/Model.html 'protected array $hidden The attributes that should be hidden for serialization.'

Laravel Auth manually login by id

I am new to laravel and I am working with a functionality where we insert data in user table with
DB::insert();
After that i get last id with
$user_id = DB::getPdo()->lastInsertId();
Now I want user to login after register and I am trying to
Auth::loginUsingId($user_id);
But its returning me false. I also tried
$user = User::find($user_id);
Auth::login($user);
Its also return null $user.
Please help...
This worked for me
Auth::loginUsingId(1);
Login User:
Auth::login($user);
check current user is login or not:
Auth::check();
Auth:login returns void so you can try something like this to check if user is logged in or not:
Auth::login($user);
return [
'status' => Auth:check()
];
check() determine if the current user is authenticated or not.
So, can you show your user Model?
In the Laravel Docs (https://laravel.com/docs/5.7/authentication) you can see, that your model must be an implementation of the Illuminate\Contracts\Auth\Authenticatable contract.
The basic User model looks like:
<?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',
];
}
and thats working lice expected.

Not enough rights to add an object in Algolia Laravel

I have a problem with using Algolia. Working with database but i can't save it in to API Algolia.com. I tried to search through google but i didn't get any results for this problem.
My controller:
public function store(Request $request)
{
$role = new Role;
$role->name = $request->name;
$role->save();
}
My model:
<?php
namespace App;
use Laravel\Scout\Searchable;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
use Searchable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name'];
/**
* Get the index name for the model.
*
* #return string
*/
public function searchableAs()
{
return 'roles_index';
}
}
In you env file, make sure you are setting the admin key as the ALGOLIA_SECRET.
By default, Algolia gives you different key:
Search key, which can only perform search (read) operations.
Write key, which can index (write) data.
Admin key, which can do everything. This is the recommended one for Laravel Scout.
Please note that only the search key can be passed to your frontend, if you use Vue InstantSearch for instance.
Please let me know if that solved your issue.

Laravel Model accessing a value of an instance of its self

I've got a model and the model its self could be linked to multiple other databases but only one at a time.
Instead of having a eloquent method for all the possible databases; it could have one that will use a variable from the self instance to choose the database and return just that.
It will save alot of work, as returning each one and testing to see if there are any results is cumbersome.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Feature extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'companies';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'db_name',
'enabled',
];
/**
* Uses the its own database name to determine which input to return.
*/
public function inputs() {
// if this->hidden->db_name == 'input type 1'
// return $this->HasMany(InputType1::class);
.... and so on
} // end function inputs
}
This is definitely a strange behaviour but I think you can achieve what you are looking for like so :
//in your model
public function inputs()
{
switch ($this->attributes['db_name']) {
case : 'input type 1':
return $this->hasMany(InputType1::class);
case : //some other database name
return //another relation
}
}
Expanding on shempognon answer, what I actually got to work was
switch($this->db_name) {
case 'Input_Timesheet':
return $this->hasMany(Input_type1::class);
}

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