【问题标题】:Trying to get property of non-object Error i like试图获取我喜欢的非对象错误的属性
【发布时间】:2016-05-31 16:01:19
【问题描述】:

所以这就是我这样做时的问题:

<p>{{ $event->media }}</p>

我明白了:

{"id":43,"location":"\/assets\/img\/space-4k.png","description":"Space","image_album_id":1277165568,"featured":null,"thumbnail":null,"isVisible":1}

然后我想要这个位置,所以我这样做:

<p>{{ $event->media->location }}</p>

然后我得到这个不错的 Trying to get property of non-object 错误。

我将它用于另一个对象并做了同样的事情并且它有效..所以我找不到它为什么不起作用..

我的事件模型:

<?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use DB;

    class Event extends Model
    {
    protected $table = "events";
    public $timestamps = false;

   public function albums()
   {
        return $this->belongsToMany('App\Album', 'events_has_image_albums', 'events_id', 'image_albums_id');
   }

    public function viewableAlbums()
    {
        return $this->belongsToMany('App\Album', 'events_has_image_albums', 'events_id', 'image_albums_id')
        ->whereExists(function($query)
        {
            $query->select(DB::raw(1))
                ->from("images")
                ->whereRaw('images.image_album_id = image_albums.id')
                ->where('isVisible', '=' , '1');
        })
        ->with('FirstMedia');
    }

    public function images()
    {
        return $this->belongsToMany('App\Media', 'events_has_images',    'events_id', 'images_id');
    }

    // this is the media function from the $event->media
    public function media()
    {
      return $this->belongsTo('App\Media', 'header');
    }
}

【问题讨论】:

  • 我会继续猜测 $event->media 是 JSON 字符串而不是对象。 print_r($event-&gt;media) 说什么?
  • 欢迎来到 Stack Overflow!为了使您的问题更易于阅读,请format your code and error output,特别是在每个代码/输出行前加上 4 个空格。此外,查看更多代码会很有帮助,最好是MCVE。一种猜测:$event 是在循环中定义的吗? (例如@foreach ($events as $event)
  • 是的 $event 来自 @foreach 循环

标签: php laravel-5.2 laravel-blade


【解决方案1】:

你有一个 JSON Obect,所以你需要像这样解码它:

     <?php $objDecoded  = json_decode($event->media); ?>
     <?php $strLocation = $objDecoded->location; ?>
     <?php var_dump($objDecoded); exit; // TRY TO DUMP THE DECODED DATA TO SEE WHAT YOU GET... ?>

     <p>{{ $strLocation }}</p>

【讨论】:

  • ErrorException in 79487d15e7f32bf64b98bc29e6d7b892a687253e.php 第 8 行:试图获取非对象的属性(查看:C:\xampp\htdocs\WWO_SOJ\resources\views\events.blade.php)
【解决方案2】:

这样使用

<p>{{ $event->media['location'] }}</p>

【讨论】:

    猜你喜欢
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 2016-06-13
    • 2018-06-02
    • 2017-08-20
    相关资源
    最近更新 更多