Laravel 5:尝试获取非对象的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31840427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 5: Trying to get property of non-object
提问by Evaldas L.
I'm get:
我得到:
Trying to get property of non-object (View: C:\xampp\htdocs\resources\views\posts.blade.php)
试图获取非对象的属性(视图:C:\xampp\htdocs\resources\views\posts.blade.php)
Error in these lines:
这些行中的错误:
@if($post->id === Auth::user()->id)
<br><a href="#">Redaguoti</a>
@endif
All code:
所有代码:
@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
Thanks in advance ;)
提前致谢 ;)
EDITThat's because I'm not logged in :D
编辑那是因为我没有登录:D
回答by Ben Claar
Either $post
isn't an object, or the user isn't logged in, so Auth::user()
is returning null
.
要么$post
不是对象,要么用户未登录,因此Auth::user()
返回null
.
To remove the error, check first if the user is logged in before running that section of code:
要消除错误,请在运行该部分代码之前先检查用户是否已登录:
@if (Auth::check())
// put auth-only code here
@if($post->id === Auth::user()->id)
<br><a href="#">Redaguoti</a>
@endif
@endif
回答by Chambah Russell
There are several instances you can get this error,
有几种情况您可能会收到此错误,
- When your response needs an authenticated user to access as your case might be and
- When you are returning an object but you're accessing it as an array either using foreach, or forelse.
- 当您的响应需要经过身份验证的用户访问时,您的情况可能如此,并且
- 当您返回一个对象但您使用 foreach 或 forelse 作为数组访问它时。
You have to check with all diligence what data you're returning and the respective methods accordingly
您必须仔细检查要返回的数据以及相应的方法