I started learning Laravel today and I've ran into a problem. There are 3 seperated posts. Each one has titles and I made an other title too which should be in the url of the page of the posts, for example: something.com/posts/post_three instead of posts/3 With the id version (posts/3) it worked perfectly, but I tried to change the code so it will go to posts/post_three, but I keep getting the following error:
Trying to get property 'created_at' of non-object (View: C:\xampp\htdocs\lsappesources\views\posts\show.blade.php)
I have the following codes which I've changed something in:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('urltitle', 'desc')->paginate(5);
return view('posts.index')->with('posts', $posts);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($urltitle)
{
$post = Post::find($urltitle);
return view('posts.show')->with('post', $post);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
-
@extends('pages.layouts.app')
@section('content')
<h1 style="text-align: center">Posts</h1>
@if(count($posts) > 0)
@foreach($posts as $post)
{{$post->urltitle}}
<div class="card" style="padding-top: 8px">
<div class="card-body">
<h3><a href="/posts/{{$post->urltitle}}">{{$post->title}}</a></h3>
<small>Written on: {{$post->created_at}}</small>
</div>
</div>
@endforeach
<div style="justify-content: center; display: flex;">{{$posts->links()}}</div>
@else
<p>No posts found</p>
@endif
@endsection
- And here is the code which can't "recognise" $post
@extends('pages.layouts.app')
@section('content')
<div class="jumbotron text-center">
<a href="/posts" class="btn btn-default">Go Back</a>
<h1>{{$post->title}}</h1>
<div>{{$post->body}}</div>
<hr>
<small>Written at {{$post->created_at}}</small>
</div>
@endsection