jc1992
jc1992

Reputation: 644

How to save multidimensional array in Laravel

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 ?

Upvotes: 0

Views: 962

Answers (1)

manix
manix

Reputation: 14747

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();

Upvotes: 1

Related Questions