Entries with the tag “laravel”

These entries contain content about programming efficient, effective and secure Laravel projects.

Want to become a better Laravel programmer? Check out masteringlaravel.io for ebooks, videos, tools and more - or listen to the dulcet tones of Joel and I talking Laravel on the No Compromises Podcast.

Logging for Laravel Http Client

Jan 15, 2024 laravel

I’m a huge fan of using the Laravel HTTP Client for requests to third-party APIs. It’s clean and easy, nice for unit testing, and exposes methods for the most common functionality we need when consuming APIs. But one thing has bothered me - how do I log both my request and the API’s response, no matter what, with no special calls. Well, we’re in luck - using some global middleware on the client, we can do just that.

Actions Should Not Have Tightly Coupled Input

Oct 12, 2023 laravel php programming

If you’re going to use an Action pattern for your application, be careful what you expect coming in as input. In fact, input should be loose and output should be tightly coupled. Let me explain…

Is a Laravel Blade Component for a Form a Good Idea?

Jun 5, 2023 laravel

The other day I was troubleshooting some code for a form in Laravel that was using a PUT method. Turns out the previous developer had not understood - and I had missed - that the @method override was missing. So I got to thinking - what if we made a form component that handles this for us? Is this a good idea?

Get Laravel Auth User in 404 Blade

May 6, 2023 laravel

It’s nice that you can customize the 4xx/5xx error blade files if they’re published in Laravel - I like that. But what if you want to access the current user - or even use your standard layout - for the not found / 404 error? It’s actually quite easy. Let’s check it out.

Sort Nova Users on Spatie Role

Apr 9, 2023 laravel

The specific challenge is to sort users in a Laravel Nova application by their role. For this specific example, though, we have a number of assumptions. Although this article solves this very specific problem, you can probably extend it to apply to other custom data challenges in Nova. Let’s check it out.

Use PHPDoc in Laravel Blade files for autocomplete in PHPStorm

Oct 25, 2022 laravel php phpstorm

I love PHPStorm, but it can only do so much. Even with plugins like Laravel Idea, you may still have some missing features. One that I wish I had was autocomplete of models from collections or paginators in blade files. Well, turns out there’s an easy enough way to add this functionality for yourself.

Quick trick for Laravel requests saves tons of time

Sep 14, 2022 laravel php

I love Laravel request classes for validation. You should be using these whenever you can! But sometimes, writing the rules seems redundant between store and update. There’s a quick fix, though.

Be careful with prepareForValidation in Laravel

Sep 2, 2022 laravel php

The prepareForValidation() method is really useful in Laravel requests: it helps modify the incoming data so that validation might be easier. But you need to be careful that you implement it correctly and don’t mess up your data. Let me explain.

Use Traits in Laravel in Policies

Jul 11, 2022 laravel php

I love using Policies in Laravel. A particularly useful feature is the interception of checks. But what if only some of our policies need that? That’s where we can judiciously use traits.

How to Break Down Laravel Unit Tests into Types

Jun 23, 2022 laravel php testing

What’s the difference between unit test, integration test, and a feature test? Which should you use for what type of test? Is it just preference or does performance factor in when using Laravel? Let me give you my take from over a decade of unit testing experience.

Add Interfaces to Laravel to Increase Code Readability and Verbosity

Jun 11, 2022 laravel php

There seems to be an endless debate: clearly written code doesn’t need comments vs comments are needed to explain code and give context. I can see both sides of this debate, but there is a middle ground. Let me show you one way.

Highlight Laravel Logs in PHPStorm

Jan 12, 2022 laravel phpstorm

I’d like to say I don’t ever have tons of error logs in my Laravel projects - but, sometimes it happens. With a sea of text, how can you see what you need to see easily? Enter JetBrain’s idealog plugin in PHPStorm.

The State of Security of Laravel Apps in 2021

Jan 4, 2022 laravel php

The State of Security of Laravel Apps in 2021 is a whitepaper based on the quiz submissions from Laravel programmers.

Command to Quickly Show Config in Laravel

Dec 21, 2021 laravel php

What if you need to see your config quickly in Laravel from the command line? And you don’t want to use Tinker? Let me show you how I do it…

Capture and redirect all Laravel email

Dec 2, 2021 laravel php

First off, if you can use something like mailtrap I definitely recommend doing it. Mailtrap provides credentials and configuration so you can capture all of your email into a test inbox. But if that’s not possible, there is another option - and it has to do with Laravel’s mail events.

Publish Bugsnag's Laravel Configuration Only

Nov 14, 2021 laravel php

If you follow the instructions to customize the configuration of Bugsnag’s Laravel package, they’ll tell you to run vendor:publish. But this is not what I want.

How to Install a Composer package from a local zip

Nov 8, 2021 composer laravel php

I use Laravel Nova in a lot of my projects, but I’ve never liked the idea of storing the files in a local directory after download. Yes, you can use credentials for a Composer-based install, true, but I wanted something that didn’t require that. Turns out you can install packages like Laravel Nova from a zip file locally. Here’s how.

Do Not Use Laravel Tinker in Production

Oct 19, 2021 laravel php

I’ll say it again: do not install Laravel Tinker in production, and certainly do not use it. It’s a great tool to do work in your application, but only in test and development environments. That’s why I only install it in my require-dev section of my composer.json file.

Securing Laravel from Hackers

Aug 23, 2021 laravel php security

Laravel Hacker is no longer a brand. You can find my security work at MasteringLaravel.io/security

Laravel is a great framework that is pretty secure by default. However, configuration mistakes or coding errors can still leave your app open for attack. Where do you go for help?

Illustrating Why Fillable and Validated Matter in Laravel

Feb 22, 2021 laravel php security

When given a choice of methods and ways to do something, it might not be clear which way is the best. As programmers, we tend to pick the easiest, then. However, the easiest can have security implications. Let me illustrate why we should use more stringent controls in a Laravel project.

Stop Using Assert Database Has in Laravel

Apr 24, 2020 laravel php phpunit testing

Please stop using assertDatabaseHas in Laravel. There are many reasons why this is bad, and there are better options available. Let’s find out why.

Reasons Why Not to Use Doctrine with Laravel

Nov 16, 2019 laravel php

Currently, there are two pretty common packages for interacting with your database: Eloquent and Doctrine. Eloquent is part of Laravel and Doctrine, while used often on its own, is usually referenced with Symfony. If you’ve come to read this article, you’re probably versed in Doctrine and wondering why you can’t just - or shouldn’t just - use it with your new Laravel project.

Remember to Review Your Package Code for Security

Aug 12, 2019 laravel php security

Open source software is wonderful for many reasons. One of the best is we can see and inspect the software for vulnerabilities. But, far too many people actually do this. Let me demonstrate, using a Laravel package, how this lack of review might backfire and cause you grief.

Filter User Input Before Validation in Laravel

Jun 6, 2019 laravel php

Sometimes it makes sense to filter user input before it goes to validation. If you’re using controller-based validation in Laravel, this is pretty easy. But, if you’re doing your validation in request classes, your approach needs to be different.

Two Gotchas in Laravel Unit Testing

May 20, 2019 laravel php phpunit

There’s a struggle to balance the easy-to-use Laravel helpers and functions with very verbose, complicated methods in unit tests. As I’ve been relying on Laravel’s way of doing testing more, I’ve ran into a couple of gotchas that I should share.

What Version of Laravel is This?

Apr 29, 2019 composer laravel php

There are tons of ways to answer this question each with its own benefits. Let’s check out a few.

Laravel 5 Middleware that Requires JSON

Mar 18, 2019 laravel php

Laravel has a built in request helper called wantsJson() that determines if the request is requesting JSON with the Accept: application/json header. But, what if you want to only accept JSON responses? I set up a Laravel middleware that rejects anything that isn’t JSON.

Truncate MySQL Causes Implicit Commit

Feb 18, 2019 laravel mysql

I guess I should RTFM more often… but I didn’t remember (or know??) that MySQL truncate table causes an implicit commit.

Keep Data Migrations Separate from Database Migration

Jan 7, 2019 laravel mysql php

By now, you’ve probably written many database migrations in Laravel. But, then something else happens. Perhaps your business model changed, your data attributes changed or you’re just refactoring to a stronger architecture. Doesn’t matter which, you’re going to need to convert and migrate some data.

Quick Honey Pots in Laravel

Aug 18, 2018 laravel php

When someone breaches the security of a web app, sometimes it’s not discovered to weeks or months later. There are a number of tools that specialize in intrusion detection, but they may be costly or difficult to set up. Another idea is to use a canary in the coal mine or a honey pot. Here we’ll talk about the concept and then demonstrate some easy and quick methods.

Adding CSV Responses to Laravel Using Macros

Aug 3, 2018 laravel php

Laravel has a lot of the most common functionality built into the framework. However, decisions need to be made to balance the needs of the majority of use cases with the stability and agility that programmers need. No one really wants a bloated library. Because of this, you might find that you need functionality that is not directly built into Laravel. When I started working with Laravel-based CSV responses, this was the case. (This article is based on Laravel 5.6.)

Laravel 5.4 API/Request Validate Boolean

Nov 17, 2017 laravel php

For some API work in Laravel, I wanted to validate that the incoming request parameter was a boolean value. At first I tried using the built in boolean slug validator but it didn’t accept all of the ‘boolean’ values I wanted to use. (Also there were weird scenarios where string values of false were triggering as true - like what I wrote about here.

Validate Request Parameter Not Present in Laravel 5.4

Nov 17, 2017 laravel php

You can make use of guarded or fillable attributes in Eloquent models in Laravel to help control what values you might allow to be updated via your API. But, I wanted to go a step further and actually stop certain values from being passed in. You could go pretty wild with this and try to block everything, but that’s not what I did. I made this validator.

For Performance, Skip Generating Hashes in Laravel Factories

Nov 15, 2017 laravel php

This isn’t a one-size-fits-all suggestion, but it’s a start to help you think about how you actually interact with factories in Laravel. They are used for test data, and are ran very often, multiple times in a row. You don’t need as much random information as you need. (In fact, a lot of times I see people overusing Faker even.)

Laravel Pretty Print JSON Middleware

Nov 14, 2017 laravel php

For testing, I tend to use Postman - which gives you the option to view your API JSON responses in a preview mode (interactive), pretty and raw. But, the other day I heard someone saying sometimes they just want to invoke pretty print in their JSON responses without having to use an external tool and set up a whole environment.

Studly Words in Laravel

Oct 25, 2017 laravel php

In Laravel, the Support\Str class has a lot of useful methods for switching formats of strings between each other. I needed to take a hyphenated slug and change it to title case words. In Laravel land, I think this is referred to as “Studly” - because I found something very similar called Str::studly(). This converts underline or hyphenated words into a single string with capital letters. I wanted to not concatenate all of these.

Use Dependency Injection in Laravel Console Commands

Sep 23, 2017 laravel php testing

It’s important to unit test your application code - even your console commands. So many times, I’ve seen people using the Artisan facade inside of console commands to either queue up new commands or call a different command. This makes it more difficult to unit test the application - you have to rely more on fakery (requiring you to reset your application each time then) and/or integration tests.

Laravel Default Throttle Configuration and Common JWT Blacklist Vulnerable to Cache Attacks

Aug 7, 2017 laravel php security

One thing I like about Laravel is the amount of built-in functionality that is available. But when this functionality is left in default configuration (much like many default configuration items getting hacked), there can be consequences.

Easily Test JSON Keys in Laravel API Response

Jun 27, 2017 laravel php phpunit

In my Laravel application, I have an end point that will retrieve a collection of Client models. I have many other unit tests that validate that my repository returns the proper clients when requested, that my client model is sound. My last test is a feature test checks that if I retrieve a list of clients from the end point there is proper pagination and client models exist. I don’t really need to test the exact values because I know this will work - from all my other tests.

Laravel Log Database Queries Based On Environment Variable

Jun 6, 2017 laravel php

A nice feature of Laravel is the ability to add a listener to the DB object’s events (or SQL queries). I’ve seen some people add this, then comment it out when it’s done, then un-comment it if they need it again. I don’t like that - I don’t want commented code in my files (also that’s why we have version control).

Issue 404 Not Found Middleware After Pagination Limit

Jun 1, 2017 laravel php

A pet-peeve of mine is pagination that doesn’t work properly. One that I ran into lately with Laravel is related to the pagination system it has built in. I was able to request pages that were larger than the last page with no discernible error. So, I decided to write a middleware to handle this issue for all of my content.

Using Namespaces in Laravel Tinker

May 4, 2017 laravel php

I hate to admit it, but I do like Laravel’s Tinker package. Sometimes, just testing out your relationships on the command line before you go further is super helpful.

Fixing Laravel 5.4's Dependency on PHPUnit 5

Apr 14, 2017 laravel php phpunit testing

Normally, when I write unit tests, I don’t use Laravel’s facade and fakery methods. I do a lot of injection of services, but in one particular case, when working with the Queue system, I had to use the facade for faking the queue and asserting some jobs were pushed.

Laravel Command to Generate Swagger Documentation

Feb 20, 2017 laravel php

If you’re not using Swagger (or OpenAPI) yet to document your APIs, you should start. It’s pretty simple to get started - especially in PHP. I recommend using the swagger-php package - it’s pretty easy. Just use annotations, and then generate the Swagger definition when you’re done.