How to Create Short URLs in Laravel

https://ashallendesign.ams3.digitaloceanspaces.com/public/blog/56/how-to-create-short-urls-in-laravel.png

Introduction

Short URL is an open-source Laravel package that you can use to create short URLs for your web apps. It comes with different options for tracking users that click your short URL and it only takes a couple of minutes to add it to your Laravel project.

In this article, we’re going to step through how to install Short URL (ashallendesign/short-url) in your Laravel projects and then take a look at a few of the different customisation options that are available. If you’re interested in checking out the code for the package and seeing what other functionality the package provides, you can view it in the GitHub repository.

There’s also a really useful, quick review video by Povilas Korop (Laravel Daily) at the end of this article to show how you can use the package.

To get a better idea of what the package does, let’s take a quick look at a basic example. Imagine that you have a Laravel app hosted on https://my-web-app.com and you want to create a short URL to redirect the user to https://ashallendesign.co.uk. To do this, your code might look something like this:

        

1use AshAllenDesign\ShortURL\Facades\ShortURL;

2 

3$shortUrl = ShortURL::destinationUrl('https://ashallendesign.co.uk')->make();

We can then imagine that this code would create a short URL similar to this: http://my-web-app.com/short/abc123. Now, if you were to navigate to this URL, you’d be redirected to https://ashallendesign.co.uk and your visit would be recorded in the database (if the tracking features are enabled).

In fact, if you read my monthly Round Up articles (such as “Round Up: March 2022“), you’ll likely know that I’m using Short URL as the basis for building a small privact-first, open source URL shortening service. The service is called Mango Two and is something that I’m slowly building as a side project so that I can have some practice with using Typescript to build a Chrome extension. If you’re interested in checking it out, there’s already an early version of the extension available for installing that you can install in under 30 seconds! Any feedback on the Mango Two Chrome extension is greatly appreciated.

Installing the Package

To get started with the Short URL package, you’ll need to make sure that your Laravel app is using at least Laravel 8.0 and PHP 8.0.

You can install the package via Composer using the following command:

        

1composer require ashallendesign/short-url

After installing the package, you can then publish the package’s config file and database migrations by using the following command:

        

1php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider"

This package contains several migrations that add two new tables to the database: short_urls and short_url_visits. To run these migrations, simply run the following command:

Congratulations, Short URL should now be installed in your Laravel app and ready to use!

Creating Short URLs

Now that we’ve installed Short URL, let’s take a look at how we can create our own short URLs.

The quickest way would be to use something similar to the snippet below. We simply need to choose the destination URL that the visitors would be redirected to, and then use the make method to store the Short URL in database.

        

1use AshAllenDesign\ShortURL\Facades\ShortURL;

2 

3$shortURLObject = ShortURL::destinationUrl('https://destination.com')->make();

4 

5$shortURL = $shortURLObject->default_short_url;

The make method returns a AshAllenDesign\ShortURL\Models\ShortURL model that extends the default Laravel Illuminate\Database\Eloquent\Model class. So, all of the usual methods that you’d typically call on your Laravel models can also be used here if you’d like.

Using Custom Short URL Keys

By default, the shortened URL that is generated will contain a random key (the key is the unique identifier that is placed at the end of short URLs). For example, if a short URL is https://webapp.com/short/abc123, the key would be abc123.

Sometimes, you may wish to define a custom key yourself for that URL that is more meaningful to your visitors than a randomly generated one. This is perfect for if you’re using the short URLs for things like marketing or advertising campaigns.

To define a custom short URL key, you use the urlKey() method, like in the example below:

        

1use AshAllenDesign\ShortURL\Facades\ShortURL;

2 

3$shortUrl = ShortURL::destinationUrl('https://destination.com')

4 ->urlKey('custom-key')

5 ->make()

6 ->default_short_url;

7 

8// $shortUrl will be equal to: "https://webapp.com/short/custom-key"

Tracking Visitors

Depending on what you’re using the short URLs for, you may want to track some data about the visitors that have used the short URL. This can be particularly useful for analytics.

By default, tracking is enabled and all of the available tracking fields are also enabled. You can toggle the default options for the different parts of the tracking in the package’s short-url.php config file that you published when installing the package.

If you want to override the default option set in the config file whether tracking is enabled or not when creating a shortened URL, you can use the trackVisits() method.

For example, if we wanted to force tracking to be enabled for the URL, our code might look something like this:

        

1$shortURLObject = ShortURL::destinationUrl('https://destination.com')

2 ->trackVisits()

3 ->make();

Likewise, if we wanted to force tracking to be disabled for the URL, our code might look something like this:

        

1$shortURLObject = ShortURL::destinationUrl('https://destination.com')

2 ->trackVisits(false)

3 ->make();

Enabling Tracking Fields

If tracking is enabled for a shortened URL, each time the link is visited, a new ShortURLVisit row in the database will be created. By default, the package will record the following fields of a visitor:

  • IP Address
  • Browser Name
  • Browser Version
  • Operating System Name
  • Operating System Version
  • Referer URL (the URL that the visitor originally came from)
  • Device Type (can be: desktop/mobile/tablet/robot)

Each of these fields can be toggled in the config files so that you only record the fields you need. However, if you want to override any of the default options, you can do so when creating your short URL.

For example, if we wanted to force all of the tracking fields to be enabled when creating our short URLs, our code might look something like this:

        

1ShortURL::destinationUrl('https://destination.com')

2 ->trackVisits()

3 ->trackIPAddress()

4 ->trackBrowser()

5 ->trackBrowserVersion()

6 ->trackOperatingSystem()

7 ->trackOperatingSystemVersion()

8 ->trackDeviceType()

9 ->trackRefererURL()

10 ->make();

It’s worth noting that each of the tracking methods also allows you to pass false as the argument to force a specific fields to not be tracked. For example, if we wanted to force the IP address to not be tracked, our code could look something like so:

        

1ShortURL::destinationUrl('https://destination.com')

2 ->trackVisits()

3 ->trackIPAddress(false)

4 ->make();

Creating Single-use Short URLs

By default, all of the short URLs that you create can be visited for as long as you leave them available in your database. However, depending on how you’re using them in your applications, you may want to only allow access to a short URL once. This would then mean that any subsequent visitors who visit the URL after it has already been viewed will get a HTTP 404 response.

To create a single use shortened URL, you can use the ->singleUse() method.

The example below shows how to create a single use shortened URL:

        

1ShortURL::destinationUrl('https://destination.com')->singleUse()->make();

Setting Activation and Deactivation Times

By default, all short URLs that you create are active and accessible as soon as you create them and until you delete them from your database. However, the package provides functionality for you to set activation and deactivation times for your URLs when you’re creating them.

Doing this can be useful for things like marketing or advertising campaigns. For example, you may want to launch a new URL for a marketing campaign on a given date and then automatically deactivate that URL when the campaign comes to an end.

The example below shows how to create a short URL that will be active from this time tomorrow onwards:

        

1ShortURL::activateAt(now()->addDay())->make();

The example below shows how to create a short URL that will be active from this time tomorrow onwards and then is deactivated the day after:

        

1ShortURL::activateAt(now()->addDay())

2 ->deactivateAt(now()->addDays(2))

3 ->make();

If a user was to visit a short URL before it was activated or after it was deactivated, they would receive a HTTP 404 response.

Customising the Short URL Prefix

The Short URL package comes with a route that you can use for your short URLs without any further setup. By default, this route is /short/{shortURLKey}.

You might want to keep using this default route but change the /short/ prefix to something else. To do this, you can change the prefix field in the config.

For example, if we wanted to change the default short URL to /s, we could change the config value like so:

        

config/short-url.php

1return [

2 

3 // ...

4 

5 'prefix' => 's',

6 

7 // ...

8 

9];

Likewise, you may also remove the prefix from the default route completely. For example, if you want your short URL to be accessible via /{shortUrlKey}, then we could update the prefix config value to null like so:

        

config/short-url.php

1return [

2 

3 // ...

4 

5 'prefix' => null,

6 

7 // ...

8 

9];

Using the Short URLs

Now that we know how to create the short URLs, let’s take a look at how to visit them in our applications.

The package makes using the short URLs super simple because it ships with it’s own route and controller that are automatically available without any set up.

Unless you changed the prefix field in the short-url.php config file, the package’s route is available at short/{urlKey}. This route uses the single-use controller that is found at \AshAllenDesign\ShortURL\Controllers\ShortURLController.

That’s it, there’s nothing more to it (as long as you want to use the package’s route)! You can start sharing your short URLs and they can be instantly accessed by your visitors.

Using a Custom Route

There may be times when you wish to use your own route or controller for your short URLs other than the default URLs that are created.

If you want to use a different route but use the same controller, you’ll just need to add your new route to your web.php field and point it to the controller like so:

        

web.php

1Route::get('/custom/{shortURLKey}', '\AshAllenDesign\ShortURL\Controllers\ShortURLController');

It’s important to remember that your route must include a {shortURLKey} field.

If you do choose to use your own route or controller, you might want to disable the default route that the app provides. By doing this, any visitors who try to use the packages default route (when you don’t want them to), will receive a HTTP 404 response. To do disable the route, you can set the disable_default_route field in your short-url.php config file to true, like so:

        

config/short-url.php

1return [

2 

3 // ...

4 

5 'disable_default_route' => true,

6 

7 // ...

8 

9];

Laravel Daily Review

Povilas Korop also made a quick review video of the Short URL package. So, you can see it in action here:

Conclusion

Hopefully, this post should have shown you how you can use the Short URL package in your Laravel apps to create shortened URLs. If you’re interested in checking out the code for the Short URL package, you can view it in the GitHub repo.

If you enjoyed reading this post, I’d love to hear about it. Likewise, if you have any feedback to improve the future ones, I’d also love to hear that too.

If you’re interested in getting updated each time I publish a new post, feel free to sign up for my newsletter below.

Keep on building awesome stuff! 🚀

Laravel News Links

Matt Layman: You Don’t Need JavaScript

https://www.mattlayman.com/img/2022/bbkPxxxCV6M.jpgWhat If I Told You… You Don’t Need JavaScript.
This talk explores why JavaScript is not good fit for most web apps.
I then show how most web apps can do dynamic things using htmx. htmx is an extension library to make HTML markup better.
I present examples of AJAX fetching and deletion. The presentation includes a dynamic search and how to implement infinite scrolling with a trivial amount of code.Planet Python

‘Stormgate’ is a new free-to-play RTS from the director of ‘Starcraft 2’

http://img.youtube.com/vi/lLMEIMCmS44/0.jpg

In 2020, Starcraft 2 production director Tim Morten left Blizzard to start Frost Giant Studios. At Summer Game Fest, he finally showed off what he and his team have been working on for the past two years. We got our first look at Stormgate, a new free-to-play real-time strategy game that runs on Unreal Engine 5. Morten didn’t share too many details on the project but said the game would feature two races at launch.  

Frost Giant features some serious talent. In addition to Morten, former Warcraft 3: The Frozen Throne campaign designer Tim Campbell is part of the team working on Stormgate. Frost Giant plans to begin beta testing the game next year. 

Engadget

One Reporter’s Road Trip Nightmare Proves the Electric Vehicle Skeptics Right

https://www.louderwithcrowder.com/media-library/image.png?id=29955272&width=980

As much as the environmentalist crowd and proponents of "green" renewable energy enjoy touting the newest technological innovations as something of a godsend, many Americans remain skeptical of the advances. Even the seemingly unstoppable climb in gas prices fails to move many who simply don’t believe their neighbor’s Prius is the solution to their fiscal woes. Perhaps it’s just intransigence. Maybe Americans simply aren’t prepared to adopt the new technology simply because we’re stuck in our ways–who doesn’t enjoy hearing the purr of a finely tuned vehicle or the roar as you stomp the gas at a light that has only just turned green.

But it may also be that people have weighed to pros and cons, looked into the capabilities, and made an educated choice based on all the relevant factors. If they haven’t, or if they are still thinking about making the move to an electric vehicle, the story of one journalist’s nightmare road trip might be the final bit of information they need to make a decision.

Writing for the Wall Street Journal, Rachel Wolfe prepared and planned for a recent trip with all the glee of a child counting down the days to Christmas the year before finding out Santa doesn’t actually exist. She is hopeful to the point of giddiness, unaware that the fantasy she’s been told is all about to come crashing down, in due time.

She’s responsible about the planning, outlining the entire itinerary, and planning every stop to charge her rented Kia EV6. She’s so sure about her plan that she invites along her friend who has a hard time to meet–a shift at work at the end of the trip.

What Wolfe and her friend Mack find out, however, is the truth.

The reality of the electric vehicle infrastructure immediately slaps the duo in the face. Not only are chargers apparently divided into quick chargers and, well, not, but among those chargers there exists an extremely and ultimately disconcerting caveat to the moniker "quick charger." This categorization is given to those machines capable of supplying from 24-350kW, a range that proves troublesome as it translates into far longer charge times when the machine you’ve stopped at is on the lower end of that spectrum and even worse when it can’t even meet the minimum standard, like the machine Wolfe came across in the first leg of her trip.

From there, it only spirals. Suffice it to say, deficiencies in the charging infrastructure as well as flaws in the vehicle itself, which especially suffers through inclement weather, repeatedly deal blow after blow, heartache after headache all the way to the end. What’s more, it would seem the universe was attempting to warn the two women about their decision, as person after person along the way voiced apprehension, skepticism, and regret regarding the purchase of electric vehicles.

At one point, to conserve energy, Wolfe and her friend frantically work to cut power consumption to prevent a breakdown on the road in the middle of a storm. "To save power, we turn off the car’s cooling system and the radio, unplug our phones and lower the windshield wipers to the lowest possible setting while still being able to see. Three miles away from the station, we have one mile of estimated range."

Don’t worry. This isn’t about to turn into a horror movie where they break down in the middle of the night or something. They make it to the next charging station but only right in the nick of time.

"At zero miles, we fly screeching into a gas-station parking lot. A trash can goes flying and lands with a clatter to greet us."

They also manage to make it back to Chicago in just enough time for an emotionally drained and physically exhausted Mack to walk into a shift at work, at least she didn’t miss it.

In the end, even Wolfe was forced to come to terms with the reality of the present state of EVs and their support, obviously coming to the conclusion that they aren’t all they’re cracked up to be.

"The following week, I fill up my Jetta at a local Shell station. Gas is up to $4.08 a gallon. I inhale deeply. Fumes never smelled so sweet."

While I’ve editorialized quite a bit and condensed her story down to just a few snippets, you can rest assured the entire story is there. And for those of us who have honestly kept an eye on the burgeoning electric vehicle industry, absolutely none of this comes as a shock. The tech is getting there, and I will even concede that it may well become something great and reliable in the future, but that future is not yet upon us. So, while politicians and celebrities laugh at Americans still driving around in gasoline-powered vehicles, pointing at the skyrocketing gas prices and laughing at those forced to pay them, the truth is that even those financially capable of making the change to an EV will find themselves wrestling with the same issues encountered by Wolfe during her brief trip.

Now, I just moved. The drive was about 350 miles one way, and I did it on a single tank of gas. And while even my trip suffered from a few spats of rainy weather, I never had to stop or sacrifice my AC or unplug my phone, turn off the radio, or worry about if my windshield wipers were going to suck up the last bit of fuel in the tank. And if I had run low on fuel, I knew that any gas station could fill me up. And the high prices notwithstanding, that’s a level of peace of mind no EV driver can say to have. Or rather, not if they want to pull out of the station in under an hour.

Perhaps what is necessary is not to force Americans to make the transition to EVs; this would only serve to stress an already weak infrastructure. What we need is more responsible policies to lower gasoline prices, make driving more affordable, and provide the requisite amount of time to build that infrastructure if and or when that transition occurs naturally.

The Louder with Crowder Dot Com Website is on Instagram now! Follow us at @lwcnewswire and tell a friend!


Kamala DODGES Question On The Idiotic ‘Green New Deal’ | Louder With Crowder

www.youtube.com

Louder With Crowder

You Thought ‘Bugdom’ and ‘Nanosaur’ Were Lost Forever

https://i.kinja-img.com/gawker-media/image/upload/c_fill,f_auto,fl_progressive,g_center,h_675,pg_1,q_80,w_1200/3f2bea8263f27df10227d92520762547.jpg

These days, the only pre-installed game you’ll find on Mac is an exciting, strategy-based war simulator pitting royal factions against one another. And by that, I mean Chess. But now you can get unique, fun, classic games like Bugdom, Nanosaur, and Cro-Mag Rally. I thought these titles were lost for good, but as it turns out, you can still play them.

I grew up with the iMac G3. To the outside world it certainly wasn’t a gaming machine, but to me it was a premiere PC. I was able to play the games I wanted to play, which were usually the Mac’s two Harry Potter ports (those soundtracks, though), but my favorite part of the G3 was the pre-installed titles: I didn’t have an N64, PlayStation, or GameCube, but I had Bugdom, Nanosaur, and Cro-Mag Rally. And that was alright with me.

What happened to Bugdom, Nanosaur, and Cro-Mag Rally?

In case you don’t have the fond memories of these titles, here’s a quick summary: Bugdom has you playing as a pill bug traversing 10 levels to save your world from an invasion of enemy ants. (It’s great, I promise.) In Nanosaur, you’re a dinosaur armed to the teeth, outrunning other dinosaurs in an effort to steal their eggs. (Again, it’s great.) And Cro-Mag Rally is a kart racer game that’s set in the ancient world, complete with “time-appropriate” karts and weapons.

These games wouldn’t be a sell in 2022, but they did push some boundaries for Mac gaming and 3D development back in the day.

It doesn’t end there, though: The iMac G5 also shipped with two unique titles: Nanosaur 2, a sequel to the original dino shooter (this time starring a murderous pterodactyl), and Marble Blast Gold, in which you controlled a marble through a series of progressively challenging race tracks to the finish line. To give credit where credit’s due, Pangea Software developed most of these games, plus plenty of other games you could purchase separately, while Marble Blast Gold was developed by GarageGames.

The problem with these old games is they were written for Mac hardware (PowerPC) that is no longer supported. The original game files exist, but if you download them to your Mac today, you won’t be able to open them. With the exception of mobile ports (which I’ll cover below), I thought most of these games were essentially lost forever. Luckily, there’s a way to replay them on your current hardware, through both mobile ports, as well as total rewrites of the games’ original code.

How to download classic Mac games, or play online

The two titles available as Mac downloads right now are Bugdom and Nanosaur. These games have been rewritten by developer Jorio for macOS, Windows, and Linux, which allows you to play the original games as they were on your current machine. To install these games on your computer, follow the links above, then choose your particular OS from the list of download links. It’s a nostalgia trip, for sure. Do I miss playing these things on that classic CRT display with the matching keyboard and hockey puck mouse? Sure. But after years of not being able to play Bugdom outside of my own memories, I’ll take it.

The easiest one to play, though, is Marble Blast Gold. The game and its sequel were ported by developer Vanilagy as web apps, meaning you can play right in your browser. Head to this site, then click the marble in the top left to choose Marble Blast Gold. You’ll find all levels already unlocked, plus over 2,000 custom levels designed by other players.

Cro-Mag Rally and Nanosaur 2 haven’t been rewritten for modern Macs, unfortunately, but you can play the games’ ports on iOS and iPadOS as a $1.99 download (there’s also a free version of Nanosaur 2 with ads). Nanosaur 2 is mostly how I remember it, but I’m a bit disappointed with the Cro-Mag Rally situation. Don’t get me wrong—I’m thrilled this game is ready to play in 2022 in any form, but this version isn’t the one I really want. Cro-Mag Rally on Mac OS X came with additional game modes, plus a settings pane that let you adjust the physics of the game. I’d love to experience those parts of Cro-Mag Rally again, but it doesn’t look like that’s happening anytime soon.

 

Lifehacker

Akaunting 3.0


We are a podcast-first media company based in Estonia and Turkey. We are required to follow two different tax regimes in two countries. Akaunting helps us focus on what matters to grow our business
instead of being tangled in invoicing details. And their App Store is beneficial if you are trying to customize the bookkeeping process.

Laravel News Links

In Honor Of Pride Month Chick-Fil-A Waffle Fries Will Be Seasoned With Salt From Lot’s Wife

https://media.babylonbee.com/articles/article-11445-1.jpg

U.S.—Chick-Fil-A has finally come around to celebrating pride month this year. The fast-food company has announced that throughout June, all waffle fries will be covered in salt from Lot’s wife.

“Other companies go in for rainbow flags and squeezing in PRIDE everywhere they can, but we wanted our celebration of pride month to be a bit more…biblical,” said Dan Cathy at a recent press release. “Now with every delicious, perfectly seasoned bite of waffle fry customers will be reminded how God celebrates Pride.”

“Wow! That IS salty. Man, I needed this reminder to flee from sexual sin,” said Chick-fil-a patron Brenda Lovelace. “I don’t want to end up as a pillar of salt just like Lot’s wife!”

Much to Chick-fil-a’s surprise, this move to faithfully honor pride month has been met with intense backlash from the LGBT community. “WHAT?! You’re supposed to celebrate by changing all your bags to rainbow flags and putting Drag Queens in the playplace ball pit!” said queer-activist Brandley Xenus. “This doesn’t count!” 

At publishing time, Dan Cathy also announced that if you tell any employee the secret phrase “I take kids to Drag shows,” they will celebrate by placing a millstone to your neck and tossing you into the ocean.


Are you a woman? It’s hard to tell these days. Watch our well-researched video to find out whether you are indeed a woman.

Subscribe to The Babylon Bee on YouTube

The Babylon Bee

Blow-Molding a Boat

https://theawesomer.com/photos/2022/06/blow_molding_a_boat_t.jpg

Blow-Molding a Boat

Link

This fascinating video from GWIN TECH shows how a factory quickly cranks out lightweight plastic boats. The blow molding process involves filling a plastic bladder with hot air and then stamping them together with giant dies while the plastic is still pliable.

The Awesomer