laravelrelationshiplaravel-bladebelongs-to

Laravel BelongsTo confusion


I have an OneToMany relation between EVENT and MAJOR model as following's schema :

EVENT belongs to Major and Major HasMany Events

Here is my tables in MySQl

EVENTS Table :

   id   name          major_id  
    1   liga 1st          1     
    2   liga 2nd          2     

Majors Table :

id  symbol                 name     
1   MTB           xxxxxxxxxxxxxxxxxxxxxxxx  
2   ROAD          yyyyyyyyyyyyyyyyyyyyyyyy  
3   TRACK         zzzzzzzzzzzzzzzzzzzzzzzz

in controller I passed all event's data to the view as following:

 $events= Event::all();

and in my view I could not reach majors table based on relation :

   @foreach($events as $event)
     <option value="">{{$event->major->name }}</option>
    @endforeach

But I tried with this code and it works :

   @foreach($data as $event)
    <option value="">{{$event->major()->first()->name }}</option>
   @endforeach

my question is if each event have one Major_id why shouldn't I utilize the first query that I noted above.


Solution

  • After 24H I finally found the ridicules problem !

    I'd assigned a getMajorAttribute() in my model and it was processing the output data ! thanks