256 Kilobytes

[Laravel/PHP] How to Make a “Recently Viewed Posts” Widget

Articles in Frameworks | By August R. Garcia

Published

Holy shit, use krsort(), not arsort().

2,290 views, 0 RAMs, and 0 comments

Okay, you fucking cocksuckers, I'm going to stab myself for the reason stated in the description.

Anyway, here's some code to make a fucking "recently viewed posts" widget in Laravel/PHP.

[Laravel/PHP] How to Make a “Recently Viewed Posts” Widget

Code

Main PHP Function

// The actual function to call to push the current page into the "recently viewed posts"
// cookie data. The only Laravel functionality here that isn't in plain PHP is the Laravel
// cookie library:
// https://laravel.com/docs/5.7/requests#cookies
// Also \Request::url(), which gets the current URL:
// https://laravel.com/docs/5.7/urls#accessing-the-current-url
function push_current_page_to_recently_viewed($post_title="Some Post") {
        // Configuration Variables
        $num_to_store     =    5; // If there are more than this many stored, delete the oldest one
        $minutes_to_store = 1440; // These cookies will automatically be forgotten after this number of minutes. 1440 is 24 hours.

        // Create an object with the data required to create the "Recently Viewed" widget 
        $current_page["name"]       = $post_title;
        $current_page["url" ]       = \Request::url(); // The current URL  

        // Get the existing cookie data from the user 
        $recent                  = \Cookie::get(  'recently_viewed_content');

        // Since cookies must be strings, the data is stored as JSON.
        // Decode the data.
        // The second parameter, "[w]hen TRUE, returned objects will be
        // converted into associative arrays."
        $recent                  = json_decode($recent, TRUE);

        // If the URL already exists in the user's history, delete the older one
        // Note -- If there are multiple URLs for individual posts (GET variables, etc)
        // Possibly rework to include a unique post ID (or whatever) 
        if ( $recent ) {
                foreach ( $recent as $key=>$val ) {
                        if ( $val["url"] == $current_page["url"])
                                unset( $recent[$key] );
                }
        }

        // Push the current page into the recently viewed posts array 
        $recent[ time() ] = $current_page;

        // If more than $num_to_store elements, then delete everything except the newest $num_to_store 
        if (sizeof($recent) > $num_to_store) {
                // These are already in the correct order, but would theoretically be logical to sort by key here.
                $recent = array_slice($recent, sizeof($recent)-5, sizeof($recent), true);
        }

        // Queue the updated "recently viewed" list to update on the user's next page load 
        // I.e., don't show the current page as "recently viewed" until they navigate away from it (or otherwise refresh the page)
        \Cookie::queue('recently_viewed_content', json_encode($recent), $minutes_to_store);
}

PHP/Blade Template File

<?php
/*
 * This is a widget/whatever that shows a user links to their recently viewed posts.
 * Easily converted to plain PHP.
*/
$recently_viewed_content = json_decode(\Cookie::get('recently_viewed_content'), TRUE);
?>
@if ( $recently_viewed_content )
        <?php
                krsort( $recently_viewed_content );
        ?>
        <details open>
                <summary class='help' title="Recently Viewed">Recently Viewed</summary>
                <ul>
                        @foreach ( $recently_viewed_content as $rvc)
                                <li><a href="{{ $rvc['url'] }}" rel="nofollow">{{ $rvc['name'] }}</a></li>
                        @endforeach
                </ul>
        </details>
@endif

Include the Widget

<?php
    // Standard include with the blade templating engine
    // Can do basically the same with plain PHP
?>
@include('inc.recently-viewed-posts')

In Conclusion

What a nice post. The end.

Download more RAM. 🐏 ⨉ 0Posted by August R. Garcia 2 years ago 🕓 Posted at 03 February, 2019 05:55 AM PST

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

August Garcia is some guy who used to sell Viagra on the Internet. He made this website to LARP as a sysadmin while posting about garbage like user-agent spoofing, spintax, the only good keyboard, virtual assitants from Pakistan, links with the rel="nofollow" attributeproxiessin, the developer console, literally every link building method, and other junk.

Available at arg@256kilobytes.com, via Twitter, or arg.256kilobytes.com. Open to business inquiries based on availability.

Post a New Comment

Do you like having a good time?

Register an Account

You can also login to an existing account or reset your password. All use of this site is subject to the terms of service and privacy policy.

Read Quality Articles

Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.

View Articles →

Argue with People on the Internet

Use your account to explain why people are wrong on the Internet forum.

View Forum →

Vandalize the Wiki

Or don't. I'm not your dad.

View Wiki →

Ask and/or Answer Questions

If someone asks a terrible question, post a LMGTFY link.

View Answers →

Make Some Money

Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.

Register an Account