mafortis
mafortis

Reputation: 7128

Laravel exclude current user from array

Logic

  1. I have store function and it's returning data of users in the group.
  2. The person who saves this data is also included of group users.
  3. Now I want to exclude s/he from group users when data returns.

code

I've commented the code so you can understand it better.

public function store(Request $request)
{
    $user = $request->user(); // current user who should be excluded
    $group = Group::where('id', $request->input('group_id'))->first();
    $message = new GroupMessage;
    $message->group_id = $request->input('group_id');
    $message->user_id = $user->id;
    $message->note = $request->input('newMessage');
    $message->message_id = $request->input('message_id');
    $message->save();


    // returning data
    // 'user' is current user (also available in 'group.users')
    // remove current 'user' from ('group.users')
    $ms = GroupMessage::where('id', $message->id)->with(['user', 'group', 'group.users'])->first();
    return response()->json([
        'data' => new NotesResource($ms),
        'message' => 'Message sent successfully.'
    ], 200);
    Log::info('message data sent.');

    broadcast(new MessageSent($message))->toOthers();
}

Screenshot

here is how code above returns data

one

Any idea?

Upvotes: 0

Views: 177

Answers (1)

lagbox
lagbox

Reputation: 50491

You can exclude this User using Eager Loading Constraints:

$ms = GroupMessage::where('id', $message->id)
    ->with(['user', 'group.users' => function ($query) use ($user) {
        $query->where('users.id', '<>', $user->id);
    }])->first();

Laravel 7.x Docs - Eloquent - Relationships - Constraining Eager Loads

Upvotes: 2

Related Questions