0

Good afternoon !

I am creating a private chat , and I get the first objective , get the message and users with the following code.

public function getEnviarMensajes($id,$identificador){
        $user = User::find($identificador);
        $idReceptor =  $user->id;
        $idEmisor = Auth::user()->id;

        $mesageuser = MessageUser::with('user')->with('message')->get();
        $name = [];
        $content = [];
        foreach($mesageuser as $users){
            foreach($users->message as $mensajes){
                if($users->user->id==$idEmisor){

                $name[] = $users->user->name;
                echo "<p>";
                $content[] = $mensajes->contenido;
                echo "<p>";
                echo $mensajes->created_at;
                echo "<p>";

                }
                if($users->user->id==$idReceptor){

                $name[] = $users->user->name;
                echo "<p>";
                $content[] = $mensajes->contenido;
                echo "<p>";
                echo $mensajes->created_at;
                echo "<p>";
                }
            }

        }

However , I have a problem , this results i need to "join" , in many ocasions I used an array , but in this case ? How I can save differents rows in Laravel ? , also I need to sort this content for datetime row.

Could anyone helps to me ?

1 Answer 1

1

I think you can cut your code at this way:

$mesageuser = MessageUser::with('user')->with('message')->get();
$messages = [];

foreach($mesageuser as $users){
    foreach($users->message as $mensajes){
        $messages[] = [
            'nombre' => $users->user->name,
            'contenido' => $mensajes->contenido,
            'creado' => $mensajes->created_at,
            'emisor' => ($users->user->id==$idEmisor) // true or false
        ];
    }
}

return view('chat', ['messages' => $messages]);

The two if statements are useless because inside of them the code is the same. And I had used an multidimensional array in order to store all the messages with the following structure:

[
    [
        'nombre' => 'Marta',
        'contenido' => 'Hola',
        'creado' => '24/03/2015',
        'emisor' => false
    ],
    [
        'nombre' => 'Salomé',
        'contenido' => 'adiós',
        'creado' => '24/03/2015',
        'emisor' => true
    ]
]

If you want, for example, order by date, then edit your query:

$mesageuser = MessageUser::with('user')->with(['message' => function($query){
    $query->orderBy('created_at', 'desc');
}])->get();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.