How to change User Table in Laravel? - php

I use Laravel 5.0.
I have user table in my DB.
I changed table variables in User and Config/Auth to user but when I try to register Laravel gives me an error:
Table 'xxxx.crmx_users' doesn't exist (SQL: select count(*) as aggregate from `xxxx` where `email` = xxx
What I do wrong? Why Laravel is still looking for userS table?

Go to app\Services\Registrar.php file, and in validator() function.
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
Change
'email' => 'required|email|max:255|unique:YOUR_TABLE_NAME',
I believe this will solve your problem.

Related

Laravel Jetstream - How to join a default team at registration

I am trying to change Laravel Jetstream's logic in order to join a default team at registration rather than create a personal team. I found the method that does this:
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'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'],
'password' => Hash::make($input['password']),
]), function (User $user) {
$user->currentTeam = Team::find(1); # SQLSTATE[42S22]: Column not found: 1054 Unknown column 'currentTeam' in 'field list'
$user->save();
});
});
}
The issue here is that currentTeam seems to be an created after the database level and not a column in the Database itself. The documentation says that currentTeam returns the Team model but doesn't say how to update the current users team programmatically.
I can see I can manually use a DB query to insert a row into the team_user table but there must be a method to do this.
return DB::transaction(function () use ($input) {
return tap(User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]), function (User $user) {
DB::table('team_user')->insert(['user_id' => $user->id, 'team_id' => 1, 'role' => 'rfn']);
$user->current_team_id = 1;
});
});
Any help would be appreciated, I understand this will be reliant on this team always existing in the Database but further measures will be implemented so it cannot be removed.
After some tinkering with a local Laravel version, this is was I came up with. This assumes the team you wanna add the user to is already created somehow, possibly through a seeder, or created manually. The file you need to edit is app/Actions/Fortify/CreateNewUser.php, namely the createTeam method.
Instead of creating a new team, we want to grab a team from the database, attach it to the newly registered user and then make that now attached team the users current team.
protected function createTeam(User $user)
{
$team = Team::first();
$user->teams()->attach($team);
$user->switchTeam($team);
}
The reason we first need to attach the team first is that switchTeam checks if a user belongs to that team if it doesn't it returns false and doesn't switch to the new team. By attaching the team first we make the user belong to that team before we can actually switch to it as the current team.
you can assign role as well in above answer of #KimHallberg as below
$team = Team::first();
$user->teams()->attach($team, array('role' => 'editor'));
$user->switchTeam($team);

Laravel unique validation with softdeletes data

I want to use Laravel Unique validator with the implementation of softdeletes. I've been try many times but it produce an error like this. What should i do? Thanks in advance. Here's my code example.
public function store(Request $request)
{
$request->validate([
'nama' => 'required',
'nim' => [
'required',
'size:10',
Rule::unique('students')->where(function ($query) {
return $query->where('deleted_at', NULL);
})
],
'email' => 'required|email',
]);
Student::create([
'major_id' => $request->major_id,
'nama' => $request->nama,
'slug' => Str::of($request->nama)->slug('-'),
'nim' => $request->nim,
'email' => $request->email,
]);
return redirect('/students')->with('status', 'Success');
}
The error you're getting is from a constraint in your database. Nothing you can do in the code can counter that. The database doesnt care for soft delete.
You need to remove the constraint from the database first, then use your solution or the one from this post check-if-name-is-unique-among-non-deleted-items-with-laravel-validation
To remove the constraint, run this query
ALTER TABLE students DROP CONSTRAINT students_nim_unique;
The best practice would be to create a new migration running this query. Carefull for the down() method, you will not be able to put back the constraint if there are dupplicate nim in the table (soft deleted or not)

How to insert into another table after Registration on Laravel?

So, I have a laravel web and have some tables, two of them are users and user_data.
user_data have a foreign key user_id that references to id on users.
users have general attributes like username, email, password, etc. and user_data have 1 on 1 relation with users and have attributes like game_money, game_job, game_tier, etc.
The columns are too long if I combine those 2 into 1 table, so I tought to normalize it.
User registration is working and running smooth. But I don't know how to add a new entry into user_data when a new user registered and add a new entry in users.
The attributes columns in user_data (like game_money,etc.) are filled by external application outside laravel, so all I need is to add an entry to user_data.user_id foreign key, and let the other attributes in user_data use the default values or null before being updated by the external apps.
Here is my user_data migration:
Schema::create('user_data', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->string('account_tier')->default("Free");
$table->float('economy')->default(0);
$table->string('job')->nullable();
$table->timestamps();
});
Where should I put the insert query inside laravel? Or should I handle user_data using the external app?
Thank you very much.
You should use an id on user_data table as your primary key. By the way you can just use the following code for your desired result.
In the registration method use something like below:
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
The user variable is holding the information of the newly created user. Now its time to insert into your user_data table. Assuming the model is UserData.
UserData::create([
'user_id' => $user->id,
............
]);
In RegisterController
inside create function
$user= User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
//UserData is the Model of user_data table
$user->UserData->create(['job'=>$data['job']]);
return $user
Try To This Example:
use Illuminate\Support\Facades\DB;
$user_data= array(
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
);
$role_data= array(
'user_name' => $data['name'],
'email' => $data['email']
);
$response = DB::table('users')->insert($user_data);
$response = DB::table('role')->insert($role_data);
You can use the Model boot events as following when you define relationship each other these models;
public static function boot()
{
parent::boot();
self::created(function($model){
$model->userData()->create([
'user_id' => $model->id,
'job' => $model->job
]);
});
}

Laravel 5.5 unique validation rule on seperate table with different column name

So I have users and companies. A user belongs to one company.
I want to validate a user registration so that the business_name field they use to register is unique in the companies table, the goal is to not allow users from creating duplicate companies.
Here is my register function:
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'business_name' => 'required|unique:companies',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->messages()], 401);
}
}
The field I want to compare against is the companies.name to check for uniqueness.
Is this possible? At the moment it is trying to look for business_name in the companies table.
Never mind, managed to figure it out. Just needed an extra parameter to specify the column name:
'business_name' => 'required|unique:companies,name',

Laravel 5.3 and Zizaco/entrust : Field 'expired_at' doesn't have a default value

I am using composer Zizaco/entrust and Laravel 5.3's Auth out of the box,
I modified the method create of RegisterController.php like this:
protected function create(array $data)
{
$user =User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->roles()->attach($data['role']);
return $user;
}
The original method create is as follow:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
When I register an user with the modified method,there are 2 problems:
1、There is an error on table role_user:
SQLSTATE[HY000]: General error: 1364 Field 'expired_at' doesn't have a default value (SQL: insert into `role_user` (`role_id`, `user_id`) values (2, 5))
2、Another question is on table users,the field remember_token of table users is null.
It's not at the users table. its on role_user table.
If you have the migration on role_user put nullable on expired_at column should solve it.
Or
You can edit your database.php under config folder. and set strict to false.
For question number 2:
You need to set remember when attempt:
if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) {
// The user is being remembered...
}
for more information about it: https://laravel.com/docs/5.3/authentication#remembering-users
By default remember_token is nullable

Categories