I am getting Error "MassAssignmentException in Model.php line 448: nom" When I am using create method, here is my code below:
class User extends Model
{
protected $table = 'users';
protected $fillable = ['nom','prenom','username','password','email','phone'];
}
AuthetificationController.php (Controller)
$parameters = $request->all();
$user = User::create($parameters);
I also did this:
$user = User::create([
'nom' => $request->input('nom'),
'prenom' => $request->input('prenom'),
'username'=> $request->input('username'),
'password'=> $request->input('password'),
'email' => $request->input('email'),
'phone' => $request->input('phone'),
]);
Still the same error
and when I do:
var_dump($parameters);
I get the following results
try using in your controller
User::create(Request::all());
Related
Modify my registration blade. I added 2 additional functions that trigger the registration of the user. The data I needed are being saved to the appropriate tables but I am having this error,
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must
implement interface Illuminate\Contracts\Auth\Authenticatable, boolean
given, called in
E:\wamp64\www\aftscredit-appzcoder\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php
on line 35
Here's my Registration controller
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Referral;
use App\CollectorMember;
use App\HasRoles;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
public function index(Request $request)
{
$referral = '';
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if (is_null($keyword))
return view ( 'Auth.register');
elseif ($referral)
return view ( 'Auth.register', compact('referral', $referral))
->withDetails ( $referral )
->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not EXISTING or not AVAILABLE.' );
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user_id = $user->id;
Referral::find($data['referral_id'])->update ([
'status' => 1,
'date_used' => $data['referral_date_used']
]);
return CollectorMember::create ([
'collector_id' => $data['referral_generate_by'],
'borrower_id' => $user_id,
'referral_id' => $data['referral_id'],
]);
}
}
What's causing this? thanks in advance!
Try opening the RegistersUsers trait and look at line 35. A user is not being created.
The original Laravel controller code to create a user is as follows:
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Note how the DocBlock indicates an instance of User must be returned. This is key because the the actual code that completes the registration, within the trait, assumes a a valid User model instance.
It's sometimes helpful to step through the code and understand what Laravel is doing for you, behind the scenes.
I am trying to make the 'name' and 'email' properties guarded in my user model, because I don't want my users to be able to change them after registration.
My user model looks like this:
protected $fillable = [
'province',
'city',
'street',
'postal',
'cellphone',
'facebook',
'instagram',
];
protected $guarded = [
'name',
'email',
'password',
'account_type',
'verified_type',
];
Upon registration, Laravel by default mass assigns these values like so:
//Create the user
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'province' => $data['province'],
'city' => $data['city'],
'street' => $data['street'],
'postal' => $data['postal'],
'cellphone' => $data['cellphone'],
'trial_ends_at' => \Carbon\Carbon::now()->addMonths(3),
'account_type' => $accountType,
]);
But this throws an error for me because 'name' doesn't have a default value and isn't nullable. I understand why I'm getting the error and how to fix it, but I would like to know how I should go about assigning the name and email if they don't have default/nullable properties. For example, something like:
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->save();
$user->update([
//the rest of the mass assignable values
]);
Or is there an easier way?
You can accomplish by adding this to your model.
/*
Attribute which are protected from updating.
*/
protected $protected = [
'name', 'email'
];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
if($model->id){
foreach($model->protected as $attribute){
$model->$attribute = $model->getOriginal($attribute);
}
}
});
}
Hope the code is self-expresive.
you can use a mutator and remove name from guarded attributes. read the docs here
public function setNameAttribute($newName)
{
if(isset($this->name) && $this->name !== null){
throw new \Exception;
//or do nothing
} else {
$this->attributes['name'] = $newName;
}
}
and do the same for email too
I have a unit acceptance test where I am mocking the creation of a user.
class UserAcceptanceApiTest extends TestCase
{
use WithoutMiddleware;
public function setUp()
{
parent::setUp();
$this->User = factory(App\Models\User::class)->make([
'id' => '999',
'name' => 'Name',
'email' => 'test#example.com',
'password' => bcrypt('password'),
]);
$this->User = factory(App\Models\User::class)->make([
'id' => '999',
'name' => 'Name',
'email' => 'test#example.com',
'password' => bcrypt('password'),
]);
$user = factory(App\Models\User::class)->make();
$this->actor = $this->actingAs($user);
}
public function testStore()
{
$response = $this->actor->call('POST', 'api/users', $this->User->toArray());
$this->assertEquals(200, $response->getStatusCode());
$this->seeJson(['id' => 999]);
}
}
I get the following exception "Field 'password' doesn't have a default value.
This is because in my User model I have the following:
protected $hidden = ['password', 'remember_token'];
So it automatically removes the password field from the JSON.
Is there a way I can override this only for this test? As I want to keep the password as a hidden attribute.
public function testStore()
{
$this->User->makeVisible(['password']);
$response = $this->actor->call('POST', 'api/users', $this->User->toArray());
$this->assertEquals(200, $response->getStatusCode());
$this->seeJson(['id' => 999]);
}
i want to insert into userbio after register here is my register RegisterController
protected function create(array $data)
{
$databio = new ModelBio();
$maxbio = $databio->getMaxbioId();
// die( $maxbio );
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'biodataId' => $maxbio,
'password' => bcrypt($data['password']),
]);
return Biodata::create([
'biodataId' => $maxbio,
'fullname' => $data['fullname']
]);
}
It creates new record for Users. But, there is a problem i cant insert into usersbio, I can't find any error message there . Btw RegisterController is from laravel auth. here is my Biodata
class Biodata extends Model
{
//
protected $primaryKey = 'biodataId';
protected $table = "usersbio";
public $incrementing = false;
protected $fillable = [
'biodataId','address','fullname','remarks'
];
static function getMaxbioId(){
$max = Biodata::max('biodataId');
if($max == ""){
return "BIO-0001";
}else{
$number = substr($max, 4);
return 'BIO-' . sprintf('%04d', intval($number) + 1);
}
}
}
how can i fix it ? thanks in advance
Do not write return while creating User. It actually returns from there and no further code will be executed of the function.
protected function create(array $data)
{
$databio = new ModelBio();
$maxbio = $databio->getMaxbioId();
// die( $maxbio );
User::create([ // Removed `return` from here
'username' => $data['username'],
'email' => $data['email'],
'biodataId' => $maxbio,
'password' => bcrypt($data['password']),
]);
return Biodata::create([
'biodataId' => $maxbio,
'fullname' => $data['fullname']
]);
}
I have a static method in User model.
namespace Tol;
...
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
...
public static function signup(array $data)
{
$user = new User([
'email' => $data['email'],
'password' => Hash::make($data['password']),
'username' => $data['username'],
'type' => $data['type'],
]);
$user->save();
if ($user && $user->id) {
$profile = new UserProfile([
'first_name' => trim($data['first_name']),
'last_name' => trim($data['last_name']),
'gender' => $data['gender'],
]);
$user->profile()->save($profile);
EmailVerification::sendTo($user, 'signup');
}
return $user;
}
...
}
And I'm trying to call call this method simply from my controllers.
like this
$user = User::signup($input);
And it throws error like this:
I don't know why it is referring it as a method on the Builder class. The code is very simple and everything was working when it was Laravel 4.
Please help.
thanks
your code should have no problem, im afraid the problem is in your auth.php file, please ensure
'model' => 'App\User',
is set it to your model file in your case
'model' => 'Tol\User',
and to ensure your calling the right file you might want to give this a try
\Tol\User::signup($array);