Posts

Since 2024
Microsoft Clarity Integration for Laravel
Microsoft Clarity Integration for Laravel

The clarity-laravel package lets you easily integrate Microsoft Clarity into your Laravel application. I wasn't familiar with Clarity before seeing this package—it's a GDPR and CCPA-ready product that you embed in your application, and it can capture how people use your site: Heatmaps with Microsoft Clarity The main features that Clarity offers your application include: Heatmaps Session recordings Insights Google Analytics integration Integration is easy with this package: you set up a few environment variables and include the package's Blade component in your application's layout file: <head> <x-clarity::script /> </head> This package will enable Clarity based on the CLARITY_ENABLED environment variable value in the clarity.php configuration file. If setting the environment variable isn't flexible enough, you can set the :enabled property on the component with a variable boolean value that you define: <x-clarity::script :enabled="$enabled" /> While you could easily integrate the Clarity embed code in your application directly, this package takes care of it for you, and you can start collecting data in minutes. You can learn more about this package, get full installation instructions, and view the source code on GitHub. You can learn more about Clarity from the Microsoft Clarity documentation. You can also see a live demo The post Microsoft Clarity Integration for Laravel appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Apply Dynamic Filters to Eloquent Models with the Filterable Package
Apply Dynamic Filters to Eloquent Models with the Filterable Package

Filterable is a Laravel package by Jerome Thayananthajothy that enhances Laravel queries with adaptable, customizable filters and intelligent caching to improve both performance and functionality. The main features of this package include: Dynamic Filtering: Apply filters based on request parameters with ease. Caching: Improve performance by caching query results. User-specific Filtering: Easily implement filters that depend on the authenticated user. Custom Filter Methods: Extend the class to add your own filter methods. Defining Filter classes is at the center of this package, where you can create methods that can apply filtering to Eloquent queries. The package includes a make:filter Artisan command to generate a filter in your app's App\Filters namespace. Here's an example of a filter from the package's README: namespace App\Filters; use Filterable\Filter; use Illuminate\Database\Eloquent\Builder; class PostFilter extends Filter { protected array $filters = ['status', 'category']; protected function status(string $value): Builder { return $this->builder->where('status', $value); } protected function category(int $value): Builder { return $this->builder->where('category_id', $value); } } Given a PostFilter, you can utilize this class in a controller with the Post model to filter models based on the HTTP query params: public function index(Request $request, PostFilter $filter) { // i.e., /posts?status=active&category_id=2 $query = Post::filter($filter); $posts = $request->has('paginate') ? $query->paginate($request->query('per_page', 20)) : $query->get(); return response()->json($posts); } You can learn more about this package, get full installation instructions, and view the source code on GitHub. The post Apply Dynamic Filters to Eloquent Models with the Filterable Package appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Property Hooks Get Closer to Becoming a Reality in PHP 8.4
Property Hooks Get Closer to Becoming a Reality in PHP 8.4

The Property Hooks RFC passed a significant milestone, getting an overwhelmingly positive 34 "yes" votes and only 1 "no" vote. That's well above the required 2/3 majority required to pass. What are property hooks in PHP? Here's the proposal summary from the RFC: Developers often use methods to wrap and guard access to object properties. There are several highly common patterns for such logic, which in practice may be verbose to implement repeatedly. Alternatively, developers may use __get and __set to intercept reads and writes generically, but that is a sledge-hammer approach that intercepts all undefined (and some defined) properties unconditionally. Property hooks provide a more targeted, purpose-built tool for common property interactions... This RFC introduces two “hooks” to override the default “get” and “set” behavior of a property. Although not included in this initial version, the design includes the ability to support more hooks in the future. Property hooks are inspired by languages like Kotlin, C#, and Swift, and the syntax includes two syntax variants that resemble short and multi-line closures: class User implements Named { private bool $isModified = false;   public function __construct( private string $first, private string $last ) {}   public string $fullName { // Override the "read" action with arbitrary logic. get => $this->first . " " . $this->last;   // Override the "write" action with arbitrary logic. set { [$this->first, $this->last] = explode(' ', $value, 2); $this->isModified = true; } } } The syntax doesn't require that both hooks always be defined together; in fact, here's an example of only defining set from the RFC: class User { public string $name { set { if (strlen($value) === 0) { throw new ValueError("Name must be non-empty"); } $this->name = $value; } }   public function __construct(string $name) { $this->name = $name; } } You can read all the details about Property Hooks in PHP in the RFC. This feature looks likely to drop in PHP 8.4. The implementation is already a draft pull request if you want to see the discussion and progress of this feature. The post Property Hooks Get Closer to Becoming a Reality in PHP 8.4 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Asserting Exceptions in Laravel Tests
Asserting Exceptions in Laravel Tests

Laravel's recent release of Laravel 11.4 introduced the Exceptions facade, which adds conveniences around asserting exceptions in Laravel's exception handler. Before this release, I would typically use the $this->withoutExceptionHandling() to assert that a specific exception happened during an HTTP test: use App\Exceptions\WelcomeException; $this->withoutExceptionHandling(); try { $this->get('/'); } catch (WelcomeException $e) { $this->assertEquals('Woops, there was an issue with your request!', $e->getMessage()); return; } $this->fail(sprintf('The expected "%s" exception was not thrown.', WelcomeException::class)); When you expect a request to not throw any exceptions, using withoutExceptionHandling cuts out the middleman when you're debugging why an error is happening when you don't expect it. The above code is tedious to write, because it manually captures the exception, makes assertions about the exception, and calls return to avoid the manual $this->fail() call. The manual failure will catch situations when the test doesn't throw an exception when expected. If $this->fail() is called in the above scenario, here's what the output would look like: $ phpunit There was 1 failure: 1) Tests\Feature\ExampleTest::test_the_application_returns_a_successful_response The expected "App\Exceptions\WelcomeException" exception was not thrown. /app/tests/Feature/ExampleTest.php:33 Laravel's Exceptions Facade Let's look at how the new Exceptions facade can simplify our test; the first example, rewritten, would look as follows: use Illuminate\Support\Facades\Exceptions; Exceptions::fake(); $this->get('/'); Exceptions::assertReported(function (WelcomeException $e): bool { return $e->getMessage() === "Woops, there was an issue with your request!"; }); Using the Exceptions facade gives us the bonus of not having to capture an exception to assert things manually. Said another way, the test can keep Laravel's exception handler in place but still be able to assert exceptions that happened during a request. If we want to be sure that a test doesn't throw a specific exception or doesn't throw any exceptions, period, the new facade has our back: Exceptions::assertNotReported(WelcomeException::class);   Exceptions::assertNothingReported(); If the exception handler does not report the WelcomeException, the test output would give us a nicely formatted message: $ phpunit There was 1 failure: 1) Tests\Feature\ExampleTest::test_the_application_returns_a_successful_response The expected [App\Exceptions\WelcomeException] exception was not reported. While there may be times when you don't want to fake Laravel's exception handler, when testing edge cases, the new Exceptions facade is tremendously helpful and cleans up our code: Exceptions::assertReported(WelcomeException::class); Exceptions::assertReportedCount($count); Exceptions::assertNotReported(WelcomeException::class); Exceptions::assertNothingReported(); Exceptions::throwFirstReported(); To learn more about the Exceptions facade, check out Laravel’s documentation. The post Asserting Exceptions in Laravel Tests appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Basset is an alternative way to load CSS & JS assets
Basset is an alternative way to load CSS & JS assets

It's 2024 and I'm calling it - Server-Side Rendering has officially made a comeback: in Laravel, where Livewire now has 46.000 installs per day in Ruby on Rails with Hotwire in Phoenix with Liveview in web dev in general with HTMX Now that "the old has become the new"... maybe it's time to re-visit another practice we've adopted from the Javascript ecosystem. Maybe it's time to... drop the build step? Crazy, I know! But there's been a lot of talk about no-build Laravel setups in my bubble. And there's one place where people invariably get stuck - "If we drop NPM, what do we do about JS dependencies?". Here's my answer to that - or at least an important first step. What if instead of installing our JS dependencies with a package manager like NPM and bundling them... we just load them directly from the URL? You know... similarly to what the founder of NodeJS himself is doing in Deno. He has publicly said NPM has become a mess and created an alternative for the JS ecosystem... why don't we do the same for the Laravel ecosystem? If you dream about the simple days when you could just load assets using asset(), try Basset - a better asset helper for Laravel. You just replace asset() with basset() to gain some super-powers: assets from CDNs are downloaded to /storage and served from there; vendor assets become possible to load; non-public assets become possible to load; it becomes impossible to double-load an asset during a request; In short, basset() removes the limitations of asset(), allowing you to load any asset you want, safely. That means in addition to this: <link href="{{ asset('path/to/public/file.css') }}"> You can safely do this: <script src="{{ basset(storage_path('file.js')) }}"> <script src="{{ basset(base_path('vendor/org/package/assets/file.js')) }}"> <script src="{{ basset('https://cdn.com/path/to/file.js') }}"> This is a very simple solution for those who want to load assets "the old easy way" in their Laravel projects, because it solves a few problems with that "old way": Don't want GDPR issues? ✅ Solved - Basset will cache the asset to /storage and serve it from there. Don't want to depend on a CDN being up? ✅ Solved - the assets can be cached upon deployment (or on commit). Don't want to load an asset twice, if used by multiple components on that page? ✅ Solved - automatically. Concerned about the performance of loading multiple JS files vs one big bundle? ✅ Solved by HTTP/2, which makes it performant to load multiple Javascript assets on a single page. Granted, Basset may not be a perfect asset loading solution. At least not for every project. It's only been around for 12 months, so it's missing things like importmaps and the like, to make it a 1-to-1 alternative to NPM and Deno's way. But it has been around for 12 months and has proven its usefulness. Perhaps... it's time for us to take another look at how we load assets in our Laravel projects. Maybe we'll discover the simple way... is a good way. For some projects, at least. I suggest you give Basset a try. After all: it's been in production for 1 year already; it's maintained by the Backpack team; it's got 110.000 downloads already; it's under MIT License; If you have feedback on it, open an issue on Github and tell the team about it. A v2 is due soon enough, and we want to incorporate as much feedback as possible. The post Basset is an alternative way to load CSS & JS assets appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4
Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4

This week, the Laravel team released v11.4, with reversible form Prompts, a new Exceptions facade, Enum support in the Collection::mapInto() method, and more. Introduce the Exceptions Facade Nuno Maduro contributed the Exceptions facade: The Exceptions facade provides a consistent way to test exceptions in Laravel applications. Here is the list of methods that the Exceptions facade provides: assertReported assertReportedCount assertNotReported assertNothingReported throwOnReport throwFirstReported Here's an example from the pull request description illustrating the Exceptions::fake() method and assertReported() method: use Illuminate\Support\Facades\Exceptions; test('example', function () { Exceptions::fake(); $this->post('/generate-report', [ 'throw' => 'true', ])->assertStatus(503); // Service Unavailable Exceptions::assertReported(ServiceUnavailableException::class); // or Exceptions::assertReported(function (ServiceUnavailableException $exception) { return $exception->getMessage() === 'Service is currently unavailable'; }); }); Read our Asserting Exceptions in Laravel Tests article for more details. Livewire-style Directives @devajmeireles contributed the ability to use Boolean-style directives, without any defined value: {{-- Before --}} <x-fetch wire:poll /> {{-- Generates this HTML --}} <div ... wire:poll="wire:poll" /> {{-- After --}} <x-fetch wire:poll /> <div ... wire:poll /> Reversible Forms in Prompts Luke Downing contributed form prompts, which are a grouped set of prompts for the user to complete. Forms include the ability to return to previous prompts and make changes without having to cancel the command and start over: use function Laravel\Prompts\form;   $responses = form() ->text('What is your name?', required: true) ->password('What is your password?', validate: ['password' => 'min:8']) ->confirm('Do you accept the terms?') ->submit(); Here's an example of using values from previous responses: $responses = form() ->text('What is your name?', name: 'name') ->add(fn () => select('What is your favourite language?', ['PHP', 'JS']), name: 'language') ->add(fn ($responses) => note("Your name is {$responses['name']} and your language is {$responses['language']}")) ->submit(); See Pull Request #118 in the laravel/prompts project for implementation details. This feature is already documented in the Prompts documentation. Add Support for Enums on mapInto Collection Method Luke Downing contributed support for Enums on the Collection::mapInto() method, which allows you to build up enums from an array of values: public function store(Request $request) { $request->validate([ 'features' => ['array'], 'features.*' => [new Enum(Feature::class)], ]); $features = $request ->collect('features') ->mapInto(Feature::class); if ($features->contains(Feature::DarkMode)) { // ... } } An afterQuery() Hook Günther Debrauwer contributed an afterQuery() hook to run code after running a query: $query->afterQuery(function ($models) { // Make changes to the queried models ... }); Here's a use-case example from the pull request's description: // Before public function scopeWithIsFavoriteOf($query, ?User $user = null) : void { if ($user === null) { return $query; } $query->addSelect([ // 'is_favorite' => some query ... ]); } $products = Product::withIsFavoriteOf(auth()->user())->get(); if (auth()->user() === null) { $products->each->setAttribute('is_favorite', false); } And here's the code using the afterQuery() hook: // After public function scopeWithIsFavoriteOf($query, ?User $user = null) : void { if ($user === null) { $query->afterQuery(fn ($products) => $products->each->setAttribute('is_favorite', false)); return; } $query->addSelect([ // 'is_favorite' => some query ... ]); } Product::withIsFavoriteOf(auth()->user())->get(); Release notes You can see the complete list of new features and updates below and the diff between 11.3.0 and 11.4.0 on GitHub. The following release notes are directly from the changelog: v11.4.0 [11.x] Apc Cache - Remove long-time gone apc_* functions by @serpentblade in https://github.com/laravel/framework/pull/51010 [11.x] Allowing Usage of Livewire Wire Boolean Style Directives by @devajmeireles in https://github.com/laravel/framework/pull/51007 [11.x] Introduces Exceptions facade by @nunomaduro in https://github.com/laravel/framework/pull/50704 [11.x] afterQuery hook by @gdebrauwer in https://github.com/laravel/framework/pull/50587 Fix computed columns mapping to wrong tables by @maddhatter in https://github.com/laravel/framework/pull/51009 [11.x] improvement test for string title by @saMahmoudzadeh in https://github.com/laravel/framework/pull/51015 [11.x] Fix failing afterQuery method tests when using sql server by @gdebrauwer in https://github.com/laravel/framework/pull/51016 [11.x] Fix: Apply database connection before checking if the repository exist by @sjspereira in https://github.com/laravel/framework/pull/51021 [10.x] Fix error when using orderByRaw() in query before using cursorPaginate() by @axlon in https://github.com/laravel/framework/pull/51023 [11.x] Add RequiredIfDeclined validation rule by @timmydhooghe in https://github.com/laravel/framework/pull/51030 [11.x] Adds support for enums on mapInto collection method by @lukeraymonddowning in https://github.com/laravel/framework/pull/51027 [11.x] Fix prompt fallback return value when using numeric keys by @jessarcher in https://github.com/laravel/framework/pull/50995 [11.x] Adds support for int backed enums to implicit Enum route binding by @monurakkaya in https://github.com/laravel/framework/pull/51029 [11.x] Configuration to disable events on Cache Repository by @serpentblade in https://github.com/laravel/framework/pull/51032 Revert "[11.x] Name of job set by displayName() must be honoured by S… by @RobertBoes in https://github.com/laravel/framework/pull/51034 chore: fix some typos in comments by @laterlaugh in https://github.com/laravel/framework/pull/51037 Name of job set by displayName() must be honoured by Schedule by @SCIF in https://github.com/laravel/framework/pull/51038 Fix more typos by @szepeviktor in https://github.com/laravel/framework/pull/51039 [11.x] Fix some doc blocks by @saMahmoudzadeh in https://github.com/laravel/framework/pull/51043 [11.x] Add @throws ConnectionException tag on Http methods for IDE support by @masoudtajer in https://github.com/laravel/framework/pull/51066 [11.x] Add Prompts textarea fallback for tests and add assertion tests by @lioneaglesolutions in https://github.com/laravel/framework/pull/51055 Validate MAC per key by @timacdonald in https://github.com/laravel/framework/pull/51063 [11.x] Add throttle method to LazyCollection by @JosephSilber in https://github.com/laravel/framework/pull/51060 [11.x] Pass decay seconds or minutes like hour and day by @jimmypuckett in https://github.com/laravel/framework/pull/51054 [11.x] Consider after_commit config in SyncQueue by @hansnn in https://github.com/laravel/framework/pull/51071 [10.x] Database layer fixes by @saadsidqui in https://github.com/laravel/framework/pull/49787 [11.x] Fix context helper always requiring $key value by @nikspyratos in https://github.com/laravel/framework/pull/51080 [11.x] Fix expectsChoice assertion with optional multiselect prompts. by @jessarcher in https://github.com/laravel/framework/pull/51078 The post Reversible Form Prompts and a New Exceptions Facade in Laravel 11.4 appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.

The Random package generates cryptographically secure random values
The Random package generates cryptographically secure random values

The Random package by Stephen Rees-Carter, generates cryptographically secure random values in a range of different formats through a simple helper package for PHP. Here is why this package was created: Something I commonly encounter during my security audits (especially on older codebases) is insecure randomness, usually in places where security is required. It’s usually using some form of rand(), often injected inside md5() to generate a random hash, combined with str_shuffle() to generate new passwords, or used to make an One-Time Password (OTP) with rand(100_000, 999_999). The problem is rand() is not cryptographically secure, and neither is mt_rand(), mt_srand(), str_shuffle(), array_rand(), or of the other insecure functions available in PHP. We can’t simply declare these methods insecure, drop the mic, and walk away. Instead, we need to provide secure alternatives - so rather than simply saying “don’t use rand() in that way”, we can say “here’s a secure method you can use instead”! Here are some examples of what you can do with this Random package: Random One-Time Password (Numeric fixed-length OTPs) Generate a random numeric one-time password (OTP) of $length digits: $otp = Random::otp(int $length): string; Useful for generating OTPs for SMS or email verification codes. Random String Generate a random string of $length characters, which includes characters from the enabled character types. By default, it will randomly select characters and not guarantee any specific character types are present. If you require one of each character to be included, you can set $requireAll = true. // Primary method $string = Random::string( int $length = 32, bool $lower = true, bool $upper = true, bool $numbers = true, bool $symbols = true, bool $requireAll = false ): string; The string method also comes with nice wrappers for common use cases: // Random letters only $letters = Random::letters(int $length = 32): string; // Random alphanumeric (letters and numbers) token string $token = Random::token(int $length = 32): string; // Random letters, numbers, and symbols (i.e. a random password). $password = Random::password(int $length = 16, bool $requireAll = false): string; // Random alphanumeric token string with chunks separated by dashes, making it easy to read and type. $password = Random::dashed(int $length = 25, string $delimiter = '-', int $chunkLength = 5, bool $mixedCase = true): string; Shuffle Array, String, or Collection Securely shuffle an array, string, or Laravel Collection, optionally preserving the keys. $shuffled = Random::shuffle( array|string|\Illuminate\Support\Collection $values, bool $preserveKeys = false ): array|string|\Illuminate\Support\Collection; And more Visit the official package page on GitHub for complete details, and also check out the announcement post. The post The Random package generates cryptographically secure random values appeared first on Laravel News. Join the Laravel Newsletter to get Laravel articles like this directly in your inbox.