M
M
maks789452021-03-21 23:57:49
Laravel
maks78945, 2021-03-21 23:57:49

How to add additional condition in laravel authorization?

Good evening, tell me how you can change the user authorization method.
I have 2 User tables with a company_id field and other standard fields, as well as a Company table with id, name, active.
I need to authorize a user only if his company has active=1.
I managed to google solutions on how to change the Login method if active in the User table.
But what changes do I need to make in order to be able to implement my version, where the relationship by company_id and active is in another table?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2021-03-22
@maks78945

Migration - creating an additional binding field in an existing table with a foreign key.
public function up()
{
Schema::table('user', function (Blueprint $table) {
$table->integer('company_id')->unsigned()->default(1);
$table->foreign( 'company_id')->references('id')->on('company');
});
}
public function down()
{
Schema::table('user', function ($table) {
$table->dropForeign('user_company_id_foreign');
$table->dropColumn('company_id');
});
}
In the User model
public function company()
{
return $this->belongsTo('App\Company');
}
Check in login
$user->company->active

J
jazzus, 2021-03-22
@jazzus

company_id in users is wrong. You need to remove and add user_id to companies. And create a link between user hasMany companies and company belongsTo user. If companies can also have many users, then use the manyToMany relationship between User and Company. Request like this

User::whereHas('companies', function ($query) {
    $query->where('active', true);
})->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question