I think this will work for you, if this is not what you want we need to see some more code ;)
// You only need to pass an array with ids here
$status = Status::whereIn('posted_status_user_id', [4, 5, 7])->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
So I have two tables : Status & follow_user Status table has: id posted_status_user_id status_content created_at
Follow_user has : id following_from_user_id following_to_user_id
I have no problem of displaying all statuses but I want only statuses of following users. For eg. If i'm following 10 people then I want to display only their statuses.
How to setup relationship and Eloquent query ?
Thanks!
I think this will work for you, if this is not what you want we need to see some more code ;)
// You only need to pass an array with ids here
$status = Status::whereIn('posted_status_user_id', [4, 5, 7])->get();
@bobbybouwmann Okay! Do I need to provide hasMany Relationships ?
Not sure as to the purpose of your application, so this answer may not suit your requirements. I'd have 3 tables and 2 models.
User | Status
Tables Users, Statuses, Follows
You'd have a method in Users
public function following()
{
return $this->belongsToMany('App\User', 'follows');
}
Then through eloquent you'd be able to do
$status = Auth::user->following()->with('statuses');
Or, a hasManyThrough might solve your problem.
@taijuten : Thanks :)
I think you forgot to add users has many statuses.
The status holds the user id right? Then my code should be fine!
If you tell us some more on your needs and how you want to display stuff we can help you get the correct code ;)
@bobbybouwmann You are right. But the thing is how do I get follwed user id's? For example: My user id is : 5 and Im following users having ids 1,2,3,4 So the data in the table would be : 5->1 5->2 5->3 5->4 How can I pass 1,2,3,4 and so on?
I think you first need to setup your relations and show them to us ;) I can throw some code to you, but that's not going to help you
@bobbybouwmann Frankly speaking, I'm very poor at creating relations, It will be better if you teach me :)
Just give it a try yourself ;) You will learn more from your mistakes then from copying ;)
Laracasts has a good series on relations as well: https://laracasts.com/series/digging-in/episodes/3
You can also find all the information in the documentation: http://laravel.com/docs/5.0/eloquent#relationships
@abhishek009 Try to think of your models in terms of "Resources" that your site deals with.
In the below examples, every word I put in bold would be a model.
e.g. "My site lets car dealers advertise their cars to people within their state.
Relations: State->hasMany->Dealers->hasMany->cars
"My site lets Users post status updates to their followers
Relations: User->hasMany->Statuses User->hasMany->Followers
@taijuten Wow ! Great explanation! :) Now, How do I relate 2 tables that are statuses and followers. I have user's id using Auth::user()->id. I successfully displayed the the user which I followed. Now, I want to display statuses of the users I followed. But don't know how do I relate 2 tables. :(
The statuses and followers wouldn't have a direct relation.
Think about how you're asking for this information. "I want to display statuses of the users I followed"
So there has to be some link from the User to the Users that they follow. This is a many to many relationship, since a user can follow many users, and be followed by many users.
I'd create a table called "Follows"
user_id | follows_id
Then on your user model
public function following() {
return $this->belongsToMany('App\User', 'follows', 'user_id', 'follows_id');
}
public function followers() {
return $this->belongsToMany('App\User', 'follows', 'follows_id', 'user_id');
}
public function statuses() {
return $this->hasMany('App\Status');
}
now doing
User::find(1)->following()
will give you all the users that User 1 is following. If you have your status relationship also working, you can extend upon this to give you.
User::find(1)->following()->with('statuses');
This will give you the users that User 1 follows, and their statuses
See I have 3 tables :
users | statuses | following
Users table has id field. Statuses table has following fields :
uid | status
Following table has below fields :
following_from_id | following_to_id
As you said but you have not given any relation with statuses and following table.
There is no relation between statuses and following.
It's User and status, and User and User (following). These are two separate relationships.
What you want to do is get the Users the User is following
User::find(x)->following();
And include those user's statuses.
User::find(x)->following()->with('statuses');
It says "Call to a member function following() on null"
Have you set the relationship as I described above?
In your user model
public function following() {
return $this->belongsToMany('App\User', 'following', 'following_from_id', 'following_to_id');
}
public function followers() {
return $this->belongsToMany('App\User', 'following', 'following_to_id', 'following_from_id');
}
public function statuses() {
return $this->hasMany('App\Status');
}
Yes sir. I have done everything as you said. My tables look like :
Statuses:
Schema::create('statuses', function(Blueprint $table)
{
$table->increments('id');
$table->integer('uid')->unsigned();
$table->string('status');
$table->timestamps();
$table->foreign('uid')->references('id')->on('users')->onDelete('cascade');
});
followings :
Schema::create('following', function(Blueprint $table)
{
$table->increments('id');
$table->integer('following_from_id')->unsigned();
$table->integer('following_to_id')->unsigned();
$table->timestamps();
$table->foreign('following_from_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('following_to_id')->references('id')->on('users')->onDelete('cascade');
});
Users :
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('username');
$table->string('month');
$table->integer('day');
$table->integer('year');
$table->integer('image');
$table->string('gender');
$table->string('place');
$table->string('last_name');
$table->timestamp('last_login');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
Can you show your User model?
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name','username','month','day','year','gender','place','last_login','last_name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password', 'remember_token'];
/*
* One to Many relationShip
*/
public function following() {
return $this->belongsToMany('App\User', 'following', 'following_from_id', 'following_to_id');
}
public function followers() {
return $this->belongsToMany('App\User', 'following', 'following_to_id', 'following_from_id');
}
public function statuses() {
return $this->hasMany('App\statuses');
}
public function articles()
{
return $this->hasMany('App\Article');
}
public function comments()
{
return $this->hasMany('App\Comments');
}
}
What that error means is that the first part doesn't have a user found.
so in this code
User::find(x)->following()->with('statuses');
You'd need to make the first part the user. So either X would be the user's id, or if it relates to the logged in user you could do
Auth::user()->following()->with('statuses');
It's doesn't show anything.
public function index()
{
$status = Auth::user()->following()->with('statuses');
return view('home',compact('status'));
}
In blade :
@foreach($status as $get)
{{ $get->status }}
@endforeach
If you ever need to troubleshoot an eloquent relationship, do a
dd($status);
to work out the issue. First do
dd(Auth::user());
to ensure that you have a successfully logged in user
Then do
dd(Auth::user()->following());
To ensure the relationship is working, and so on.
One bit that I should have mentioned though, is that you're going to need to use
->get()
to get the results of the eloquent query. So...
$status = Auth::user()->following()->with('statuses')->get();
okay. Now it says :
QueryException in Connection.php line 624:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'statuses.user_id' in 'where clause' (SQL: select * from `statuses` where `statuses`.`user_id` in (2, 3))
When you do a relationship with Eloquent, it follows several naming conventions.
This relationship:
public function statuses() {
return $this->hasMany('App\statuses');
}
makes the assumption that the statuses record will have a user_id column, since the current model is "User".
However, you can override this behaviour if you've chosen another column name, by doing the following:
public function statuses() {
return $this->hasMany('App\statuses', 'uid');
}
Yes ! I have added it but still I didn't get output.
The thing I can only get is id's I can't get any other fields.
public function index()
{
$status = Auth::user()->following()->with('statuses')->get();
return view('home',compact('status'));
}
It returns ID
@foreach($status as $get)
{{ $get->id }}
@endforeach
But When I try to get status :
@foreach($status as $get)
{{ $get->status }}
@endforeach
It doesn't work!
When you do a
dd($status);
does it return the data you expect? Doing this should show you the structure of the data so you can output it.
The way that this query is done, is that it gets all the followed users, and their statuses, so it will be "grouped by" the user.
If you just want the statuses without being grouped by the user, you'll have to use hasManyThrough - http://laravel.com/docs/5.0/eloquent#has-many-through
Collection {#210 ▼
#items: array:2 [▼
0 => User {#202 ▼
#table: "users"
#fillable: array:11 [▼
0 => "name"
1 => "username"
2 => "month"
3 => "day"
4 => "year"
5 => "gender"
6 => "place"
7 => "last_login"
8 => "last_name"
9 => "email"
10 => "password"
]
#hidden: array:2 [▼
0 => "password"
1 => "remember_token"
]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:16 [▼
"id" => 2
"name" => "Admin"
"username" => "Admin"
"month" => "1"
"day" => 1
"year" => 1994
"image" => 0
"gender" => "male"
"place" => "India"
"last_name" => "Admin"
"last_login" => "0000-00-00 00:00:00"
"email" => "admin@admin.com"
"password" => "$2y$10$qTuW3YU4yjf6.n6ZCCw60O9ubC.PP32PXwlde9uj19VMv7Rlv5wyi"
"remember_token" => null
"created_at" => "2015-05-03 17:04:17"
"updated_at" => "2015-05-03 17:04:17"
]
#original: array:18 [▼
"id" => 2
"name" => "Admin"
"username" => "Admin"
"month" => "1"
"day" => 1
"year" => 1994
"image" => 0
"gender" => "male"
"place" => "India"
"last_name" => "Admin"
"last_login" => "0000-00-00 00:00:00"
"email" => "admin@admin.com"
"password" => "$2y$10$qTuW3YU4yjf6.n6ZCCw60O9ubC.PP32PXwlde9uj19VMv7Rlv5wyi"
"remember_token" => null
"created_at" => "2015-05-03 17:04:17"
"updated_at" => "2015-05-03 17:04:17"
"pivot_following_from_id" => 1
"pivot_following_to_id" => 2
]
#relations: array:2 [▼
"pivot" => Pivot {#201 ▼
#parent: User {#197 ▶}
#foreignKey: "following_from_id"
#otherKey: "following_to_id"
#guarded: []
#connection: null
#table: "following"
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: false
#attributes: array:2 [▶]
#original: array:2 [▶]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
"statuses" => Collection {#208 ▼
#items: array:1 [▼
0 => statuses {#211 ▼
#table: "statuses"
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:5 [▼
"id" => 1
"uid" => 2
"status" => "Hey ya!"
"created_at" => "2015-05-03 17:06:31"
"updated_at" => "2015-05-03 17:06:31"
]
#original: array:5 [▼
"id" => 1
"uid" => 2
"status" => "Hey ya!"
"created_at" => "2015-05-03 17:06:31"
"updated_at" => "2015-05-03 17:06:31"
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]
}
]
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
1 => User {#203 ▼
#table: "users"
#fillable: array:11 [▼
0 => "name"
1 => "username"
2 => "month"
3 => "day"
4 => "year"
5 => "gender"
6 => "place"
7 => "last_login"
8 => "last_name"
9 => "email"
10 => "password"
]
#hidden: array:2 [▼
0 => "password"
1 => "remember_token"
]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:16 [▼
"id" => 3
"name" => "john"
"username" => "John"
"month" => "1"
"day" => 1
"year" => 1994
"image" => 0
"gender" => "male"
"place" => "United States"
"last_name" => "doe"
"last_login" => "0000-00-00 00:00:00"
"email" => "john@doe.com"
"password" => "$2y$10$6ogFDFE/o6J491/eum1xQuF1111Lz7q5nakQR8tOz5ys8qH3eQ77a"
"remember_token" => null
"created_at" => "2015-05-03 17:20:08"
"updated_at" => "2015-05-03 17:20:08"
]
#original: array:18 [▼
"id" => 3
"name" => "john"
"username" => "John"
"month" => "1"
"day" => 1
"year" => 1994
"image" => 0
"gender" => "male"
"place" => "United States"
"last_name" => "doe"
"last_login" => "0000-00-00 00:00:00"
"email" => "john@doe.com"
"password" => "$2y$10$6ogFDFE/o6J491/eum1xQuF1111Lz7q5nakQR8tOz5ys8qH3eQ77a"
"remember_token" => null
"created_at" => "2015-05-03 17:20:08"
"updated_at" => "2015-05-03 17:20:08"
"pivot_following_from_id" => 1
"pivot_following_to_id" => 3
]
#relations: array:2 [▼
"pivot" => Pivot {#200 ▼
#parent: User {#197 ▼
#table: "users"
#fillable: array:11 [▼
0 => "name"
1 => "username"
2 => "month"
3 => "day"
4 => "year"
5 => "gender"
6 => "place"
7 => "last_login"
8 => "last_name"
9 => "email"
10 => "password"
]
#hidden: array:2 [▼
0 => "password"
1 => "remember_token"
]
#connection: null
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: true
#attributes: array:16 [▶]
#original: array:16 [▶]
#relations: []
#visible: []
#appends: []
#guarded: array:1 [▶]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
#foreignKey: "following_from_id"
#otherKey: "following_to_id"
#guarded: []
#connection: null
#table: "following"
#primaryKey: "id"
#perPage: 15
+incrementing: true
+timestamps: false
#attributes: array:2 [▼
"following_from_id" => 1
"following_to_id" => 3
]
#original: array:2 [▼
"following_from_id" => 1
"following_to_id" => 3
]
#relations: []
#hidden: []
#visible: []
#appends: []
#fillable: []
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
"statuses" => Collection {#207 ▼
#items: []
}
]
#visible: []
#appends: []
#guarded: array:1 [▼
0 => "*"
]
#dates: []
#casts: []
#touches: []
#observables: []
#with: []
#morphClass: null
+exists: true
}
]
}
Yes, so this has returned the user that is followed, and their statuses.
So your foreach would be per user.
foreach($users as $user)
@foreach($user->statuses as $status)
{{ $status->status }}
@endforeach
@endforeach
As mentioned above, if you don't want to go through each user, and just want a list of all the statuses, you'd use hasManyThrough http://laravel.com/docs/5.0/eloquent#has-many-through
Thank you so much man ! You helped me a lot :)
Can you tell me the best way to learn queries and relationships ?
No problem. The best way? Keep trying them!
Also, the docs are a great use. http://laravel.com/docs/5.0/eloquent
Please or to participate in this conversation.