This episode is for members only

Sign up to access "Build A Static File Blog with Laravel" right now.

Get started
Already a member? Sign in to continue
Playing
08. Refactoring to use Blade components

Transcript

00:00
Before we go ahead and add tags to our blog post, let's create another blade component
00:05
for the author information, because we're actually using this in two different places. Normally, I wouldn't refactor this early, but if we're working with something like this, where we want the styling to be very consistent, it's worth moving over to a new component. So I'm going to create out a blade component in here called, let's think, let's say PostMeta.
00:27
And again, we'll use that view flag in here because we don't really need a class associated with this component. It's going to be very, very simple. Okay, so we can head over to our index, we can grab what we need here, and we can add that to our PostMeta.blade.php component. We're going to be adding our tags in here later and iterating through them. So it kind of makes
00:49
sense for the PostMeta to be in its own component, because we don't want to be iterating over on lots of different pages. So we can just switch this up now. So let's go ahead and say X PostMeta, and then we can just pass the post through here that we want. So let's pass this in as post, and this is on our index, so we should see no difference at all. We can now reuse this component
01:12
over here, and then when we add to this later, we're just going to have these appear in both places. So let's go down to our show page, and we'll do the same here, and there we go. Great, so we have a little bit more consistency now. It's looking nice, and when we add our tags in the next few episodes, we can just add them to this component, and they will always be there.

Episode summary

In this episode, we start by noticing that our author information is being used in more than one place in our blog app. Instead of repeating ourselves, we decide to refactor this author (or post meta) section into its own Blade component. This keeps our codebase DRY and assures consistent styling everywhere we display this info.

So, we go ahead and create a new Blade component called PostMeta. Since the component is really simple and doesn't need any logic, we use the Blade view-only option instead of making a separate class. We then grab the markup for the author info and put it into our new component file.

From there, we update our index and show pages to use the new <x-post-meta :post="$post" /> component. With this refactor, nothing visibly changes in the browser, but we're now set up nicely for the next step—adding tags. When we do, we'll only have to update the PostMeta component, and the changes will automatically show up everywhere it's used! Pretty neat for keeping things consistent and easy to maintain.

Episode discussion

No comments, yet. Be the first!