mercredi 31 juillet 2019

How to use Eloquent to retrieve data from two different tables

I'm setting up a system to check if the user has sent a message to another user.

MessagesController.php

use App\Message;
use App\User;

class MessagesController extends Controller
{
    public function index()
    {
        return view('admin.messages')->with('messages', Message::all())
                                     ->with('users', User::all());

    }

The message migration has following data:

Schema::create('messages', function (Blueprint $table) {
    $table->increments('id');
            $table->integer('from');
            $table->integer('to');
            $table->mediumText('text');
            $table->integer('status');
            $table->timestamps();
});


And the web.php

Route::get('/admin/messages', [
        'uses' => 'MessagesController@index',
        'as' => 'messages'
    ]);


So the idea is to present a panel with the data of messages, showing:

<tbody>
    <tr>
        @foreach ($messages as $message)

        <td>
            
        </td>
        <td>
            
        </td>
        <td>
            
        </td>
        <td>
            
        </td>
        <td>
            
        </td>

        @endforeach
    </tr>
</tbody>


This loads correctly all the information on the Message table. However, it will display the 'from' and 'to' as and ID, as it should.

I expect to have the table populated with not the ID of the user, but the Name of the user, via a relationship between the Message table and the Users table.

What am I missing?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire