【问题标题】:Laravel 5: Trying to get property of non-objectLaravel 5:试图获取非对象的属性
【发布时间】:2015-10-28 16:43:06
【问题描述】:

我明白了:

试图获取非对象的属性(查看:C:\xampp\htdocs\resources\views\posts.blade.php)

这些行有错误:

@if($post->id === Auth::user()->id)
<br><a href="#">Redaguoti</a>
@endif

所有代码:

@extends('layouts.main')
@section('content')
<div class="media">
  <div class="media-body" rel="#author{{ $topics->author_id }}">
    <h4 class="media-heading">{{ $topics->title }}</h4>
  </div>
    @foreach($posts as $post)
    <div class="media">
  <div class="media-left">
    <a href="{{ generateProfileURL($post->name, $post->id) }}">
      <img class="media-object" src="http://localhost/uploads/avatars/{{ $post->avatar_id }}.{{ $post->avatar_end }}" style="width: 64px">
    </a>
  </div>
  <div class="media-body" rel="#post{{ $post->pid }}">
  <a href="{{ generateProfileURL($post->name, $post->id) }}">{{ $post->name }}</a><br>{{ $post->text }}
  @if($post->id == Auth::user()->id)
  <br><a href="#">Edit</a>
  @endif
  </div>
</div>
@endforeach
</div>
{!! $posts->render() !!}
@stop

提前致谢;)

编辑那是因为我没有登录 :D

【问题讨论】:

  • $post 不是对象,或者用户没有登录,所以Auth::user() 返回 null。你能告诉我们你传递给$posts的视图吗?
  • @Ben 是的,我没有登录,谢谢 ;)
  • 好的,我把它作为答案发布了——谢谢!

标签: php laravel properties


【解决方案1】:

$post 不是对象,或者用户没有登录,所以Auth::user() 返回null

要消除错误,请先检查用户是否已登录,然后再运行该部分代码:

@if (Auth::check())

     // put auth-only code here

     @if($post->id === Auth::user()->id)
         <br><a href="#">Redaguoti</a>
     @endif

@endif

【讨论】:

  • 好的,非常感谢,我会在 10 分钟后标记为答案,因为现在我不能
【解决方案2】:

有几种情况会出现此错误,

  1. 当您的响应需要经过身份验证的用户才能访问时,可能是您的情况,并且
  2. 当您返回一个对象但您使用 foreach 或 forelse 作为数组访问它时。

您必须仔细检查您返回的数据以及相应的方法

【讨论】:

    猜你喜欢
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-22
    • 2017-03-20
    • 2014-03-25
    • 2015-01-25
    相关资源
    最近更新 更多