Reputation: 111
Here's the controller file code:
public function viewpost($url)
{
$url ='articles/'.$url;
if(count(posts::where('url', '=', $url)->first())<>1) {
return redirect()->back();
}
$posts = posts::all();
return view('viewpost')->with([
'posts' => posts::all(),
'post' => posts::where('url', '=', $url)->first()
]);
}
The normal URL of a post is supposed to be website.com/articles/name-of-post-here. In the sidebar, the posts are now being displayed as website.com/articles/articles/name-of-post-here
Example of a live post:
https://collegeconnect.ph/articles/how-to-improve-your-study-habits
Also, some of the posts have the status of "trashed" in the database. How can I only display posts with the stats of "active"?
My view code:
@foreach($posts as $post)
<p><a href="{{ URL::to($post->url) }}"><img style="width:100px;" src="{{asset('thumbnails/'.$post->thumbnail)}}" class="responsive"></a><br>
<a href="{{$post->url}}">{{substr(($post->title),0,88)}}..</a></p>
</tr>
@endforeach
Upvotes: 0
Views: 53
Reputation: 176
Your making 4 database calls in your example, Better to just get the data once from the DB and work with the data.
Also I would be getting post id, Allot cleaner. But if you want name you can change id to name.
in routes/web.php
Route::get('/articles/{url}', 'Auth\HomeController@viewpost');
in Controller
public function viewpost($url){
$url = 'articles/'.$url;
$posts = posts::where('post_status', '')->get();
$post = $posts->where('url', $url)->first()
if ( empty($post) )
return redirect()->back();
return view('viewpost')->with('post', $post)->with('posts', $posts);
Then in view $post will be available eg
<h1>{{ $post->title }}</h1>
Then in the foreach $posts loop in the view change it to
<a href="{{ URL::to($post->url) }}"><img style="width:100px;" src="{{asset('thumbnails/'.$post->thumbnail)}}" class="responsive"></a>
Upvotes: 2