Laravel Eloquent Many to Many to One relationship - laravel

I'm creating a laravel application where the user logins in and can create clients and fill out an applicant form that is linked to the client.
I'm trying to make a relationship with many users that each have many clients, which have one applicant. But I get the following error:
Error
I'm confused with whats wrong and with naming the functions.
ClientContoller:
public function createApplicant(){
$data = request()->validate([
'name' => 'required',
'dob' => 'required',
'age' => 'required',
'gender' => 'required',
'ethnicity' => 'required',
'country' => 'required',
'interpreter' => '',
'language' => 'required',
'homeAddress' => 'required',
'job' => 'required',
'workAddress' => 'required',
'email' => 'required',
'phone' => 'required',
'contact' => 'required',
'extra' => 'required',
]);
auth()->user()->clients()->applicant()->create([
'name'=>$data['name'],
'dob'=>$data['dob'],
'age'=>$data['age'],
'gender'=>$data['gender'],
'ethnicity'=>$data['ethnicity'],
'country'=>$data['country'],
'interpreter'=>$data['interpreter'],
'language'=>$data['language'],
'homeAddress'=>$data['homeAddress'],
'job'=>$data['job'],
'workAddress'=>$data['workAddress'],
'email'=>$data['email'],
'phone'=>$data['phone'],
'contact'=>$data['contact'],
'extra'=>$data['extra'],
]);
dd($data);
}
User Model:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function clients(){
return $this->hasMany(Client::class);
}
}
Client Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email'
];
public function applicant(){
return $this->hasOne(Applicant::class);
}
}
Applicant Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Applicant extends Model
{
use HasFactory;
protected $fillable = [
'fullName',
'date_of_birth',
'age',
'gender',
'ethnicity',
'country',
'interpreter',
'language',
'homeAddress',
'job',
'workAddress',
'email',
'phone',
'contact',
'extra'
];
}
applicants table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Applicants extends Migration
{
public function up()
{
Schema::create('applicants', function (Blueprint $table) {
$table->id();
$table->string('fullName');
$table->date('date_of_birth');
$table->string('age');
$table->string('gender');
$table->string('ethnicity');
$table->string('country');
$table->boolean('interpreter');
$table->string('language');
$table->string('homeAddress');
$table->string('job');
$table->string('workAddress');
$table->string('email')->unique();
$table->string('phone');
$table->string('contact');
$table->string('extra');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('applicants');
}
}
clients table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Clients extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('clients');
}
}
Any help would be greatly appreciated.
Thank you!

As Maksim mentioned, Laravel is confused which client it should create an applicant for. So, you need to specify it somehow. My suggestion is:
public function createApplicant(Request $request){
$data = request()->validate([
'name' => 'required',
'dob' => 'required',
'age' => 'required',
'gender' => 'required',
'ethnicity' => 'required',
'country' => 'required',
'interpreter' => '',
'language' => 'required',
'homeAddress' => 'required',
'job' => 'required',
'workAddress' => 'required',
'email' => 'required',
'phone' => 'required',
'contact' => 'required',
'extra' => 'required',
]);
$client = Client::find($request->id);
$client->applicant()->create([
'name'=>$data['name'],
'dob'=>$data['dob'],
'age'=>$data['age'],
'gender'=>$data['gender'],
'ethnicity'=>$data['ethnicity'],
'country'=>$data['country'],
'interpreter'=>$data['interpreter'],
'language'=>$data['language'],
'homeAddress'=>$data['homeAddress'],
'job'=>$data['job'],
'workAddress'=>$data['workAddress'],
'email'=>$data['email'],
'phone'=>$data['phone'],
'contact'=>$data['contact'],
'extra'=>$data['extra'],
]);
dd($data);
}
So, you need to form a request before sending data to controller, with an id field, where you specify, which exact client you want to create applicant for.
Alternatively, if you call it like
Route::post('/add_applicant/{id}', 'ClientController#createApplicant');
you could replace Request $request and $request->id with just $id. The main idea is just to pass an id parameter somehow.
However, you still can find a more elegant approach.

Related

Jetstream unable to delete account after modifying the authentication logic. (Laravel 9,Jetstream, Inertia, VueJs3)

Recently I have decided to add another field when in log in page( Username ), it is unique.
When log in you can use either username or email to do so.
After the modification, "Login", "Registeration", "Changing Password", "Password Reset", "Email Verification" worked fine.
"Two Factor Authentication", "Browser Sessions", "Delete Account" does not working just wondering what has gone wrong
When i try to delete account or log out from all browser session, this pops out
for more detailed error https://flareapp.io/share/17DK4R9P#F73
config/fortify
'username' => 'auth',
'email' => 'email',
Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use JoelButcher\Socialstream\HasConnectedAccounts;
use JoelButcher\Socialstream\SetsProfilePhotoFromUrl;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Jetstream\HasTeams;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Models\Post;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto {
getProfilePhotoUrlAttribute as getPhotoUrl;
}
use HasTeams;
use HasConnectedAccounts;
use Notifiable;
use SetsProfilePhotoFromUrl;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'profile_photo_url',
];
/**
* Get the URL to the user's profile photo.
*
* #return string
*/
public function getProfilePhotoUrlAttribute()
{
if (filter_var($this->profile_photo_path, FILTER_VALIDATE_URL)) {
return $this->profile_photo_path;
}
}
Users database
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->nullable();
$table->rememberToken();
$table->foreignId('current_team_id')->nullable();
$table->foreignId('current_connected_account_id')->nullable();
$table->foreignId('current_connected_post_id')->nullable();
$table->text('profile_photo_path')->nullable();
$table->timestamps();
});
}
}
}
action/fortify/UpdatesUserProfileInformation.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'alpha_dash:users', Rule::unique('users')->ignore($user->id)],
'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)],
'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:10024'],
])->validateWithBag('updateProfileInformation');
action/fortify/CreatesNewUsers.php
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:255', 'unique:users','alpha_dash:users'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'username' => $input['username'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$this->createTeam($user);
});
});
provides/fortifyserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
provides/jetstreamserviceprovider.php
Fortify::authenticateUsing(function (LoginRequest $request) {
$user = User::where('email', $request->auth)
->orWhere('username', $request->auth)->first();
if (
$user &&
Hash::check($request->password, $user->password)
) {
return $user;
}
});
I have found the solution for all this,
Inside vendor/laravel/fortify/src/Actions/ConfirmPassword.php, there is a function __invoke which Confirm that the given password is valid for the given user.
In default, $username = config('fortify.username'); but my config('fortify.username') is set to auth that why it is not inside the database and return column not found
Is there a way to change this? cuz modifying the vendor is not a good solution.
You can do this in two ways and override the required items in Fortify
app()->singleton(ConfirmPassword::class, MyConfirmPassword::class);
or
// custom hook for confirming passwords
Fortify::confirmPasswordsUsing(function($user, $password) {
// your code!;
});

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null?

I got this error when try to seed database.
Laravel 7.
BlogPost Model
class BlogPost extends Model
{
protected $fillable = [
'title',
'slug',
'user_id',
'category_id',
'excerpt',
'content_raw',
'content_html',
'is_published',
'published_at',
'updated_at',
'created_at',
];
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
User model
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
User migration
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
BlogPost migration
Schema::create('blog_posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('category_id');
$table->foreignId('user_id')->constrained();
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt')->nullable();
$table->text('content_raw');
$table->text('content_html');
$table->boolean('is_published')->default(false)->index();
$table->timestamp('published_at')->nullable();
$table->foreign('category_id')->references('id')->on('blog_categories');
$table->timestamps();
});
User seeder
class UserTableSeeder extends Seeder
{
public function run()
{
$users = [
[
'name' => 'Author',
'email' => 'seriiburduja#mail.ru',
'password' => bcrypt('some1234')
],
[
'name' => 'Admin',
'email' => 'seriiburduja#gmail.com',
'password' => bcrypt('some1234')
]
];
DB::table('users')->insert($users);
}
}
BlogPost Factory
$factory->define(BlogPost::class, function (Faker $faker) {
$title = $faker->sentence(rand(3, 8), true);
$text = $faker->realText(rand(1000, 4000));
$isPublished = rand(1, 5) > 1;
$createdAt = $faker->dateTimeBetween('-6 months', '-1 day');
return [
'category_id' => rand(1, 10),
'user_id' => 1,
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
});
DatabaseSeeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(UserTableSeeder::class);
$this->call(BlogCategorySeeder::class);
factory(BlogPost::class, 1)->create();
}
}
When i run php artisan migrate:fresh --seed i got this error.
Tables users and blog_categories seeds successfully, but error appear for blog_categories.
I don't understand why.
Field user_id exists in $fillable in BlogPost Model.
If i change migration for blog_posts and add a nullable for user_id, than seed work, but user_id is null. But i don't need that.
Thansk in advance.
In Blog Post Model
Change user relationship to
public function owner()
{
return $this->belongsTo(User::class);
}
In User Model
Add this relationship
public function blogposts()
{
return $this->hasMany(BlogPost::class);
}
In Database seeder don't use UserSeeder Directly create user in DatabaseSeeder
public function run()
{
$user = User::create([
'name' => "Your name",
'email' => "youremail#gmail.com",
'password' => Hash::make('YourPassword')
]);
$this->call(BlogCategorySeeder::class);
$user->blogposts()->saveMany(BlogPost::factory(1));
}
In BlogPost Factory remove user_id
return [
'category_id' => rand(1, 10),
'title' => $title,
'slug' => Str::slug($title),
'excerpt' => $faker->text(rand(100, 400)),
'content_raw' => $text,
'content_html' => $text,
'is_published' => $isPublished,
'published_at' => $isPublished ? $faker->dateTimeBetween('-6 months', '-1day') : null,
'created_at' => $createdAt,
'updated_at' => $createdAt
];
fillable is not required when you are using Seeder to insert data.
If you want to insert each and every column in database then you can use guarded property which is opposite of fillable.

Code going through laravel basic authentication

Ok so I'm half way trough my app and I notice that I can pass code into my database. For example I use standard laravel authentication and if I type e.g.<?php die(); ?> instead of first name it passes right trough and goes into database. I'm confused now , I tought that laravel takes care of those things and thats one of the reasons I chose this framework. This is my last resort, I have been searching something in laravel documentation and all over the web about this and I found nothing.
Register Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
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 = RouteServiceProvider::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, [
'role' => ['required', 'string', 'max:100'],
'gendre' => ['required', 'string', 'max:100'],
'firstname' => ['required', 'string', 'max:100'],
'lastname' => ['required', 'string', 'max:100'],
'country' => ['required', 'string', 'max:100'],
'company' => ['required', 'string', 'max:100'],
'phone' => ['required', 'string', 'max:15'],
'email' => ['required', 'string', 'email', 'max:100', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'role' => $data['role'],
'gendre'=>$data['gendre'],
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'country' => $data['country'],
'company' => $data['company'],
'phone' => $data['phone'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname', 'lastname' , 'email','password', 'company', 'phone','country','role','gendre'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I only did some minor changes to what laravel already provides, nothing that special.
And Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('role');
$table->string('gendre');
$table->string('firstname');
$table->string('lastname');
$table->string('country');
$table->string('company');
$table->string('phone');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
I think there may be a little bit of confusion going on here!
SQL Injection Attacks
The Laravel framework uses things like prepared statements to prevent SQL Injection Attacks. The stops things like
"; DELETE FROM `users`"
being appended to a database query when inserting data provided by form requests.
Escaping Rendered Characters
Trying to render content into a blade template will also be escaped by default unless you explicitly tell it otherswise
# $php_code = "<?php die(); ?>"
{{ $php_code }}
This will render as a a string of "".
# $php_code = "<?php die(); ?>"
{!! $php_code !!}
This will render the php and stop the script from running
TLDR;
The fact the the input is "<?php die(); ?>" is fine provided it is treated as a string. At the end of the day, It's just a string of valid characters

Auto Login After successful registration in laravel 6 getting an error

I am getting an error while trying to Auto Login After successful registration in laravel 6 getting the following error.
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in
My Registercontroller is
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = RouteServiceProvider::HOME;
public function __construct()
{
$this->middleware('guest');
// $this->middleware(['auth','verified']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'min:3'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$username = slugify($data['name'])."-".mt_rand(10000, 99999);
$user = User::create([
'name' => $data['name'],
'username' => $username,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
Auth::loginUsingId($user->id);
}
}
User Model
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Jobs\SendEmailJob;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email','name','password','username','picture',
'ip_address','email_verified_at','email_token','verified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
function socialProviders(){
return $this->hasMany(socialProvider::class);
}
// This is the code define in the sendEmailVerificationNotification
public function sendEmailVerificationNotification()
{
SendEmailJob::dispatch($this);
}
}
You have overwritten the registration logic, but you have ignored the fact that create method needs to return an instance of App\User - or at least a class that implements Authenticatable.
Take a look at the original logic; you will see that the docblock shows that an instance of App\User is being returned and that the original implementation returns the result of the User::create() call.
To get your custom method working, update it like so:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => slugify($data['name'])."-".mt_rand(10000, 99999);,
'email' => $data['email'],
'password' => Hash::make($data['password']),
'email_token' => base64_encode($data['email']),
]);
}
Laravel will take care of logging the user in by default anyway.

Request Data to Model Function

I'm trying to find out why when I dd($request->all()) in the store method of my controller everything is correct, however when I send it to the model function register() its no where to be seen.
I'm not quite sure what I'm doing wrong.
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function store(Request $request, User $user)
{
$this->authorize('delete', $user);
$this->validate($request, [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
$userRegistered = $user->register(
new User($request->all())
);
if ($userRegistered) {
flash()->success('Success', 'The user has been successfully created!');
} else {
flash()->error('Error', 'The user could not be successfully created!');
}
return redirect()->to(route('users'));
}
}
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends Authenticatable
{
use SoftDeletes;
/**
* Fillable fields for a user.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'display_name',
'email',
'password',
'role_id'
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function register(User $user)
{
return $user->create([
'first_name' => $user->firstName,
'last_name' => $user->lastName,
'display_name' => $user->displayName,
'email' => $user->emailAdress,
'password' => $user->password,
'role_id' => $user->role
]);
}
}
You've mixed up the formatting of your variables between your request data and your User model.
According to your validation logic, the request data is coming is as camelCase. Yet, according to your $fillable array, the fields on your User model are snake_case. But, even then, in your register method, you're attempting to access the fields on the User model using camelCase.
You haven't given enough information for a definitive answer, but you need to fix the formatting of your variables. For example, change your request fields names from camelCase to snake_case, and make sure you access your fields on the model using snake_case.
You have to pass a list of attributes to "validate" method.
//...
$this->validate($request->all(), [
'firstName' => 'required|min:3',
'lastName' => 'required|min:3',
'displayName' => 'required|min:3',
'emailAddress' => 'required|email|unique:users,email',
'password' => 'required|min:3',
'role' => 'required|exists:roles,id'
]);
One more thing..check if you are using "web" middleware. (Kernel.php => MiddlewareGroups). Add that middleware to your route.

Resources