foreach the data of relationship - laravel

I have two tables media_user and users
media_user table like [ id | user_id | media_id | link ]
I need to bring all user from media_user by relationship, so I created relation in user model:
/**
* that users belong to the media_user table.
*/
public function media()
{
return $this->hasMany('App\Models\Social_Media','user_id','id');
}
And in the view, I did this
#foreach ($user->media as $m)
// my data
#endforeach
I got the empty array when I dump the result as dd($user->media)
What is the problem pls?

The relation looks fine, please check
there are some media items for the user with a correct foreign key.
there is an attribute in the user table called media.
there is no global scope.
the $user is a valid object and belongs to the ORM model
I suggest installing debug bar and view executed query on the media table

Related

I have a laravel project with 2 tables (users and roles). In a roles view, I am trying to display a count of users who are using that specific role

My tables areas follows
roles table (id, roleName, roleDesc)
users table (id, name, role, email)
When adding a new user, I insert a role eg "Admin" into the role column of the user.
My problem is that I want to show the number of users who have that role in a view data table that displays list of roles. Eg would simply be an integer of number of members who share that role, eg 5.
In my roleController, I am fetching records using
$roles = Role::all();
$users = User::all();
I have managed to display a count of users with role "Admin", but this ofcourse just duplicated all down the datatable with eg "1"
$RoleCount = User::where('role', '=', 'Admin')->count();
So, I think I need to use a join or something to replace the 'Admin' above, with current roleName.
I hope that makes sense and I hope someone can help me find a solution. I know this is pretty elementary, but trying to rap my head around joins and having a bit of trouble.
Thanks in advance.
First it will be great to use Relationships (Laravel docs)
With relationships it will be super easy.
Change Users table, so you have there NO the name of role, but ID of role = columns id, name, role_id, email
In Role model add relationship to User, and in User model add relationship to Role:
Model User.php - add method
public function role(){
return $this->belongsTo('App\Role'); //use your correct namespace
}
Model Role.php - add method
public function users(){
return $this->hasMany('App\User'); //use your correct namespace
}
And then just select all roles with count of users:
$roles = Role::withCount('users')->get();
In your view:
#foreach($roles as $role)
{{ $role->roleName }} - {{ $role->users_count }}<br>
#endforeach

How to get data from additional table in many to many relationship?

I have a many to many relationship between tables 'products' and 'recipes'. I created table product_recipe to handle this and my table looks like:
id | recipe_id | product_id | amount
In my blade file I use
#foreach($recipe->product as $row)
<p>{{ $row->name }}</p>
#endforeach
to get a name of used products in recipe. How I can get an amount of product which is stored in product_recipe table? Do I have to create a model for product_recipe table and get it from model?
You will have to declare the relationship wants to include the extra pivot information so that the pivot object that is attached to the records will have more than just the 'id's:
public function products()
{
return $this->belongsToMany(Product::class)->withPivot('amount');
}
Now the pivot object will include the field amount:
foreach ($recipe->products as $product) {
echo $product->pivot->amount;
}
"By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship"
Laravel 6.x Docs - Eloquent Relationships - Many To Many - Retrieving Intermediate Table Columns withPivot
You have to use pivot attribute.
#foreach($recipe->product as $row)
<p>{{ $row->pivot->field_name}}</p>
#endforeach
No need to create Model for product_recipe. Just specify table name in relation of two Models.
Like return $this->belongsToMany('App\Product', 'product_recipe')->withPivot('amount'); and similar for other model.

Invalid argument supplied for foreach() in laravel when use Eloquent: Relationships

I wanna get the class name of a user via the user ID. When I input the ID of a user so I will wanna get the class name. I have three tables such as users table, classes table, and class_users table. The class_users table is born from two users table and classes table.
A users table has an id, name, email, password.
A classes table has an id, class_code, class_name.
A class_users table has an id, class_id, user_id
And this problem relates to Eloquent Relationships.
Thank you for help.
My Route:
Route::get('/find_classes/{id}','StudentController#find_classes');
My Controller function:
public function find_classes($id)
{
$users = User::find($id);
foreach($users->classes as $class)
{
echo $class->name . '<br';
dd($class);
}
}
My User Model:
public function classes()
{
return $this->belongsTo('App\Classes','class_users','user_id','class_id');
}
Looks like you might have the wrong relationship set up on your User model. You have a one to many set up, but your DB is setup to handle a many to many. I suggest you change your User model relationship:
public function classes()
{
return $this->belongsToMany('App\Classes');
}
Note, you may need to name the FK on that relation, as I see you have class_id on the table, but your actual class is named 'Classes'. Check through your relationships to ensure this is explicit on the FK where it doesn't follow Laravel convention exactly.
With this relationship, your foreach loop should work. It would be a good idea for efficiency, as mare96 noted, to eager load the classes on the $users collection when you query:
$users = User::with('classes')->find($id);

Laravel: return multiple relationships

I have the following table:
The table is called user_eggs and it stores the user eggs.
eggs are items with additional data (hatch_time)
As you can see, user 2 has 2 eggs, which are items 46 and 47.
My items table stores the item general information such as name, image, description, etc...
How I can return the user eggs using $user->eggs() including the item data in my items table of the egg item_id?
I tried:
User Model:
/**
* Get the eggs
*/
public function eggs()
{
return $this->belongsToMany(Egg::Class, 'user_eggs','user_id','item_id')
->withPivot('id','hatch_time');
}
but $user->eggs() returns an empty array.
Any ideas?
A simple approach will be:
in your UserEgg model define:
/**
* Get the user associated with egg.
*/
public function _user()
{
return $this->belongsTo('App\User','user_id');
}
/**
* Get the item associated with egg.
*/
public function item()
{
return $this->belongsTo('App\Item','item_id');
}
then in your controller:
use the model to extract everything like this:
$userEggs = UserEgg::where('user_id',2)->get();
foreach($userEggs as $userEgg){
$associateduser = $userEgg->_user;
$associatedItem = $userEgg->item;
}
Short answer
If you loop through the user's eggs:
foreach($user->eggs as $egg){
$item = Item::find($egg->pivot->item_id);
}
If you want to query:
$user->eggs()->wherePivot('item_id', 1)->get();
Long answer
From the Laravel Documentation
Retrieving Intermediate Table Columns
As you have already learned, working with many-to-many relations requires the presence of an intermediate table. Eloquent provides some very helpful ways of interacting with this table. For example, let's assume our User object has many Role objects that it is related to. After accessing this relationship, we may access the intermediate table using the pivot attribute on the models:
$user = App\User::find(1);
foreach ($user->roles as $role) {
echo $role->pivot->created_at;
}
Notice that each Role model we retrieve is automatically assigned a pivot attribute. This attribute contains a model representing the intermediate table, and may be used like any other Eloquent model.
By default, only the model keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
If you want your pivot table to have automatically maintained created_at and updated_at timestamps, use the withTimestamps method on the relationship definition:
return $this->belongsToMany('App\Role')->withTimestamps();
Filtering Relationships Via Intermediate Table Columns
You can also filter the results returned by belongsToMany using the wherePivot and wherePivotIn methods when defining the relationship:
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
return $this->belongsToMany('App\Role')->wherePivotIn('priority', [1, 2]);

Laravel 5 get name based on ID

I have a users and departments table. So my departments table might have a row like so
id | departmentName
----------------------
2 | Marketing
----------------------
And the users table might have something like
id | name | email | departmentId
-------------------------------------------------------
18 | Nick | nick#email.com | 2
-------------------------------------------------------
So the users table links to the departments table via the id.
So now onto my UserController, in the index function, I do
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
Now that will display everything within my users table.
My problem is, I do not want to display the departmentId. I want to display the departmentName which is linked to that departmentID. So in the above example, my users index page for that one row should show Marketing, not 2.
How would I go about doing this?
Thanks
You can use Eloquent Relationships. What you described in your question is a One-to-Many Relation, meaning a department can have many users, and each user belongs to a department. So you'll need to setup a model for your departments table (if you haven't done so already) and then define the relationship in your User model like so:
class User extends Model
{
public function department()
{
return $this->belongsTo('App\Department', 'departmentId');
}
}
You can then access the department details in your view via that relationship:
#foreach ($users as $user)
{{ $user->department->departmentName }}
#endforeach

Resources