Reputation: 453
I'm using Laravel with the following libraries:
On the User model I have the password attribute hidden, so when I do a GET It's working as expected, show all the attributes least password
Now when I do a POST with with a model created form Faker I can't send the attribute Password.
Faker Factory
<?php
$factory->define(App\User::class, function (Faker\Generator $faker) {
$role = App\Role::all()->random(1);
return [
'role_id' => $role->id,
'username' => $faker->userName,
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'email' => $faker->safeEmail,
'password' => str_random(10),
];
});
User Model
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $hidden = [ 'password' ];
/* rest of the code */
/* I have a validation rule for password to be required */
User Context Function
<?php
/**
* @When I try to save a valid user
*/
public function iTryToSaveAValidUser()
{
$modelFake = factory('App\User')->make();
$client = new GuzzleHttp\Client();
$data['data'] = $modelFake;
$res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);
}
The error I'm getting is the password required, there is a way to set hidden ONLY on GET?
I "Fixed" this issue with the following code but I don't like this way
<?php
/**
* @When I try to save a valid user
*/
public function iTryToSaveAValidUser()
{
$modelFake = factory('App\User')->make();
$client = new GuzzleHttp\Client();
$modelArray = $modelFake->toArray();
$modelArray['password'] = str_random(10);
$data['data'] = $modelArray;
$res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);
}
Thanks in advance!
Upvotes: 3
Views: 1119
Reputation: 880
I think that this is due to this line
$res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);
where you send attribute as json.
Read this properly,It can help.
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 definition to your model:
Note: When hiding relationships, use the relationship's method name, not its dynamic property name.
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:
protected $visible = ['password']
Temporarily Modifying Property Visibility
If you would like to make some typically hidden attributes visible on a given model instance, you may use the makeVisible method. The makeVisible method returns the model instance for convenient method chaining:
return $user->makeVisible('attribute')->toArray();
Upvotes: 4