大家度过美好的一天,只想询问Laravel学习像我这样的学生。
登录后,我可以访问此页面:
Route::get('/posts/{id}', 'PostController@showById');
当我退出并尝试再次访问该页面时,我收到提到的错误,我希望即使是访客也要显示帖子,但如果他们已退出,则不允许撰写帖子。
这是showById():
public function showById($id)
{
$post = Post::find($id);
return view('show-solo', compact('post'));
}
show-solo.blade.php
@extends('master')
@include('partials.nav-none')
@section('content')
<div class="col-sm-8 blog-main">
<div class="blog-post">
@if ($flash = session('message'))
<div class="alert alert-success flash-message" role="alert">
{{ $flash }}
</div>
@endif
@if ( $post->user_id == Auth::user()->id)
<a href="/posts/{{ $post->id }}/delete">
<button class="btn-sm btn-warning post-btn" data-toggle="tooltip" data-placement="top" title="Delete Post"><i class="fa fa-times"></i></button>
</a>
<a href="/posts/{{ $post->id }}/edit">
<button class="btn-sm btn-primary post-btn" data-toggle="tooltip" data-placement="top" title="Edit Post"><i class="fa fa-pencil-square-o"></i></button>
</a>
@endif
<h2>Post number: {{ $post->id }}</h2>
<h2 class="blog-post-title">
<a class="title-link" href="/posts/{{ $post->id }}">{{ $post->title }}</a>
</h2>
<!-- {{ $post->created_at->toFormattedDateString() }} -->
<p class="blog-post-meta">{{ $post->created_at->diffForHumans() }} by <a href="#">{{ $post->user->name }}</a></p>
{{ $post->body }}
<hr />
@include('partials.error')
@include('partials.post-comment')
</div>
</div>
@endsection
如果这有帮助,这是我的路线:
Route::get('/', function () {
return view('welcome');
});
Route::get('/posts', 'PostController@index')->name('home');
Route::get('/posts/create', 'PostController@showForm');
Route::get('/posts/{id}', 'PostController@showById');
Route::get('posts/{id}/edit', 'PostController@editPostForm');
Route::get('posts/{id}/delete', 'PostController@deletePost');
Route::post('/posts', 'PostController@store');
Route::post('/posts/{post}/comments', 'CommentController@store');
Route::get('posts/{id}/delete', 'CommentController@deleteComment');
Route::post('/save-post', 'PostController@savePost');
Auth::routes();
Route::get('/home', 'HomeController@index');
Route::get('/register-user', 'RegistrationController@create');
Route::post('/register-user', 'RegistrationController@store');
Route::get('/login-user', ['as' => '/login-user', 'uses' => 'SessionController@create']);
Route::post('/login-user', 'SessionController@store');
Route::get('/logout-user', 'SessionController@destroy');
我做错了吗?即使我是访客,为什么我无法访问/发布/ {id}?那是什么&#34;试图获得非对象的属性&#34;消息是什么意思?
请告诉我是否应在此引用一些代码以帮助解决问题。
任何建议都将不胜感激。感谢。
答案 0 :(得分:1)
您在以下行中收到错误
@if ( $post->user_id == Auth::user()->id)
在视图中。
您在此行中收到错误的原因是您尝试访问经过身份验证的用户的ID,如Auth::user()->id
。但是没有经过身份验证的用户。因此,Auth::user()
调用返回null
。您正试图访问id
上的null
。
尝试将其更改为
@if ( $post->user_id == @Auth::user()->id)
OR
@if(Auth::user())
@if ( $post->user_id == Auth::user()->id)
...
@endif
@endif