1
votes

I have a business table which is linked using eloquent with table addresses, location and gallery. Output looks like this:

Collection {#266 ▼
  #items: array:1 [▼
    0 => Business {#260 ▼
      #table: "businesses"
      +timestamps: true
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:14 [▶]
      #original: array:14 [▶]
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: array:3 [▼
        "addresses" => Collection {#261 ▼
          #items: array:1 [▼
            0 => Address {#263 ▼
              #table: "addresses"
              +timestamps: true
              #connection: "mysql"
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #with: []
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:9 [▼
                "id" => 10
                "firstline_address" => "96"
                "secondline_address" => "Cambridge Street"
                "town" => "[email protected]"
                "city" => "[email protected]"
                "postcode" => "SK15 1AU"
                "telephone" => "7815522481"
                "created_at" => "2017-06-26 08:05:32"
                "updated_at" => "2017-06-26 08:05:32"
              ]
              #original: array:11 [▶]
              #casts: []
              #dates: []
              #dateFormat: null
              #appends: []
              #events: []
              #observables: []
              #relations: array:1 [▼
                "pivot" => Pivot {#262 ▶}
              ]
              #touches: []
              #hidden: []
              #visible: []
              #fillable: []
              #guarded: array:1 [▶]
            }
          ]
        }
        "location" => Location {#279 ▶}
        "gallery" => null
      ]

However the problem is that is says:

Property [addresses] does not exist on this collection instance. (View: C:\xampp\htdocs\laravel\resources\views\displayBusiness.blade.php)

here's my view:

        @foreach($business->addresses as $address)
        <p>{{$address->firstline_address}}</p>
        <p>{{$address->secondline_address}}</p>
        <p>{{$address->town}}</p>
        <p>{{$address->city}}</p>
        <p>{{$address->postcode}}</p>
        <p>{{$address->telephone}}</p>
        @endforeach
    </div>

Model:

class Business extends Model 
{

    protected $table = 'businesses';
    public $timestamps = true;

    use Searchable;

    public function addresses()
    {
        return $this->belongsToMany('App\Address', 'business_address', 'business_id', 'address_id');
    }
    public function gallery()
    {
        return $this->hasOne('App\Gallery', 'business_id');
    }
    public function film()
    {
       return $this->hasOne('App\Film', 'business_id');
    }
    public function location()
    {
        return $this->hasOne('App\Location', 'business_id');
    }
    public function user()
    {
        return $this->hasMany('App\User', 'user_business', 'business_id', 'user_id');
    }

Another problem is that sometimes a field is empty so let's say sometimes $address->city = null how would I tell to ignore that field and carry on?

I can do @if($address->city == NULL) but I don't want to do it for each one as I cannot predict what will be empty.

//edit

Controller:

   public function displayBusiness($id) {

                $business = Business::where('id', $id)
                        ->with('addresses')
                        ->with('location')
                        ->with('gallery')
                        ->get();       
                        //dd($business);
                        /*
        $instagram = $business->instagram_business;
        $twitter = $business->twitter_business;
        $instagramItems=[];
        $twitterItems=[];
        if(!empty ($instagram)){
        $client = new \GuzzleHttp\Client();
        $url =  sprintf('https://www.instagram.com/'.$instagram.'/media');
        $response = $client->get($url);
        $instagramItems = json_decode((string) $response->getBody(), true)['items'];
        $twitterItems = Twitter::getUserTimeline(['screen_name' => $twitter, 'count' => 10, 'format' => 'array']);
        */
        //$session = session()->put('key', $id);
        //$gallery = Gallery::where('business_id', $id)->get();
        //$location = Location::where('business_id', $id)->get();
        //$review = Review::where('business_id', $id)->get();
            return view('business.displayBusiness', compact('business', 'address', 'gallery', 'location', 'review', 'instagramItems', 'twitterItems'));
        /*}

//edit2

It now says

Trying to get property of non-object (View: C:\xampp\htdocs\laravel\resources\views\business\displayBusiness.blade.php)

Which is:

                        @foreach ($business->location as $marker)
                            <script>
                        var map = new google.maps.Map(document.getElementById('map'), {
                        zoom: 19,
                        center: {lat: {{$marker->latitude}}, lng: {{$marker->longitude}}}
                         });
2
Please show your controller code.AddWeb Solution Pvt Ltd
sorry forgot about it :(Przemek Wojtas

2 Answers

5
votes

It looks like you need to change

$business = Business::where('id', $id)
                    ->with('addresses')
                    ->with('location')
                    ->with('gallery')
                    ->get();

to

$business = Business::where('id', $id)
                    ->with('addresses')
                    ->with('location')
                    ->with('gallery')
                    ->first();

Your problem is that your query is returning a Collection rather than a single instance of Business, this is because your query is searching for multiple businesses and will generate a Collection of any businesses it finds, even if there is just one.

0
votes

Better to use has()

$business = Business::where('id', $id) ->has('addresses') ->has('location') ->has('gallery') ->get();

Querying Relationship Existence https://laravel.com/docs/5.7/eloquent-relationships#querying-relations