Articles with the tag Tips

Different Ways To Pass Data To A Laravel View

2 years ago Mon, Jan 10, 2022

#1. Using a magic method

First up, Laravel uses some PHP magic to make sense of fluent methods. If, for example, you have an array of people in a variable $people, then you can use a magic method withPeople on the view() helper function (or View:: facade) to pass the array to your view. In your blade file, your people array will be available via a $people variable.

Route::get('/', function () {
    $people = ['Bob', 'John', 'Simon'];

    return view('welcome')->withPeople($people);

This method makes your code more readable to humans which will minimise the time it takes another developer (or your future self) to make sense of this code. Unfortunately, your IDE will most likely not be able to offer code completion or Intellisense for the withPeople method since it is using magic methods and has not been declared on the Illuminate\View\Factory class.

#2. Using a string parameter

If you liked the readability of the first method, but don't want to deal with IDE warnings, you can pass your array through with a string key that Laravel will use as the name for the variable made available in your view.

For example, if you have a people array, you can pass it to the view by using the with method, passing the string key people as the first argument and the array $people as the second argument.

Route::get('/', function () {
    $people = ['Bob', 'John', 'Simon'];

	return view('welcome')->with('people', $people);

This method has a slight limitation in that you are left with a magic string, ie: people that must be kept up to date. Say, for example, that you rename $people to $names using your IDE. It might not be immediately obvious that you need to change the string people to names. For this reason, string values that are used to create variables are often a source of confusion and code drift over time.

#3. Using an array

If you have more than one variable that needs to be passed to the view, then you can pass an array as the second attribute to the view helper method (or View Facade).

Route::get('/', function () {
    $people = ['Bob', 'John', 'Simon'];
    $days = ['Monday' 'Tuesday'];

    return view('welcome', [
	      'people' => $people
	      'days' => $days

This method can make your code look clean and concise, especially if you inline your variables.

Route::get('/', function () {
    return view('welcome', [
	      'people' => ['Bob', 'John', 'Simon'];
	      'days' => ['Monday' 'Tuesday'];

As with previous methods, you still have to set a string key for the array. Once again, string keys are often problematic, because they have no inherent meaning in PHP. This means that your editor will not be able to assist you with renaming this key across many locations.

#4. Using the compact method

Finally, we can make use of a function built in to PHP that can automatically create an array containing variables and their values.

If you are not familiar with the compact method, you can read about it in the PHP documentation.

Route::get('/', function () {
    $people = ['Bob', 'John', 'Simon'];
    $days = ['Monday' 'Tuesday'];

    return view('welcome', compact('people', 'days'));

This method is useful if you want to pass an array through to the view, but don't want to have to make an array with a key that is the same as the value variable.

// compact('people') === ['people' => $people]

Because compact is a well-defined PHP function, your editor may be able to deduce that the string key refers to a variable name in the same code block. compact can be extremely useful if you have many variables to pass through to a view and don't want to pass them inline.

compact('var1', 'var2', etc...)


There is no right or wrong way to pass data to a Laravel View. Some people detest magic methods, whilst others dislike string keys. The most important thing is that you choose a method that feels comfortable to you and try to be consistent across your code.

Let me know which method you prefer in the comments.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.
Continue Reading

Ten Tips For Mac Beginners

2 years ago Sat, Jan 8, 2022

My sister recently bought herself a new MacBook Air. Getting a new laptop is always exciting, but nothing beats the experience of opening your first Mac. Since she's coming over from Windows, I thought it would be useful for me to write down a few tips and tricks she (and you) might find useful for getting started on a Mac.

#1. How do I get online?

The first job of any modern computer is surely to access the internet. Those cat pictures don't view themselves. If you're reading this you're probably already online but here it goes anyway.

If you haven't aleady connected to WI-FI when going through setup then you'll want to look at the Menu Bar on the top right hand side of your screen. There you'll see a fan shaped icon that you can click on to show you a list of available networks. Choose your local WI-FI from the list, enter your password and you should be online in no time.

Next, you'll need a browser. Just as on an iPhone, the default browser is Safari. You'll find this in your dock if you look for a big compass icon.

Bonus Tip: On a Mac, the option key on the keyboard can often be used to list addition options in a menu. If you hold down the option key and then click on the same WI-FI icon as earlier, you will see a load more advanced options as well as more information about the network you are connected to.

#2. What's a Finder?

This is the app that let's you explore the file system of your machine, other machines on the local network, devices you plug into your machine or other computers on the internet. If you're coming from Windows, you're best thinking of it as something similar to Windows Explorer or File Explorer.

It's worth noting that this is one app you can't quit. You can close it's windows but you can't quit it as it's part of the Operating System and required for other apps. That begs a good question.

#3. How do I quit an app?

Before we get to that, it's a good idea to notice that when you click on an app in the dock, a small dot appears beneath it. That tells you that the app is open.

Now if you come from windows you might be used to pressing the red X button at the top right off any window. On a Mac, things work slightly differently as you might expect. The buttons are on the top left instead, but they don't work in exactly the same way. From right to left you have three buttons:

  • Green - Make the current window full screen (or vice-versa)
  • Yellow - Minimise (Hide) the current window. Notice that it disappears into the dock. Simply click on the dock icon again to maximise that window.
  • Red - Close the current window.

The real catch is in the last button. On a Mac, closing the window does not close the app. This is because many Mac apps allow multiple windows.

So, if you ever want to Quit the whole app, you can either:

  • Click on the name of the app at the top left of your screen and then choose Quit App where App will be replaced by the name of the current application.
  • Right click on the dock icon for the application you want to close and choose Quit.

Wait... you said 'Right Click'.

So I did, which brings us on to our next tip.

#4. How do I right click on a Mac?

When you first get a Mac you'll notice the beatiful trackpad doesn't have any buttons. In face, you can click anywhere on the trackpad to click on an item under your cursor. That doesn't mean you can't right click or bring up additional context menus. To get your trackpad to right click, open your computer's System Preferences. You can do this by clicking on the System Preferences app in the dock or by clicking on the Apple logo at the top left of your screen and then choosing System Preferences.

Now look for the Trackpad option. When you've opened the Trackpad setting, you'll notice that there is a Secondary Click checkbox. Make sure this is ticked and then click on the dropdown menu immediately beneath it. You'll find that you have the following options:

  • Click or tap with two fingers (a very good option if you can get used to it)
  • Click in the bottom right corner (just as you might be used to)
  • Click in the bottom left corner (WHY??)

Cool Fact: Try clicking your trackpad when the Mac is turned off and you'll notice it doesn't actually move! What?! Despite giving off a nice clicky feeling, Apple uses some Haptic Feedback magic to make you feel like the trackpad moved when it didn't. This means there are less moving parts in your trackpad which will make it work better for longer.

#5. I can't find the app I want!

When you first get a Mac, you'll see a lot of apps in the dock at the bottom of the screen. After a while you might find that you can't see all the apps that your mac can run and besides, how could they all fit in the dock (though some people seem to try).

One way to see all the applications on your Mac is open your Finder window and click on Applications in the menu of favourites on the left hand side.

Another option is to make a five finger gesture on the trackpad. This can be a bit tricky till you get used to it, but you need to put all your fingers on the trackpad and then bring your fingers together in a pinching motion. If you've done it right, you'll see all your apps on screen with a search bar where you can filter down to the one you are looking for.

Finally, if you're in a hurry or can't be bothered with all the clicking, press the Command and Space keys together and you will see a search bar appear in the middle of your screen. You can use this search bar to find an Application, but you can also use it to search literally anything on your Mac. This has been one of the best features of a Mac for years and it's called Spotlight. You can also access this search bar by clicking on the search icon in the Menu Bar at the top right of your screen.

#6. What other gestures can I use on the Trackpad?

Over the years, the Mac has gained a lot from the success of iOS on iPhone and iPad. There are countless gestures you can make use of, but it takes some time to get used to them and can be quite tricky to master at the start.

The best way to learn all these gestures is to head back into the Trackpad option in your System Preferences. There you will see that there are actually three tabs, one of which is named, quite helpfully, More Gestures. There you will see that you can configure the gesture you want to use, but even more helpfully, you'll find a little video when you click on each option, that explains how to perform each trackpad gesture.

If you're feeling lazy and can't be bothered with that, you can experiment by yourself. When you've had enough of things randomly scooting off and on your screen, you can also look at this helpful article on Apple's support website that lists all available gestures.

#7. How do I force quit an app?

Despite what you might have heard, even on a Mac, things occasionally go wrong and you might find yourself in a situation where the current application has become unresponsive. Luckily, the Mac operating system tends to keep things under control and one hanging application does not usually freeze the whole machine. If you notice a spinning beach ball icon then your app has probably encountered an issue that requires it to be closed forcefully.

To do this, you can either hold down the option key whilst right clicking on the application icon in the dock. You will then see that the Quit option has changed into a Force Quit option. If you open the menu and toggle the option key, you will notice the option change from Quit to Force Quit and back again.

Another option is to click on the Apple Icon at the top left of the screen and choose the Force Quit... option. You should then see a list of open applications that you can choose to Quit Forcefully.

#8. How do I install a new app?

Good question. Unlike iOS, this can sometimes become a little bit more complicated, but only because developers have more options on how to package and distribute their application.

First things first, just like you might be use to on an iPhone or iPad, the Mac comes with its very own app store. You can open the App Store app as described above or else by clicking on the Apple logo at the top left of your screen and choosing App Store. You'll need your Apple ID handy, even if you choose to download a free app. Things might change in the future, but for now you may soon notice that some apps that you would expect to be in the App Store are missing. That brings us to downloading apps from the internet.

Apps downloaded from the internet will usually end up in your Downloads folder which you can find in the left hand menu of the Finder app. When you click on them (or they open after download), you will find one of two things. If the app requires a complicated setup on your machine then the app will come with an installer that will go ahead and walk you through a number of steps in a Wizard that will ususally guide you through everything you need to do and know. An installer will usually also clean up after itself.

A more typical, but initially confusing scenario is that you will end up with something called a Disk Image in your downloads folder. A disk image is a little bit tricky to understand at first, but you should think about it like a temporary CD that has been inserted into your computer. As such, when you click on it, it is mounted and will need to be ejected when you are finished. Often times, this disk image will mount itself immediately after it is finished downloading. When the disk image is mounted you will see a Finder window with the application in it and perhaps a folder that says Applications. It might be tempting to click on the application there and then and you will infact find that it will open. You should not do this, as you will be confused later on when the application is not in your Applications folder. Instead, you should click and drag the application from the disk image into the applications folder (or the shortcut usually found in the disk image). That way, the self contained application is moved to your applications folder once and for all. After this, you can eject the disk image (remember the cd analogy) by clicking the Eject button next to the name of the disk image which you will find in the left hand menu of the finder window.

#9. Can't I just ask Siri?

If you don't mind talking to your computer, then Siri can be a great way to make your way around a Mac, especially when you are just getting to grips with things. To ask Siri, press the command key and the space bar at the same time, just as though you were going to make a spotlight search. Just hold the keys for a second longer and you will notice a window appear where Siri is asking, "What can I help you with?". Check out Siri's Support Page if you're not sure what to ask. Here are a few things to get you started:

  • Turn the brightness up
  • Turn the volume down
  • Open Finder
  • What's the weather like today?
  • Send Carl a message saying "Thanks for writing this article".
  • Tell me a joke (they're actually quite funny).

#10. Where can I get more help?

That's a lot of information to take in at once. If you're new to a Mac, it will take some time for things to start to feel natural. If you're looking for more help and a wealth of knowledge, there is no better place to start than Apple's Support Site and more specifically, the Mac OS User Guide.

Finally, and this goes to anyone reading this and not just my sister, please feel free to get in touch if you need any help. You can add a comment below or get in touch on Twitter.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.
Continue Reading

Better Http Status Codes In Laravel

2 years ago Sun, Jan 2, 2022

'Magic numbers' like 200 or 401 can cause a lot of confusion for colleagues or your future self. It's not always immediately obvious what these numbers represent.

A magic number is a number in the code that has no context or meaning.

Luckily, when it comes to HTTP Status Codes, we can make use of a complete set of constants that will make the meaning of your code self evident.

return Response::HTTP_OK;

For example, Response::HTTP_OK will return 200, Response::HTTP_UNAUTHORIZED will return 401 and my personal favourite Response::HTTP_I_AM_A_TEAPOT will return 418.

This is possible because the Illuminate\Http\Response class extends the Symfony\Component\HttpFoundation\Response class.

Finally, we also have access to an array of all status codes via Response::$statusTexts. This is handy if you want to list, validate or otherwise iterate over all status codes.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.
Continue Reading

Counting Related Models In Laravel

2 years ago Sun, Jan 2, 2022

Very often when retrieving a model in Laravel, it is useful to load a count of related models at the same time. For example, when loading a blog post, you might want to display the number of comments left on that post.

Luckily, Laravel has a method to do just that:

$posts = Post::withCount('comments')->get();

What's more, as of Laravel 8, you can also make use of the withMin, withMax, withAvg, withSum, and withExists methods.

Read more in the Laravel Documentation.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.
Continue Reading

Goodbye Forge, Hello Ploi

2 years ago Thu, May 6, 2021

When it first launched, Laravel Forge was the easiest and cheapest way to deploy a Laravel application onto a custom server. Recently, after repeatedly being presented with upgrade banners for new features, I decided to investigate the alternatives before committing to a higher fee. Happily, I stumbled upon Ploi.

At first I was skeptical that anyone could compete with the Laravel Core team who manage the established and stable product that is Laravel Forge, but over a few short hours I was increasingly convinced that Ploi was not only a suitable alternative, but hands down the better offering. Here's what finally changed my mind, made me switch all my sites and end my Forge subscription.

When it first launched, Laravel Forge was priced at $10 a month for unlimited servers, sites and services. This was an amazing and probably somewhat underpriced offering. It was incredible to be able to launch a Laravel site with a few clicks and forget about server management entirely. No more digging around in Nginx config files and hours spent installing the latest version of this or that version of PHP. Over time, more features were added for team functionality. I didn't upgrade because I didn't need access to these features. Later, the basic subscription price was increased slightly for new users, but the fee for users on existing plans remained the same.

In the last year or so, however, certain new features such as server monitoring and database backups were added but only made available to users on a premium tier at $39 a month. This is quite a steep increase for features that have now become commonplace on other services. Nevertheless, this is a price that would be well worth paying if it werent for two simple reasons.

First, instead of being hidden in the settings, these additional features are presented to all users irrespective of the tier they were on. This means that as you explore the UI, you are continually presented with useless pages for features you cannot use and encouraged somewhat relentlessly to upgrade to a higher tier.

Second, a lot has changed in the few years since Laravel Forge was launched. It is now much easier to deploy sites directly to cloud providers such as AWS and Digital Ocean. Furthermore, there are a number of competitors that offer the same feature set and more for a fraction of the price.

After a quick comparison of the alternatives, I stumbled upon Ploi. It makes a great first impression and gets better and better from there. First, its fresh design makes for a welcome break from Forge's simplistic user interface which despite being improved over the years has started to feel a bit tired. Its features are well organised, searchable and accessible and it's help pages are useful and comprehensive. Next, its pricing is cheaper than Forge on every tier and offers all Forge features for less than half the price. It is intuitive and easy to use and guides you to make full use of the featurews available to you. Even better, there is no mention of upgrading unless you are looking to do so.

Finally, when you are ready to pay a little bit more, you gain access to a rich array of features which are simply not available on Laravel Forge, such as:

  • Site Monitoring
  • File Browsing
  • Status Pages
  • The ability to suspend sites with the click of a button
  • Zero Downtime deployment

All of this combined, made it a no brainer for me. Much as Laravel Forge has served me well over recent years, it was time to move on. I hope that this increased competition will make both products better and can't wait for all the quality of life goodies that we can look forward to over the next few years.

If you're convinced or simply want to try Ploi for yourself, you can sign up for a free trial with no credit card required.

Thank you for reading this article.

If you've made it this far, you might like to connect with me on 𝕏 where I post similar content and interact with like-minded people. If this article was helpful to you I'd really appreciate it if you would consider buying me a coffee.
Continue Reading