Ever since I created the social media accounts for Bloganueva, I’ve wanted to find a way to direct users to my latest post. I thought it’d be a good idea to have something like this, especially for Instagram since you can only have links in your bio or stories (if you have more than 10,000 followers). Users would be able to go straight to the corresponding post from Instagram or wherever, and it would always be correct. Here’s what I did:
$post = App\Post::orderBy('id', 'desc')->first();
$slug = '/posts/' . $post->slug;
This code is in my web.php file with all my routes. The first line grabs the most recent post from the database. Then I set a variable for the URL in the second line. In the last line I use Laravel’s
Route::redirect method to redirect
/latest to the variable I’ve set for the most recent post.
This code is simple; however, getting here was pretty annoying. I was trying to use my
PostsController with this. However, no matter what I did, I figured out for some reason that this route required authentication for it to work. I believe this had something to do with the
Auth changes made in Laravel 5.7. When I created Bloganueva Laravel was at version 5.5. If I wanted to update my authentication to the 5.7 structure, I would have needed to basically remake a lot of stuff; and I do not want to do that at all. I decided I needed to find a new solution for this problem. That’s when I came up with what I have above. I’m so excited about this. I think it will make my Instagram account’s user experience much better and will prove to be more useful than I know in the future.