Laravel 5.6 Many to Many relationship - accessing child fields in view - laravel-5.6

I have a Many to Many relationship between User and Project. I am trying to list a users projects but can't access the child fields in a view:
Models
// Project
public function users() {
return $this->belongsToMany('App\User')->withTimestamps();
}
// User
public function projects() {
return $this->belongsToMany('App\Project')->withTimestamps();
}
Intermediate table: project_user
user_id, project_id, timestamps
Controller
$projects = User::with('projects')->where('id', auth()->user()->id)->get();
return view('home')->with('projects', $projects);
View
#foreach($projects as $project)
- {{ $project->name}}
<br>
#endforeach
This returns no errors and no results
If I try $projects->projects as $project I get "projects" not available to this collection.
If I return $projects in the controller I get:
[
{
"id": 1,
"first": "User",
"last": "Name",
"organization": "Organization",
"phone": "5555555555",
"email": "test#example.com",
"created_at": "2018-03-22 20:16:20",
"updated_at": "2018-03-22 20:16:20",
"projects": [
{
"id": 10,
"name": "Project One for User One",
"description": "Project Description",
"created_at": "2018-03-22 20:16:20",
"updated_at": "2018-03-22 20:16:20",
"pivot": {
"user_id": 1,
"project_id": 10,
"created_at": "2018-03-22 20:16:20",
"updated_at": "2018-03-22 20:16:20"
}
},
...
How can I access the child fields name and description?

First, you do not have to query for the user, as it is already authenticated. If you use something like the Debugbar package, you can see that it will query the user for the current session.
So, to fetch the currently authenticated user, you can simply use:
$user = auth()->user(); // you can als use this in the view if you want.
In the controller, your code:
$projects = User::with('projects')->where('id', auth()->user()->id)- >get();
Will do a query to fetch all users with id = auth()->user()->id and it will eagerload all projects of those users (<- plural !!!).
So the $projects variable contains all the users with that id and it will attach all the projects in a subsequent query. Hence it is giving you an array of user objects, instead of the projects that you want. Which makes sense, since you are querying the User table.
Personally, I would do something like this in the controller:
$user = auth()->user();
$projects = $user->projects->get(); // doing this here will allow you to change get() to paginate() if you want.
return ('home')->with(['projects' => $projects]); // < either use compact as in the docs, or an associative array
Now in the view $projects will contain a Collection of projects, not users, and you can simply do:
#foreach($projects as $project)
- {{ $project->name}}
<br>
#endforeach

Related

How to get data from laravel relationship in single object?

IN USER MODEL this is my relation
public function User() {
return $this->belongsTo('App\models\Users','UserId');
}
IN WALLET MODEL this is my relation
public function Wallet() {
return $this->HasOne('App\Models\Wallet','UserId','Id');
}
but when i am running the query
$user = Users::with([
'Wallet' => function($query){
$query->select('test_userwallet.UserId','test_userwallet.CoinBalance');
}
])->get()->toArray();
i am getting the data in a object like this
{
"Id": 1,
"UID": "8oDI617ZlsInXtUkRpMqVKo5J4XPzI12567",
"CountryCode": "91",
"Status": "active",
"TimeStamp": "2021-02-12 06:43:08",
"wallet": {
"UserId": 1,
"CoinBalance": 6
}
which is totally fine but i am guessing is there any way or method by which i can get the data in this format
{
"Id": 1,
"UID": "8oDI617ZlsInXtUkRpMqVKo5J4XPzI12567",
"CountryCode": "91",
"Status": "active",
"TimeStamp": "2021-02-12 06:43:08",
"UserId": 1,
"CoinBalance": 6
}
like in single object as i am working in apis so i want to do like that
note : only using query or eloquent
you can do this using join:
$user = Users::query()->leftJoin('test_userwallet','test_userwallet.UserId','users.id')
->select(['test_userwallet.Id','UID','CountryCode','Status','TimeStamp','UserId','CoinBalance'])
->get()->toArray();
You've specified only using query or eloquent.
I would say the best way would be to return your endpoint response as a Resource from your controllers.
But if you must do it as a property on the model. You can use the $appends array and an accessor. See docs This will add the properties to the model any time it is serialised like when it's returned in a response.
protected $appends = [
'coin_balance',
];
public function getCoinBalance Attribute()
{
return $this->Wallet->coin_balance;
}

Retrieve username from User table for each member in a Team

I'm facing some issues in establishing relationships amongst User, Clan, and Clan Member models. I have three models in which I have defined the relationship as...
Clan model
public function clanMembers() {
return $this->hasMany('App\ClanMember', 'clan_id', 'clan_id');
}
ClanMember model
public function clan() {
return $this->belongsTo('App\Clan', 'clan_id', 'clan_id');
}
I am trying to get Clan details of a requested user and his other Clan Members. I am using the following:
$clanMembers = ClanMember::find(Auth::user()->id)->clan()->with('clanMembers')->get();
From the above, I am getting the response correct.
"data": [
{
"id": 2,
"clan_leader_id": 3,
"clan_name": "#rockers1",
"clan_avatar": "",
"game_id": 1,
"max_members_count": 50,
"clan_id": "1505ccd15b01",
"created_at": "2019-05-04 04:31:44",
"updated_at": "2019-05-04 04:31:44",
"clan_leader_name": ""
"clan_members": [
{
"id": 2,
"user_id": 2,
"clan_id": "1505ccd15b01",
"role_id": 2,
"status": 0,
"created_at": "2019-05-04 04:33:03",
"updated_at": "2019-05-04 04:33:03"
}
]
}
]
Now I want to establish a relationship between the User and Clan model which has id and clan_leader_id as a foreign key to get clan_leader_name from User table in Clan model and user_name in place of user_id in clan_members. Clan member has user_id and id with the user as a foreign key.
Check out many-to-many relationships. Your models/tables should be: User, Clan, and ClanUser, where clan_user is an intermediate pivot table containing clan_id and user_id.
Your Clan model should contain the following relationship
public function users()
{
return $this->belongsToMany('App\User');
}
And your User model should contain the following relationship
public function clans()
{
return $this->belongsToMany('App\Clan');
}
To get a list of clans for a user:
$clans = User::find($userId)->clans()->get();
To get a list of users for a clan:
$users = Clan::find($id)->users()->get();

Storing Data using Laravel Helpers Arr::add() - Laravel 5.6

I am storing data in my controller like below
Controller
public function store(Request $request, $patient_id)
{
$auth = auth();
$patient_info = this->patient->store(Arr::add($request->all(),
'patient_id' => $patient_id, 'user_id' => $auth->id()));
dd($patient_info);
}
Model
class Patient extends Model
{
protected $fillable = ['name','patient_id','user_id'];
}
Results
"patient": {
"name": "Mohammed",
"patient_id": "1",
"updated_at": "2019-05-11 18:52:32",
"created_at": "2019-05-11 18:52:32",
"id": 1
}
The data is stored accurately in my database but without user_id as shown in the response. However, i have included user_id in the Arr:add(). What could i be doing wrong in my code please ?
PS: Beginner in laravel
Make sure you are logged in, otherwise $auth->id() will return null.
You can check if user is logged in with this helper auth()->check() which returns bool value.
Also make sure you have user_id column in your Patient table

Constraining a nested 3rd level relationship

I'm building an api using eager loading so i can simply return the user model with its deep relations and it automatically be converted as json. Here's the set up.
users
id
..
clients
id
..
user_clients
id
user_id
client_id
..
campaigns
id
..
client_campaigns
id
client_id
campaign_id
..
campaign_activities
id
campaign_id
..
client_campaign_activity_templates
id
campaign_activity_id
client_id *(templates are unique per client)*
..
I've setup the models' relationships.
User
public function clients() {
return $this->belongsToMany('App\Client','user_clients');
}
Client
public function campaigns() {
return $this->belongsToMany('App\Campaign','client_campaigns');
}
Campaign
public function activities() {
return $this->hasMany('App\CampaignActivity');
}
CampaignActivity
public function templates() {
return $this->hasMany('App\ClientCampaignActivityTemplate')
}
I have a simple api endpoint to provide a JSON of a User object including its deep relations using eager loading.
public function getLoggedInUser(Request $request) {
return \App\User::with('clients.campaigns.activities.templates')->find($request->user()->id);
}
Testing this using postman, I can get the user including its deep relations.
{
"user": {
"id": 1,
"name": "user1",
"clients": [
{
"id": 1,
"name": "client1",
"campaigns": [
{
"id": 1,
"name": "campaign1",
"activities": [
{
"id": 1,
"name": "activity1",
"templates": [
{
"id": 1,
"name": "template1 for client1",
"client_id": 1,
"body": "this is a template.",
}, {
"id": 2,
"name": "template1 for client2",
"client_id": 2,
"body": "This is a template for client2"
}
]
}, {
"id": 2,
"name": "activity2",
"templates": []
}, {
"id": 3,
"name": "activity3",
"templates": []
}
]
}
]
}
]
}
}
However, on the user->clients->campaigns->activities->templates level, it will list all the templates for that activity. I know based on the code of the relationships of the models above that it's supposed to behave like that.
So the question is How would you filter the templates to filter for both campaign_activity_id and client_id?
I've been experimenting on how to filter the templates so it will only list templates for that activity AND for that client as well. I have a working solution but it's N+1, I'd prefer eloquent approach if possible. I've been scouring with other questions, answers and comments for a closely similar problem, but I had no luck, hence I'm posting this one and seek for your thoughts. Thank you
I think what you need are eager loading constraints.
public function getLoggedInUser(Request $request) {
return \App\User::with('clients.campaigns.activities.templates',
function($query) use($request) {
$client_ids = Client::whereHas('users', function($q) use($request){
$q->where('id', $request->user()->id);
})->pluck('id');
$query->whereIn('templates.client_id', $client_ids);
})->find($request->user()->id);
}
Not tested but it should only require one additional query.
What I am doing is: define a constraint for your eager loading, namely only show those templates that have a client_id that is in the list (pluck) of Client IDs with a relation to the User.
Try using closures to filter through related models:
$users = App\User::with([
'clients' => function ($query) {
$query->where('id', $id);
},
'clients.campaigns' => function ($query) {
$query->where('id', $id);
}
])->get();
Here's my working solution, but I'm still interested if you guys have a better approach of doing this.
On the CampaignActivity model, I added a public property client_id and modified the relationship code to
CampaignActivity
public $client_id = 0
public function templates() {
return $this->hasMany('App\ClientCampaignActivityTemplate')->where('client_id', $this->client_id);
}
and on my controller, limit the eager loading to activities only (actually, there are more sqls executed using eager loading[9] in this case vs just iterating[7], and also eager loading doesn't make sense anymore because we're iterating lol)
public function getLoggedInUser(Request $request) {
foreach ($user->clients as $client)
foreach( $client->campaigns as $campaign)
foreach ($campaign->activities as $activity) {
$activity->client_id = $client->id;
$activity->templates; //to load the values
}
return $user;
}

Eager loading relationship returns empty using SELECT in WITH clause

Using Laravel 5.4, I have a query that correctly returns a relationship. Using the "with" clause in the query, I am attempting to return only selected columns from the relationship in my controller.
When I add the select to the with clause, relationship returns an empty array. Oddly enough, if I add a different parameter, such as a groupBy or join the query DOES return results. So something about my setup dislikes the select on the query.
Thus far I have tried:
using selectRaw
using select(DB::raw)
tried defining this as a separate relationship on my model.
Nothing has worked this far. Sql log looks good when I dump it.
Here is my model:
// MODEL
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
class ClassBlocks extends Model
{
public $timestamps = false;
public function schedule(){
return $this->hasMany('App\ClassSchedules', 'class_block_id', 'id');
}
}
And here is my controller:
//CONTROLLER
use App;
use DateTime;
use Illuminate\Http\Request;
class ProgramsController extends Controller
{
public function filterClass(Request $request, App\ClassBlocks $block)
{
$block = $block->newQuery();
// Attempt to eager load relationship
// Returns results when "select" disabled
$block->with([
'schedule' => function($query){
$query->select('time_start');
$query->groupBy('day');
},
]);
return $block->get();
}
}
Here is a sample result with select enabled (schedule returns empty):
[
{
"id": 13,
"program_id": "1",
"class_group_id": "1",
"schedule": [
]
}
]
And here is a result with select disabled (returns relationship when select disabled):
[
{
"id": 13,
"program_id": "1",
"class_group_id": "1",
"schedule": [
{
"id": 338,
"class_group_id": "1",
"program_id": "1",
"class_block_id": "13",
"date": "06/13/2017",
"day": "Tuesday",
"instructor_id": "1",
"time_start": "6:30am",
"time_end": "6:30am"
},
{
"id": 339,
"class_group_id": "1",
"program_id": "1",
"class_block_id": "13",
"date": "06/14/2017",
"day": "Wednesday",
"instructor_id": "2",
"time_start": "6:30am",
"time_end": "6:30am"
}
]
},
]
Any insight would be greatly appreciated.
The problem here is:
$query->select('time_start');
Laravel need to have column that is connection between 2 records. In this case you should probably use:
$query->select('time_start', 'class_block_id');
to make it work.
Obviously you will have class_block_id in response this way. If you really don't want it, probably you should create some transformer that will return exactly you want in response.

Resources