What effect does $hidden have exactly in eloquent model? - laravel

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.'

Related

laravel access a eloquent row data by index

hello i have the laravel model:
class User extends Authenticatable
{
use SoftDeletes;
use Notifiable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The database primary key value.
*
* #var string
*/
protected $primaryKey = 'id';
/**
* Attributes that should be mass-assignable.
*
* #var array
*/
protected $fillable = [
'name',
'family',
];
}
in controller i get a user by id like :
$user=User::where('id','=' ,'10')->first () ;
in blade i display the family value :
{{$user->family}}
i am using :
{{$user[3] }}
to get the family value .
can we get the value by index like 2 for name ,
3 for family instead to do it like this $user->name ,or $user->family ?
thanks
Well, I hope you know what you are doing. As you want to access the User object by index.
Here is the snippet for controller:-
$user = User::where('id','=' ,'10')->first();
$user = array_values($user->toArray());
Now the $user has an array and you can access in the blade file by index.
Note that:- This will create an issue when you add more fields or remove some fields.

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.

Too many fillable fields in model Laravel?

I have around 200 fields in a table that are numbered:
field_1
field_2
etc
I tried to insert data in table:
Result::insert($data);
Where $data is multiple array:
$data = [] = array("field_1" => 3);
$data = [] = array("field_1" => 2);
Can I set * in option protected $fillable = ["*"]; to make all fields fillable?
If you need to set all columns as fillable, do this in the model:
protected $guarded = [];
If you would like to make all attributes mass assignable, you may define the $guarded property as an empty array
https://laravel.com/docs/5.3/eloquent#mass-assignment
In such scenario, you can try doing the reverse. For example: id, created_at and updated_at field as $guarded. Like:
protected $guarded = ['id', 'created_at', 'updated_at'];
Except these rest will be considered as fillable i.e. mass assignable.
You can find details in Official Laravel Doc
Guarding Attributes
While $fillable serves as a "white list" of attributes that should be
mass assignable, you may also choose to use $guarded. The $guarded
property should contain an array of attributes that you do not want to
be mass assignable. All other attributes not in the array will be mass
assignable. So, $guarded functions like a "black list". Of course,
you should use either $fillable or $guarded - not both.

whats the difference between fillable and guard in laravel?

I am newbie in Laravel and want to understand this with example.
what are main difference between fillable and guard in laravel?
How those are differentiated?
Please share one basic example.
Example 1
protected $fillable = ['name', 'email'];
It means we want to insert only name,and email colmn values
Example 2
protected $guarded = ['name', 'email'];
It means we want to ignore only name & email we don't want to insert values of name & email colmn
Example 3
protected $guarded = [];
We want to insert all columns values
First as a newbie refer the documentation on laravel site. I suppose you are asking about fillable vs guarded.
Fillable is ready for mass assignments i.e. you can use fill() with array of value sets instead of one-one assignments. Below name and email are fillable.
class User extends Eloquent{
public $timestamps = false;
protected $fillable = ['name', 'email'];
}
....
$user = User::create($request->all);
Guarded is just opposite of fillable.
keep in mind there is one more "hidden" which means its not available for json parsing. so if you use
return User::all();
the returned json will skip all fields mentioned in hidden. Also the hidden doesn't explicitly means guarded.
In Laravel, $fillable attribute is used to specify those fields which are to be mass assignable. $guarded attribute is used to specify those fields which are to be made non mass assignable.
$fillable serves as a "white list" of attributes that should be mass assignable and $guarded acts just the opposite of it as a "black list" of attributes that should not be mass assignable.
If we want to block all the fields from being mass-assigned, we can use:
protected $guarded = ['*'];
If we want to make all the fields mass assignable, we can use:
protected $guarded [];
If we want to make a particular field mass assignable, we can use:
protected $fillable = ['fieldName'];
Lastly, if we want to block a particular field from being mass assignable, we can use:
protected $guarded = ['fieldName'];

Make hash password laravel 5.1

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());

Resources