I have a user table it has one userRole and userRole belongs to Role. So, I want to fetch the userRole and Role also.
Code in user Model:
public function userRole()
{
return $this->hasOne(UserRole::class);
}
Code in UserRole model:
public function role()
{
return $this->belongsTo('App\Role');
}
Code in controller:
User::with('userRole', function ($role) {
$role->with(['Role']);
})
->wherehas('userRole', function ($query) {
$query->where('role_id','1');
})->get();
This is giving me error
"mb_strpos() expects parameter 1 to be string"
The problem is that you should pass an array when you want to add a constrait to the with() method.
Your code should like something like:
User::with([
'userRole' => function ($query) {
...
}
])
...
Related
I have laravel's basic auth system, a custom model called SecurityQuestion and a pivot table called securityquestion_user
User
public function securityquestion_user() {
return $this->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
SomeController
First option
foreach(Auth::user()->securityquestion_user as $question) {
dd($question);
}
Error: Undefined property: Illuminate\Database\Eloquent\Relations\BelongsToMany::$pivot
Second Option
foreach(Auth::user()->securityquestion_user() as $question) {
dd($question);
}
Error: returns false
Ok guys I got it,
I modified the relation to this:
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion', 'securityquestion_user', 'user_id', 'question_id')->withPivot('question_id', 'user_id', 'answer');
}
Basically I reversed the order and place 'user_id' parameter before 'question_id' parameter.
foreach(Auth::user()->securityquestion_user as $question) {
print '<pre>';
print_r($question->pivot->answer);
print '</pre>';
}
Thank you very much for you interest.
Have you added namespace for auth in controller?
Like:
use Auth;
If not imported then use this for it:
foreach(\Auth::user()->securityquestion_user as $question) {
dd($question);
}
And also correct your function in user model
public function securityquestion_user() {
return $this->belongsToMany('App\SecurityQuestion::class', 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
because your first option is correct except it!!
Try by using hasMany instead of belongsToMany in user model
public function securityquestion_user() {
return $this->hasMany (SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')->withPivot('question_id', 'user_id', 'answer');
}
Try like this, withPivot function expects one parameter: array or string.
public function securityquestion_user() {
return $this
->belongsToMany(SecurityQuestion::class, 'securityquestion_user', 'question_id', 'user_id')
->withPivot(['question_id', 'user_id', 'answer']);
}
And 'question_id' and 'user_id' are not necessary to be in withPivot function, since they are the foreign keys.
i have a two tables where user table has a one to one relationship with role table
this is my user model
public function role(){
return $this->belongsTo(Role::class);
}
this is my role model
public function user(){
return $this->hasOne(User::class);
}
this my table structure for role
this my table structure for user
how can i access in my user model the role which is equal to employee
i tried
User::with('role')->where('role_name','employee')->get();
but it has an error
role_name column not found
This will give you only the users which has an employee role .
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
And this will give you all the users with their employee roles if any exist
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();
Try this:
User::whereHas('role', function ($query) {
$query->where('role_name', 'employee');
})->get();
Details at: https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence
Try this:
User::with(['role' => function ($query) {
$query->where('role_name', 'employee');
}])->get();
I have a problem with related models.
There are three models. User, PostType (music, animals) and Post.
A user can select the posttypes he wants to see. So I created a pivot-table posttype_user.
Now I can save the selected postTypes binded to a user.
// User model
public function postTypes()
{
return $this->belongsToMany(PostType::class);
}
// PostType model
public function users()
{
return $this->belongsToMany(User::class);
}
The Post model has a foreign key with postType_id. And this relationships in the models:
// Post model
public function postType()
{
return $this->belongsTo(PostType::class);
}
// PostType model
public function post()
{
return $this->hasMany(Post::class);
}
Now I want to receive all Posts (of the selected posTypes) from the current user (Auth::user()).
But I don't know how. Does anyone have an idea?
You can use nested whereHas():
Post::whereHas('postType', function($q) {
$q->whereHas('users', function($q) {
$q->where('id', auth()->id());
});
})->get();
Or you can do this:
$postTypeIds = auth()->user()->postTypes()->pluck('id');
$posts = Post::whereIn('post_type_id', $postTypeIds)->get();
Hey how can I make relationships between two table.
Users: id, email
Notification: id, user_id(id of the logged user), client_id(id of sender)
I would like make relationship between users and notifications by user_id and client_id.
Then I will can get all notifications assigned to logged user, and get email of sender users.
I made that:
public function notifications_with_client() {
return $this->hasManyThrough('App\Models\User', 'App\Models\Notification', 'user_id', 'id', 'client_id');
}
But when I using query i got good notifications but with wrong email.
I got email from ralationship id(from users table) == id(from notifications table)
My query
$column = 'notifications_with_client';
$value[1] = ['email', 'notifications.id', 'client_id'];
$query->with([$column => function($query) use ($value) {
$query->select($value[1]);
}]);
Someone know what I do wrong?
You can try it by defining the following relations:
User Model
public function notifications()
{
return $this->hasMany('App\Models\Notification');
}
Notification Model
public function to()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function from()
{
return $this->belongsTo('App\Models\User', 'client_id');
}
And then you can query it as:
$notifications = auth()->user()->notifications()->with('from')->get();
Or if you just want email then query it as:
$notifications = auth()->user()
->notifications()
->with(['from' => function($q) {
$q->select('email');
}])
->get();
public function user()
{
return $this->belongsTo(Users::class, 'user_id');
}
public function client()
{
return $this->belongsTo(Users::class, 'client_id');
}
With this code in your Notification Model you can get the logged user with
$this->user(); // $notification->user();
and the sender with
$this->client(); //$notification->client();
You cannot use $this->hasManyThrough(). It use for a different reason
You can use $this->belongsTo() like this.
class User extends BaseModel
{
public function user()
{
return $this->belongsTo(Notification::class, 'user_id');
}
public function client()
{
return $this->belongsTo(Notification::class, 'client_id');
}
}
Then you can query like.
User::with(['user']);
or
User::with(['client']);
I have the following model relationships. If a user logs in as an employee, I want them to be able to get a list of employees for a their company and the roles they have been assigned:
class User {
// A user can be of an employee user type
public function employee()
{
return $this->hasOne('App\Employee');
}
//
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
class Employee {
// employee profile belong to a user
public function user()
{
return $this->belongsTo('App\User');
}
// employee belongs to a company
public function company()
{
return $this->belongsTo('App\Company');
}
}
class Company {
public function employees()
{
return $this->hasMany('App\Employee');
}
}
But the following query doesnt work. I get error Column not found: 1054 Unknown column companies.id in WHERE clause:
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles' => function ($query) use ($employee) {
$query->where('companies.id', '=', $employee->company_id)
->orderBy('users.created_at', 'desc');
}])->get();
The users and the employees table have a one to one relationship.
All employees have a base role type of employee in addition they may also have other roles such as manager, supervisor etc.
How do I write a query that gives me a company with all its employees and their roles?
I've tried to add a hasManyThrough relation to the Company model but that doesn't work either?
public function users()
{
return $this->hasManyThrough('App\User', 'App\Employee');
}
I think you're ring to get a list of coworkers for the current user and eager load the user and role?
$employee = Auth::user()->employee;
$companyEmployees = Company::with(['employees.user.roles')->find($employee->company_id);
Or perhaps:
$companyEmployees = Company::find($employee->company_id)->employees()->with('user.roles')->get();
$sorted = $companyEmployees->sortBy(function($employee){ return $employee->user->created_at; });
That might be a more direct route. Is your employee id in the user table or vice versa? The eloquent relationships are easy to set backwards.
Users::select('table_users.id')->with('roles')->join('table_employes', function($join) use ($employee) {
$join->on('table_employes.user_id','=','table_users.id')->where('table_employes.company_id', '=', $employee->company_id);
})->orderBy('tables_users.created_at')->get();
1. Create relationship for database table columns in migrtaion :
User Role
$table->foreign('user_id')->references('id')->on('users');
Users
$table->increments('id');
2. Create a model for each database table to define relationship
User.php (model)
public function userRoles()
{
return $this->hasOne('App\UserRoles', 'user_id', 'id');
}
Userroles.php (model)
public function user()
{
return $this->belongsTo('App\User', 'user_id', 'id');
}
3. Let controller handle database calls recommended to use REST api
Controller
use App\User;
use App\UserRoles;
class UserController extends Controller
{
public function index()
{
return User::with('userRoles')->orderBy('users.created_at', 'desc')->paginate(50);
}
}