MichalGrab
MichalGrab

Reputation: 57

How to display data from db to view in Laravel 8.*

I would like to return data from db to view. It works perfectly when I'm trying to get data from main table, but whenever I'm trying to take data from other table which got foreign key in that table, it comes back with error

Attempt to read property "name" on null (View: C:\xampp\htdocs\Laravel1\resources\views\frontend\object.blade.php) 

FrontendController

 public function object($id)
    {
        $object = $this->fR->getObject($id);
        //dd($objects);
        return view('frontend.object',['object'=>$object]);
    }

FrontendRepository

public function getObject($id)
    {
        return EventObject::find($id);
        return EventObject::with(['clubs'])->get();
    }

EventObject Model(which actually works for main table only)

class EventObject extends Model
{
    protected $table = 'events';
/*
    public function city()
    {
        return $this->belongsTo('App\Models\City');
    }
    */

    public function clubs()
    {
        return $this->belongsTo('App\Models\Club');
    }
}

Club Model

class Club extends Model
{
    protected $table= 'clubs';


    public function cities()
    {
        return $this->belongsTo('App\Models\City');
    }
}

object.blade view in which I'm trying to display data

@extends('layouts.frontend')

@section('content')
<div class="container-fluid places">


    <h1 class="text-center">{{ $object->name }} event name <small>city name</small></h1>
    <h3 class="text-center"> {{$object->clubs->name}}club name</h3>

    <p>{{$object->content}}</p>
    @endsection

Upvotes: 0

Views: 1051

Answers (1)

Pradeep
Pradeep

Reputation: 9717

You r returning twice in your getObject method that is why its not reaching the second statement . It should be like this

public function getObject($id)
{
    return EventObject::with(['clubs'])->find($id); //better use findOrfail($id)
}

https://laravel.com/docs/8.x/eloquent-relationships#eager-loading

Upvotes: 2

Related Questions