My problem: I can't seem to use where('user_id', '<>', Auth::id()
on a relationship collection using Laravel's Eloquent ORM.
In Laravel 5, I have a database with the following schema:
| USERS | JOBS | CONVERSATIONS | MESSAGES | CONVERSATION_USER |
| id | id | id | id | conversation_id |
| username | user_id | job_id | conversation_id | user_id |
| password | title | | user_id | |
| | | | message | |
and with the following relationships:
User model:
$jobs = $this->hasMany('job');
$messages = $this->hasMany('message');
$conversations = $this->belongsToMany('conversation');
Job model:
$user = $this->belongsTo('user');
$conversations = $this->hasMany('conversation');
$messages = $this->hasManyThrough('message', 'conversation');
Conversation model:
$job = $this->belongsTo('job');
$messages = $this->hasMany('message');
$user = $this->belongsToMany('user');
Message model:
$user = $this->belongsTo('user');
$conversation = $this->belongsTo('conversation');
I'm trying to get the number of messages for a job, which have not been posted by the authenticated user. My code is:
// Load all of the jobs which relate to the logged in user
$jobs = Job::with(['messages'])->where('user_id', Auth::id())->OrderBy('id', 'DESC')->get();
foreach ($jobs as $job)
{
// Count all messages that have not been sent by the logged in user
echo $job->messages->where('user_id', '<>', Auth::id())->count().'<br />';
}
However I just cannot get the count function to work.