I want to know how to make relationship using laravel Model & Eloquent.
I have data structur something like this
UserTable
username
groups
id
GroupTable
id
name
remark
My question is how to display user groups (user can assign to many groups)
and how to count how many users that assigned to each group.
thanks.
Update
public function store(Request $request){
$member = new Member();
$member->username = $request->input('name');
$member->gender = $request->input('gender');
$member->joindate = $request->input('joindate');
$member->remarks = $request->input('remarks');
if ($request->hasFile('photo')) {
if ($request->file('photo')->isValid()) {
$path = $this->upload($request);
}
}
$member->save();
foreach ($request->only('groups[]') as $key => $group){
$pivot = new pivot();
$pivot->user_id = ????? //how to get user id?
}
}
public function upload(Request $request)
{
$path = $request->file('photo')->store('profile');
return $path;
}
is that right?
and how to get currently saved user_id (it has auto increment column).
You will need to create a pivot table assigning each user to their respective groups.
so basically your tables would be like:
User Table
id
username
Groups Table
id
name
remark
User -> Group Pivot Table
user_id
group_id
Then you can use an Eloquent relationship on your user model to define your relational method like so:
class User extends Model {
public function groups() {
return $this->belongsToMany(Group::class, 'user_group_pivot_table_name', 'user_id', 'group_id');
}
}
Finally, you can return a collection of all the user’s groups by doing the following:
$user->groups();
The Laravel documentation on the Eloquent ORM is phenomenal too. Happy hunting.
Related
I have three tables in database
users
locations
location_user (columns: user_id, location_id)
I'm fetching records from locations table in multiple-drop-down field of user registration form. While filling form user has to select value from drop-down and then submit.
After submitting the form I want to insert data into users table. At the same time I also want to insert id from users table into user_id column of location_user and selected value of locations from drop-down of user registration form into location_id column of location_user table.
I know how to get this to work using eloquent but I as i mentioned in the question I want to know how to deal with this task using query builder of laravel.
Is there any reason to use a pivot table here? If you're going to tie a location to a user then just add a location_id field to the user table and have a one to many relation (location, user). I don't see any reasoning to use pivot table here unless you want a user to have multiple locations.
Anyway if you follow my advice it becomes easier. But with the current table structure, you need to setup relationships in the respective models. Then on form submit, create the user and attach the location to the user.
User model
public function locations()
{
return $this->belongsToMany('App\Location');
}
Location model
public function users()
{
return $this->belongsToMany('App\User');
}
Controller
$user = User::create($request->all());
$user->locations()->attach($request->location_id);
you must use this code:
$user = new user;
$user->title = $request->title; // your value
$user->username = $request->username // your value
$user->save();
$user->locations()->attach([1,2]); // or ->attach($location_id);
/// or $user->locations()->sync([1,2])
this is a example for your project when use ORM Eloquent and define relationship in models.
you can attention my example:
model Product
class Product extends Model
{
public function Categories()
{
return $this->belongsToMany('App\Category','product_category','category_id');
}
}
model Category
class Category extends Model
{
public function Products()
{
return $this->belongsToMany('App\Product','product_category','product_id');
}
}
when you want insert in your database you must write this code in your controller
$validated = $request->validated();
$user = Auth::user();
$product = new Product;
$product->title = $request->title;
$product->off_price = $request->off_price;
$product->price = $request->price;
$product->available = $request->available;
$product->user_id = $user->id;
$product->save();
$product->Categories()->attach($request->categories/* this is an array*/);
Here, this creates 3 separate queries using the query builder to get to what you want.
$user_id = DB::table('users')->insertGetId(
['something' => 'something']
);
$location_id = DB::table('locations')->insertGetId(
['something' => 'something']
);
DB::table('location_user')->insert(
['user_id' => $user_id, 'location_id' => $location_id]
);
But Laravel's ORM deals with this, so if you have your models mapped properly, you could do something like this:
$location = $user->locations()->create([
'something' => 'something.',
]);
See here: https://laravel.com/docs/5.4/eloquent-relationships
I have a website build in Laravel.
I have two tables - Groups and Group members.
For each group_member, the row in the table has id, group_id and user_id.
The groups have a name and a description.
When a user joins a group, a row is created in the group_member table.
But I now need to get the groups that a user is part of.
So if I have user_id = 5, I need to get all the rows in group_member where user_id = 5, and then get the corresponding group, so I can query the groups.
I need to do something like $groups = Groups::whereGroup_member ...
But I cant query the model like that, because in Groups there is no where it specificies who the members are, it is just the group details - the members are specificed in group_member table.
How do I get the groups, which a member is part of using the laravel query standards?
In your User.php Model
public function group_member(){
return $this->hasMany(GroupMember::class,'user_id','id;);
}
In your GroupMember.php Model
public function group(){
return $this->belongsTo(Group::class,'group_id','id');
}
Your query will be
$users = User::with('group_member.group')->find($user_id);
You should use Many-to-Many relation:
class Group
...
public function members() {
return $this->belongsToMany(User::class); // Users (members) that belongs to Group
}
class User
...
public function groups() {
return $this->belongsToMany(Group::class, 'group_member', 'user_id', 'group_id'); // Groups that User belongs to
}
And at controller, when You have user id:
$groups = User::where('id', $user_id)->groups;
More about this written at official docs: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);
The relevant portion of my application is set up as follows:
A Users table, with unique user IDs
A Teams table, with unique team IDs
A Team_Membership table, with
a unique ID and a column for a User ID and a Team ID, to denote
that a user belongs to a team.
A user can be on an unlimited number of teams.
I have a function to retrieve an array of the teams a given user belongs to. It would generally be called in the scope of the current logged in user to get their active teams, but will also be used in administrative functions to return the teams of a given user ID.
My first thought was to make the function callable from the user model, so for a given user object, I could do as follows
$teams = $user->get_teams();
or
$teams = User::get_teams($user_id);
But I'm not sure if this is generally considered best practice in Laravel for this type of functionality. Where should this function be located?
Actually, you are talking about something that laravel already does for you if you are using Eloquent.
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
public function teams()
{
return $this->belongsToMany(Team::class);
}
}
class Team extends Model
{
protected $table = 'teams';
public function users()
{
return $this->belongsToMany(User::class);
}
}
In addition to the users and teams table you would make a pivot table:
team_user
id - integer
team_id - integer
user_id - integer
and laravel does the rest.
$userId = 1;
$user = User::with('teams')->find($userId);
$teams = $user->teams;
I have created model so that users can be friends. I have table user_friends where user_id and friend_id are stored. The problem is, that it works only one-way. If user 1 adds user 2 as friend, user 2 will be friend of user 1 but not reverse (user 1 friend of user 2) how can I accomplish something like this?
User model
public function friends()
{
return $this->belongsToMany('User','user_friends','user_id','friend_id');
}
and User_Friend model
public function user()
{
return $this->belongsToMany('User');
}
Finding friends
$friends = User::find($user->id)->friends;
And part of controller where I save new friendship
$friendData = array('user_id' => $invite->id,); //$invite is result of $invite->save()
$friend = User::find($user->id)->friends()->attach($friendData);
One thing you can do is store and the reverse relationship.
$friendData = ['user_id' => $invite->id];
$user = User::find($user->id);
$user->friends()->attach($friendData);
$friend = User::find($invite->id);
$friend->friends()->attach($user);
Otherwise you may retrieve the reverse relationship
public function reverseFriends()
{
return $this->hasManyThrough('User', 'User_Friend', 'friend_id', 'user_id');
}
and then merge the two collections.