belongsTo error in AppServiceProvider

0

I have an error in the belongsTo relationship in the welcome view, the error is the following:

"Undefined property: stdClass::$work (View: ...\views\welcome.blade.php)"

I recover the data from the query made in AppServiceProvider since it is common in many views, the funny thing is that the CRUD index for the management works correctly.

AppServiceProvider

public function boot()
{

    Schema::defaultStringLength(191);

    // Cargo en todas las vistas el menu
    $workData = \DB::select('SELECT * FROM works');
    $eventData = \DB::select('SELECT * FROM events');

    View::share('dynamicWorks', $workData);
    View::share('dynamicEvents', $eventData);

}

Work model and Event with relationships

public function events()
{
    return $this->hasMany('App\Event', 'work_id');
}

public function work()
{
    return $this->belongsTo('App\Work', 'work_id');
}

View that does not work

@foreach($dynamicEvents as $event)
<h4 class="media-heading">{{$event->work->title}}
    <small><i>{{$event->date}} a las {{$event->time}}</i></small>
</h4>@endforeach

Driver that returns the view that works

public function index()
{
    $events = Event::paginate(15);
    return view('events.index', compact('events'));
}

View if it works

@foreach($events as $event)
<tr>
    <td>{{$event->work->title}}</td>
</tr>@endforeach
    
asked by Maurikius 26.11.2017 в 21:34
source

2 answers

1

The second view works because you are sending an object and you treat it as such:

$event->work->title

The first one does not work because it is not receiving an object, but an array, and you are treating it as an object:

$event->work->title

To solve it you have two ways: Change the query in AppServiceProvider and leave it as in the Controller. Or, change the logic in the view and treat $ even as an array.

    
answered by 28.11.2017 / 13:04
source
1

That's how it works correctly

public function boot()
{
    Schema::defaultStringLength(191);
    $data = Work::all();
    $data2 = Event::all();
    View::share('globalWorks', $data);
    View::share('globalEvents', $data2);
}
    
answered by 28.11.2017 в 14:30