MassAssignmentException in Model.php line 445: username - php

I tried to modify the 'RegisterController' to fit my needs.
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\profile;
use App\roles_id;
use App\permissions_id;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/app/system/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'string|required|max:255|unique:profiles',
'last_name' => 'string|required|max:255',
'email' => 'required|email|max:255|unique:profiles',
'username' => 'required|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
//create user
$user = User::create([
'username' => $data['username'],
'password' => bcrypt($data['password']),
'real_password' => $data['password'],
]);
//create profile
profile::create([
'username' => $data['username'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
]);
//create roles
roles_id::create([
'role_id' => 1,
'username' => $data['username'],
]);
//create role
roles_id::create([
'role_id' => 1,
'username' => $data['username'],
]);
//create permission
permisssions_id::create([
'perm_id' => 0,
'username' => $data['username'],
]);
return $user;
}
}
but it gives me this error upon sending a registration request from the registration form in the client.
MassAssignmentException in Model.php line 445: username
any ideas, help please?

As you mentioned that there is no email column in users table, update your validation method as below:
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'string|required|max:255',
'last_name' => 'string|required|max:255',
'email' => 'required|email|max:255|unique:profile',
'username' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
That means 'email' => 'required|email|max:255|unique:profile', instead of 'email' => 'required|email|max:255|unique:users'.
And to get rid of your MassAssignmentException in your profile model class use $fillable property.
protected $fillable = ['username', 'first_name', 'last_name', 'email'];

Related

Laravel sign in

I can sign up and details are then added to the database but I can't use info from the database to successfully login. It just brings back the same page with no error messages. This is the UserController code
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
class UserController extends Controller
public function getSignin()
{
return view('user.signin');
}
public function postSignin(Request $request)
{
$this->validate($request, [
'email' => 'email|required',
'password' => 'required|min:4'
]);
if (Auth::attempt(['email' => $request->input('email'), 'password' => $request->input('password')])) {
return redirect()->route('user.profile');
}
return redirect()->back();
}
```auth file
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
Probably because you're saving your password with bcrypt, but on Auth::attempt you pass it in a plain text. Try this:
Auth::attempt(['email' => $request->input('email'), 'password' => bcrypt($request->input('password'))])
Started the project again using Laravel's built in login and register system.

laravel : Return null token But used has added

I use postman to add user in my laravel project I get null token but the user has added
why?
{
"token": null }
how I can fix this error?
I use laravel 5.6
and
this my user model :
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
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','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
and this my register controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
and this is my controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Response;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;
use Validator;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
I alreday get a error and this my question question and I fiwx it
how I can fix this error?
I use laravel 5.6
I already had a similar problem before, but I realize my$user->password holds the encrypted password, not the pain text required for login(). Change your code to call
$token = JWTAuth::fromUser($user);
with $user holding the plain text password comming from $request
I solve my problem adding if condition on register function after create user
if ($this->loginAfterSignUp) {
$token = $this->login($request);
}
return $this->respondWithToken($token);

Laravel registercontroller, add another create

I am using laravel auth to handle my login/register/validation etc. Now i need to after creating the user at register also create another table containing the user->id.
Something like this is what i would like to achieve, obviously this doesnt work but you get what im after. Is this possible or is my only option to create a custom registercontroller for my needs?
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User && \App\Stats
*/
protected function create(array $data)
{
return [
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]),
Stats::create([
'user_id' => $user->id
])
];
}
This should work
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
Stats::create([
'user_id' => $user->id
]);
return $user;
}

Validating user input in Laravel using the Validator

I'm trying to use the RegisterController in Laravel, but I can't get the Validator to work. I don't understand what the problem is, because it should just take an array and validate it.
When I try to send a JSON with the right fields to the register route, I get this error:
BadMethodCallException: Method validate does not exist. in file /home/deb85528n3/vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 96
Below is my code:
protected function validator(array $data)
{
$validator = Validator::make($data,
[
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer',
'lat' => 'required',
'lon' => 'required',
]);
echo $validator->errors();
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()]);
}
if ($validator->passes())
{
$response = "validator passed";
return response()->json($response);
}
}
I also tried using the Validator in a different way:
public function validator(Request $request){
$validator = Validator::make($request->all(), [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
}
But then I get this error:
Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to App\Http\Controllers\Auth\RegisterController::validator() must be an instance of App\Http\Controllers\Auth\Request, array given, called in /home/deb85528n3/vendor/laravel/framework/src/Illuminate/Foundation/Auth/RegistersUsers.php on line 31 in file /home/deb85528n3/app/Http/Controllers/Auth/RegisterController.php on line 103
Edited to include the whole RegisterController:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
$validator = Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
echo $validator->errors();
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()]);
}
if ($validator->passes())
{
$response = "validator passed";
return response()->json($response);
}
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
//maybe check if facebook login here?
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'birth_year' => $data['birth_year'],
'lat' => $data['lat'],
'lon' => $data['lon'],
]);
}
}
change your function name
use Validator;
add this in your controller,
remove this
public function validator(Request $request){
Write your validation rules in model like below
public static function rules()
{
return [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
];
}
and call this rule in your controller
$validator = Validator::make($request->all(), "Your model Name"::rules());
if ($validator->fails()) {
//throw exception
}
The register method calls the validator method and passes through an array, it then expects that an instance of \Illuminate\Contracts\Validation\Validator to be returned.
Unless you're needed to override the default responses for registering a user, you should just be able to have:
public function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'birth_year' => 'required|integer|min:4',
'lat' => 'required|numeric',
'lon' => 'required|numeric',
]);
}

Laravel Registration ERROR With UNKnown Field

the script returns an error that i don't think i included in my code.
SQLSTATE[HY000]: General error: 1364 Field 'phone' doesn't have a default
value (SQL: insert into `users` (`name`, `email`, `location`, `password`,
`steps`, `incubation_days`, `updated_at`, `created_at`) values (ilamini
Ayebatonye Dagogo, dagogo#gmail.com, Uniben Road, Ugbowo, Benin City, Nigeria,
$2y$10$aoJRS61Bn/q1eNcUFALjne8erLXD11y1.OmHhurlQJDrex73DPWJW, settings, 8,
2017-03-01 14:11:54, 2017-03-01 14:11:54))
Can someone point me to where this phone field is coming from.
Below my Register Controller Class.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\paring_by_location;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'location' => 'required|min:5',
'name' => 'required|max:255',
'password' => 'required|min:6|confirmed',
'email' => 'required|email|max:255',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$phDay = rand(2,8);
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
'password' => bcrypt($data['password']),
'steps' => 'settings',
'incubation_days' => $phDay
]);
paring_by_location::create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
]);
event(new \App\Events\UserReferred(request()->cookie('ref'), $user));
return $user;
}
}
and Below is my HomeController that i think may be Interfering with the Register Controller.
public function AccountSettings(Request $request)
{
$id = Auth::user()->id;
$user = User::findOrFail($id);
$this->validate($request, [
'account_name' => 'required|string|min:5',
'account_number' => 'required|digits:10',
'bank_name' => 'required|string|min:3',
'phone' => 'required|digits:11'
]);
$input = $request->all();
$user->update(array('steps' => 'notification'));
$update = $user->fill($input)->save();
return redirect()->route('home');
}
also is my USER MODEL TAHT has the protected field
protected $fillable = [
'name', 'email', 'password', 'location','steps','incubation_days','phone','bank_name','account_name','account_number',
];
So I want to understand why it is returning an error when i did not include the phone in the register controller
You should set nullable() or default() value for the phone field. It should look like this in migration for users table:
$table->string('phone')->nullable();
Or make the phone field required:
protected function validator(array $data)
{
return Validator::make($data, [
'location' => 'required|min:5',
'name' => 'required|max:255',
'password' => 'required|min:6|confirmed',
'email' => 'required|email|max:255',
'phone' => 'required'
]);
}
And add it to create() method:
create([
'name' => $data['name'],
'email' => $data['email'],
'location' => $data['location'],
'phone' => $data['phone']
]);

Categories