To achieve the desired relationship without using whereRaw, you can use a combination of Eloquent relationships and query scopes to make the code cleaner and more maintainable. However, as of Laravel 11, there isn't a built-in way to directly add conditions to relationships in a more elegant way than using whereRaw for this specific case.
Here's a refined approach using a query scope to encapsulate the condition logic:
-
Define a scope in the
Usermodel:
// In User.php model
public function scopeAdminUser($query, $companyEmail)
{
return $query->where('email', $companyEmail);
}
-
Use this scope in the
Companymodel to define the relationship:
// In Company.php model
public function adminUser()
{
return $this->hasOne(User::class, 'company_id', 'id')
->adminUser($this->email);
}
This way, you encapsulate the condition logic within the User model and make the relationship definition in the Company model cleaner.
Here is the complete code for both models:
User.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// Other model methods and properties
public function scopeAdminUser($query, $companyEmail)
{
return $query->where('email', $companyEmail);
}
}
Company.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
// Other model methods and properties
public function adminUser()
{
return $this->hasOne(User::class, 'company_id', 'id')
->adminUser($this->email);
}
}
With this approach, you avoid using whereRaw directly in the relationship definition, making the code more readable and maintainable. The scopeAdminUser method in the User model encapsulates the condition logic, and the adminUser method in the Company model uses this scope to define the relationship.