Support the ongoing development of Laravel.io →
Database Eloquent Forms
Last updated 2 years ago.
0

You can't use lists like this as these are separate queries. What is Friends model?

Last updated 2 years ago.
0

This is my Friends model:

<?php

class Friends extends Eloquent {

	/*public function getKey() {
		return $this->user->id;
	}

	public function __toString() {
		return $this->user->first_name . " " . $this->user->last_name;
	}*/

	public function User() {
		return $this->belongsTo('User', 'friend_id');
	}

}

I've done it like this now

$friends = Friends::select("friend_id")->whereUserId($user->id)->with(array("user" => function($query) {
	$query->select(DB::raw('concat (users.first_name," ",users.last_name) as full_name, users.id'));
}))->get();

foreach ($friends as $value)
	$f_list[$value->friend_id] = $value->user->full_name;
Last updated 2 years ago.
0

So the Friend model in fact reflects users table?

Last updated 2 years ago.
0

I have the Friends model to relate users to eachother to get a friends-function on my website. Is that not the way to do it?

These are the columns in the friends-table: id, user_id, friend_id, confirmed, created_at, updated_at, deleted_at

Last updated 2 years ago.
0

Then I would make it a Pivot model, and acces it like usually:

$user->friends->YourPivotModel;
$user->friends()->wherePivot();
...

Nevertheless you can achieve what you want in a couple of ways:

// work with Collection

// setup accessor on the User:
public function getFullNameAttribute()
{
  return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}


// then
$friendsList = $user->friends->lists('fullName', 'id');

Or concatenating fields in the query like this:

Friends   // work on friends table
   ->join('users','users.id','=','friends_table.user_id')  // join users table to..
   ->where('friends_table.user_id', $user->id)
   ->lists(DB::raw('concat(first_name," ",last_name)'), 'friend_id')  // ...concatenate its fields
Last updated 2 years ago.
0

Thank you very much for your help!

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.