Controller
We’ll be placing the code into our controller to follow an MVC style of programming. Let’s call the function ‘getBlogView()’, as this series is based on Tags and we’ll be needing to place those tags onto our blog page.
Here’s an example of my Blog Post View function. The view it is returning to shows a single blog post.
public function getBlogPostView($slug) {
//find slug and return post object
$post = Post::where('slug', '=', $slug)->firstOrFail();
$tags = '';
//get tag names via post
$tagList = $post->tags->lists('name');
for ($j = 0; $j < $tagList->count(); $j++) {
$tagList[$j] = '' . $tagList[$j] . '';
$tags = $tags . $tagList[$j];
if ($j < $tagList->count()-1) {
$tags = $tags . ' ';
}
}
$tagList = $tags;
$dataArray = array($post, $tagList);
return view('pages.blogPost')->with('dataArray', $dataArray);
}
First if we’re displaying one blog post. We’ll use the firstOrFail method obtain the Post Model Object. We can then use the post to get a list of our tag names through the $post object. Remember in our last tutorial we setup the tags method to grab the data from the database.
A little tip here, if you’ve noticed that we haven’t used parentheses immediately after the tag function.
$tagList = $post->tags()->lists('name');
Instead we’re calling the Builder instance of the tag which allows us to query the database. So what this line is doing is grabbing the ‘name’ column from the database for the post in question. (Docs: https://laravel.com/docs/5.2/queries)
We manipulate the array list by prefixing the tags with the remaining URL structure and concatenate each tag onto each other delimited by a space and then throwing it back into the same list. Now it’s ready to be passed onto the view.
View
There’s not much to be said about the view so I’ll just paste the code below. I should really be passing it as an associative array rather than using indexes. But dataArray[1] is where our tags will be printed
@extends('main')
@section('title', 'Blog Post')
@section('content')
Blog
{{ $dataArray[0]->title }}
{{ date('M j, Y', strtotime($dataArray[0]->created_at)) }} {!! $dataArray[1] !!}
{!! nl2br($dataArray[0]->body) !!}
@endsection
@section('padding')
@endsection
TL;DR
A little tip here, if you’ve noticed that we haven’t used parentheses immediately after the tag function.
$tagList = $post->tags()->lists('name');
Instead we’re calling the Builder instance of the tag which allows us to query the database. So what this line is doing is grabbing the ‘name’ column from the database for the post in question. (Docs: https://laravel.com/docs/5.2/queries)