Laravel: How to merge a Model into another Model - php

I'm using Lumen to create an API which has to handle 2 entities: Gamemaster and Player. Both of them are actually a User of my API since they have to provide a token. So at the end, 'gamemaster' and 'player' are just an 'user' role.
So I manage them using 3 Models that handle informations from the database (I keep it simple for the example):
User:
id
username
email
password
Gamemaster:
user_id (user id as foreign key)
created_games
...
Player:
user_id (user id as foreign key)
registered_games
...
So my question is: Is it possible to merge the Model User into Gamemaster and Player? So that I can for example get a gamemaster email using Gamemaster::find($id)->email. Is there any way or I should each time search in both models to get all infos:
$user = User::find($id);
$userAsGamemaster = Gamemaster::where('user_id', '=', $id)->first();
$gamemasterName = $user->username;
$gamemasterEmail = $user->email;
$gamemasterCreatedGame = $userAsGamemaster->created_games;

use relations on model for this.
As in your case Gamemaster and Player both belongs to User so you can define relation on Gamemaster model and Player Model as following: ->
public function user(){
return this->belongsTo('App\User', 'your_foregin_key', 'Your_local_key');
}
Now You can fetch email as follows: ->
$userAsGamemaster = Gamemaster::where('user_id', '=', $id)->first();
$email = $userAsGamemaster->user->email;
Or by using:
Gamemaster::find($id)->user->email;
That's all.

Okay. I write in an answer what we had been talking about in the comments.
Not answer to the question of merge two models, but you can achive what you want defining the relationship in your models Gamemaster and Player:
public function user()
{
return $this->belongsTo(User::class);
}
So, if you have the User model id in the $id variable, you can do something like this:
$gamemaster = Gamemaster::where('user_id', $id)->first();
$gamemasterName = $gamemaster->user->username;
$gamemasterEmail = $gamemaster->user->email;
$gamemasterCreatedGame = $gamemaster->created_games;
And if in the $id variable you have the Gamemaster model id, you can do something like this:
$gamemaster = Gamemaster::find($id);
$gamemasterName = $gamemaster->user->username;
$gamemasterEmail = $gamemaster->user->email;
$gamemasterCreatedGame = $gamemaster->created_games;
And the same for the Player.

Related

Laravel 5.* - Eloquent Many to Many Relationships

I have the following tables
USERS = username | email | name
FOLLOWERS = user_id | follower_id
When a logged-in user clicks on "follow" my code saves his id inside followers.follower_id, and the id of user who he wants to follow is saved inside followers.user_id.
To see how many followers a user has and how many users a user is following I use:
$followers = Follower::where('user_id', $user->id)->count();
$following = Follower::where('follower_id', $user->id)->count();
This works well, but I would like to show information about the followers of one user. I've tried the following:
$first_follower = $followers[0]->user->username;
But it return the user followed not the follower.
I am wondering how I can get information about the follower
User Model
protected $fillable = ['username','email','name'];
public function follow() {
return $this->hasMany('Shop\Follower');
}
Follower Model
protected $fillable = ['user_id','follower_id'];
public function user() {
return $this->belongsTo('Shop\User');
}
An example how you should implement relations, is above. It's many users to many users thru followers table. You probably dont need a follower model, cause you already have a user model. Your code will work after some analyze and enhancements, but i will highly recomend you to make something like this inuser model instead:
public function followers()
{
return $this->belongsToMany('App\User','followers','user_id','follower_id');
}
public function following_users()
{
return $this->belongsToMany('App\User','followers','follower_id','user_id');
}
Than you can access a followers $user->followers (this will return eloquent collection and you will be able to do whatever you want with this according to laravel docs collection api) and a certain one like $user->followers[0]
Hope i get your answer rigth.
If I get this right the followers are instances of the User class/model, so you don't need a Follower model. You can just define a Many To Many Relationship
In your User model you can add:
public function followers()
{
return $this->belongsToMany('Shop\User', 'followers', 'user_id ', 'follower_id');
}
public function following()
{
return $this->belongsToMany('Shop\User', 'followers', 'follower_id', 'user_id');
}
Than you can access the user followers just by $user->followers which will return a Laravel Collection and with $user->following you can access the ones that the user is following.
//Get the count of all followers for $user
$count = $user->followers()->count();
//Get the count of all followed by $user
$count = $user->following()->count();
//Get the username of the first follower
$follower = $user->followers()->first();
echo $follower->username;
//Loop trough all followers
foreach ($user->followers as $follower) {
echo $follower->username;
}
Defining this relation can help you save/delete followers just by using the attach() and detach() methods
// The $user will be followed by an user with $followerId
// A record in the `followers` table will be created with
// user_id = $user->id and follower_id = $followerId
$user->followers()->attach($followerId);
// The $user will stop be followed by an user with $followerId
$user->followers()->detach($followerId);
A side note:
There is a difference between calling the followers() method and calling the followers property. The first will return BelongsToMany relation and you can call all the Eloquent query builder method on it and the later will return a Collection
/** #var Illuminate\Support\Collection */
$user->followers;
/** #var Illuminate\Database\Eloquent\Relations\BelongsToMany */
$user->followers();

Laravel include relationships with model after update

I'm using a role package which stores hasMany relational data in my database. So there is a users table and a user_roles table with foreign keys...etc...
I am updating the model using the following code:
$user = User::findOrFail($id);
$user->update(request()->all());
$user->syncRoles(request()->input('roles', []));
Is there any way I can keep a reference of the roles on the $user variable so they can be used after these lines of code run?
I'm asking because I'm using a logging system after the fact like so:
activity()->on($user)->by(auth()->user())->withProperties([
'user' => $user,
'roles' => request()->input('roles'),
])->log('Updated User');
Which I would like to condense to just:
activity()->on($user)->by(auth()->user())->withProperties($user)->log('Updated User');
You will need to refresh the model data from the database. E.g.
$user = $user->fresh('roles');
For example using lazy loading:
$user = User::findOrFail($id);
$roles = $user->roles;
and on your User Model you would create a HasMany relationship to roles table.
Eager loading:
$user = User::with('roles')->findOrFail($id);
Add the relationship in your User.php model :
public function roles(){
return $this->hasMany(Role::class);
}
Now simply call it in your code to get the roles like so:
$aUser = User::with('roles')->find($id);
$roles = $aUser->roles;

Laravel many to many retrieve data across multi table

Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.
Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;

collection to string in laravel 5.2 query builder

I want to make query in laravel 5.2 to fetch agencies table which has a foreign key with organizations table using agencies.organization_id=organizations.id. Now Users table has also foreign key with organizations table using users.organization_id=organizations.id. Now how to fetch agency table that which agencies are linked with users_id.
public function postagency(Request $request) {
$user_id = $request->user_id;
$org_id = User::where('id', $user_id)->pluck('organization_id')->first();
$postagencies = agency::where('organization_id', $org_id);
echo $postagencies;
}
For what I understand is that an user can only be under one organisation and an organisation has many agencies. If not please say so and I will alter my answer.
First of all set your relationships inside your models. An example would be:
// User.php
public function organization()
{
return $this->belongsTo('App\Organization'); // App\Organization can be changed depending on the used namespace
}
More info can be found here. If you need some more examples just ask.
After you have created these relationships you can retrieve your agency like this:
$user= User::find($request->user_id);
if (!$user) ... // Check if user exists
$agencies = $user->organisation->agencies;
If I need to explain things in more detail just ask. Hope this helps :)

How can i get all posts by a particular user in Laravel?

Try to get all post's by a user in application and show in a table with corresponding column , i tried with this way but showing exception : " Trying to get property of non-object " , how to solve it ?
public function usersPost(){
$uid = \Auth::user()->id;
$posts = DB::table('posts')->('user_id',$uid);
}
Here two table posts and users and user_id is foreign key of posts table .
Laravel allows you to relate models to each other. For instance, you can relate your Post model to your User model like this.
class User extends Eloquent {
public function posts() {
return $this->hasMany('Post');
}
}
After specifying that the User has many posts through a One-to-Many relationship, you can then simply call all of your user's posts.
$posts = User::find(user_id)->posts;
public function usersPost() {
$posts = DB::table('posts')->where('user_id', auth()->id())->get();
}
You need a where clause like this:
$posts = DB::table('posts')->where('user_id', $uid)->get();

Categories