Search code examples
laraveleloquentlaravel-7eloquent-relationship

Understanding Eloquent One-to-many Relationships


I'm trying to understand Eloquent relationships but it seems I'm missing something in understanding it. I have:

  • A Meeting produces many Documents.
  • A specific Document can be produced for one Meeting.

Thus a one to many relationship. I am trying to display the 'meeting_name' in the Document details table but get this error:

Trying to get property 'meeting_name' of non-object (View: C:\wamp64\www\yajra_contact_system\resources\views\documents\index.blade.php)

Here is my code.

Please please explain with code solution:

app\Document.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Document extends Model
{
    protected $fillable = [
        'document_name',
        'document_desc',
    ];

    public function meeting(){
        return $this->belongsTo(Meeting::class);
    }
}

app\Meeting.php File:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Meeting extends Model
{
    protected $fillable = [
        'document_id',
        'meeting_name',
        'meeting_desc',
        'room_no',
        'no_of_invitees',
        'comments'
    ];

    public function documents(){
        return $this->hasMany(Document::class);
    }
}

app\Http\Controllers\DocumentsController.php File:

namespace App\Http\Controllers;

use App\Document;
use App\Meeting;
use Illuminate\Http\Request;

class DocumentsController extends Controller
{
    public function index()
    {
        $documents =  Document::all();
        $meetings = Meeting::all();        

        return view('documents.index', compact('documents', 'meetings'));
    }
}

resources\views\documents\index.blade.php File:

@foreach($documents as $document)
    <tr>
        <td>{{$document->id}}</td>
        <td>{{$document->document_name}}</td>
        <td>{{$document->document_desc}}</td>
        <td>{{$document->meetings->meeting_name}}</td> <!-- ERROR IS HERE -->
    </tr>
@endforeach

Solution

  • So you have your tables mixed up.

    You have a single record per meeting yet you have a document_id in your meetings table which you would need to duplicate meeting record for each document.

    Remove the document_id from your meetings table

    Add a meeting_id to your documents table

    remember to update your models fallible array else you wont get the new columns in the collection.

    This should fix your problem as your relationships are correct.