Cruzito Cruzito - 6 months ago 20
SQL Question

Laravel eloquent query right data

I am fairly new to laravel and eloquent.

I have 2 tables

threads
and
messages
you can see the structure in the links below:

threads

threads

messages

messages

Now my goals is to query only the threads from table threads that have the same user_id in the messages table as the logged in user .

Is there a way to do this via eloquent or do I have to write a query for this?

I currently get all the threads like this:

$thread = Thread::findOrFail($id);


But this gives security issues since you can go to any thread if you change the id in my route.

EDIT



My current show function:

public function show($id)
{
$currentUserId = Auth::user()->id;
$threads = Thread::forUser($currentUserId)->latest('updated_at')->get();

try {
$thread = Thread::findOrFail($id);
} catch (ModelNotFoundException $e) {
Session::flash('error_message', 'Oops, not found.');
return redirect('messages');
}


if(array_has($threads, $thread)){
$users = User::whereNotIn('id', $thread->participantsUserIds($currentUserId))->get();
$thread->markAsRead($currentUserId);
return view('messenger.show', compact('thread', 'users'));
}else{
Session::flash('error_message', 'Oops, not found.');
return redirect('messages');
}

}


I need a way to check if $thread is inside $threads.

Answer

If you want to use eloquent you must first define a relationship. One message belongs to a thread and a user. Here is how to define the relationships: Inside the Message model:

public function user()
{
   return $this->belongsTo('App/User'); //User model
}

public function thread()
{
  return $this->belongsTo('App/Thread'); //Thread model
}

To define the inverse you do the following: Inside User model:

public function threads()
{
  return $this->hasMany('App/Thread');
}

Inside the Thread model:

public function messages()
{
   return $this->hasMany('App/Message');
}

Now you can do the following in your controller:

$threads = Auth::user()->threads;

Now you have all threads by the currently logged in user. I am not sure if I got the question right so ask away.

Edit: You could check like so:

$thread = Thread::find($id);
$isCurrentUserThread = false;
foreach(Auth::user()->threads as $currentUserThread) {
   if($currentUserThread->id == $thread->id) {
       $isCurrentUserThread = true;
      //$thread belongs to the current user
   }
}

if($isCurrentUserThread) {
    //the thread belongs to the current user
} else {
   //it doesn't belong to the current user
}