Reputation: 174
I have little problem with my Laravel project, when open Blog and try to read post, view give me error "Trying to get property of non-object (View: /Users/alex/Laravel/projekat/resources/views/blog/single.blade.php)"
Files in Http folder - Conttrolers: BlogController, PostController and Models: Blog
I have Blog folder and there is all okay (Create new blog, edit, delete). Posts find $id, and that showing me in url. Now, I want to use a slug instead of id in url. I don't want to change "public function show($id) to ($slug) in BlogController, need to keep them and create new function from PostController.
web.php
Route::get('blog/{slug}', ['as' => 'blog.single', 'uses' => 'PostController@getSingle'])->where('slug', '[\w\d\-\_]+');
Route::resource('blog', 'BlogController');
Auth::routes();
PostController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
class PostController extends Controller
{
public function getSingle($slug)
{
// fetch from the DB base on slug
$blog = Blog::where('slug', '=', $slug)->first();
// retunr the view and pass in the post object
return view('blog.single')->withBlog($blog);
}
}
view single.blade.php
<div class="vesti">
<div class="col-lg-12 col-md-12">
<h1>{{ $blog->naslov }}</h1>
<p>{{ $blog->tekst }}</p>
<hr/>
</div>
</div>
Thanks for your time!
Upvotes: 0
Views: 210
Reputation: 7083
You are trying to read an attribute from a null variable.
To avoid this you should check it before trying to access its attributes. Ex:
<div class="vesti">
<div class="col-lg-12 col-md-12">
@if ($blog)
<h1>{{ $blog->naslov }}</h1>
<p>{{ $blog->tekst }}</p>
<hr/>
@else
<h1>Error message</h1>
@endif
</div>
</div>
Upvotes: 0