13. Notable Code Snippets Within Views

This blog will explore a few code snippets within views which could be easily overlooked. This is important as it highlights ways in which the application was improved to make for a better user experience.


Dynamic navigation: Guest users and authenticated users will see different navigation links. This was achieved using an @guest tag. All HTML code within the opening @guest tag will be seen by guest users only, the HTML code within the @else tag will be seen by logged in users. This screen capture is taken from the application's only layout file (resources/views/layouts/app.blade.php).



Additional information on posts: The following snippet shows how I was able to show some extra information on each post. I chose to show the name of the author and the date/time when a post was first published - I displayed this using a custom format to aid readability using the format() method. I also added a user-friendly time difference (e.g. 2 days ago), by using the diffForHumans() method. Using an if statement, I could check if the post had ever been edited (if the created_at value was not equal to the updated_at value). If the post had been edited, again I displayed the date/time in a readable format. This screen capture is taken from the post index file (resources/views/posts/index.blade.php).



Displaying of post images and placeholder images: I chose to store images directly in storage with a unique file name - paths/filenames were not stored in the database. To reflect this in the views, I had to check if the image file existed, and if it did, then I would output the correct image associated with the post. If a post did not have an associated image, one of two placeholder images were displayed instead. To achieve this, I checked the current post's id, to find out if it was an odd or even number. Posts with an odd id would result in photo X being displayed, posts with an even id would result in photo Y being displayed. This screen capture is taken from the post index file (resources/views/posts/index.blade.php).



Displaying a post count: The following code checks how many blog posts a user has published. It retrieves the id of the current authenticated user, checks which posts belong to them and then finally conducts a count. This screen capture is taken from the home view (resources/views/home.blade.php).


Comments