Refactor Shared Variables on Blade Template View

We are getting addicted of having universal functions available for all views. At first we only use that for our App\Providers\AppServiceProvider to provide variable $navbars. It works perfectly and we don’t even have to think about it. However it occurred to me lately that we can have more:

  • Universal list of items
  • Anonymous functions

Let us explore each of them.

Universal list of items

At first my approach was to basically make our App\Providers\AppServiceProvider fetches recent blog posts and latest news (variable $recentBlogs and $latestNews respectively). It results in almost no way of customizing how much of each of them to be fetched, and when to fetch each of them. Basically we get all or nothing kind of deal, where ALL VIEWS would have this variable lingering about.

We wanted to improve that, and indeed we did find a better solution.

Anonymous functions

Instead of passing $recentBlogs and $latestNews, we can get an anonymous function $fetchPosts($type, $limit). Therefore we would always have this function lingering about.

However, unlike our previous approach, this one is actually useful. We can use it to basically fetch recent posts of type of our choosing, and of amount we specified. We have gained more control and flexibility on when to actually fetch items from database.

We didn’t stop there to make a list of posts. Other than $fetchPosts($type, $limit), we also specified more anonymous functions:

  • $fetchPost($slug) to fetch an individual published post item based on their slug. This function should basically return a Post model that we can morph according to our needs. It can potentially remove the need of passing Post objects directly from our controller.
  • $fetchPostById($id) to fetch any post item given only their id. Like $fetchPost($slug), but with this we can also obtain unpublished posts, as long as we know its specific ID. It can potentially be used for our landing page or any page we might need. It can also potentially be used for our footer! With this the controller will only need to pass the specific ID of our preferred footer.
  • $carbon($timestring) to generate a Carbon date instance of $timestring. If no $timestring is given, it will use current time instead. We can then use it to format date and time according to our needs on each view.

Conclusion

Generating a universal list of posts might be useful if we will often use them on any view. However if we need to only use that in certain pages but not all of them, it would be a waste of resource. Instead of generating an universal list of posts, we might better use anonymous functions.

With anonymous functions stored in variables and then make them available to all views, we would have more flexibility and usability. It would significantly reduce code complexity and duplication by abstracting them into common utilities that we can use on demand.