A collection of Laravel goodies.

Overview

Laravel Mixins

Latest Version on Packagist Build Status Quality Score Total Downloads Buy us a tree

Launcher 🚀

Hey! We've built a Docker-based deployment tool to launch apps and sites fully containerized. You can find all features and the roadmap on our website, and we are on Twitter as well!

Support

We proudly support the community by developing Laravel packages and giving them away for free. Keeping track of issues and pull requests takes time, but we're happy to help! If this package saves you time or if you're relying on it professionally, please consider supporting the maintenance and development.

Installation

Only the master branch and version 3.0 of this package are compatible with Laravel 8.0. If you're still using an older version of Laravel (or PHP < 7.4), please use the 2.x branch. Mind that older versions are no longer supported.

You can install the package via composer:

composer require protonemedia/laravel-mixins

There's no Service Provider or automatic discovery/registration of anything. All features are opt-in.

Contents

Blade Directives

Console Commands

Validation Rules

String Macros

PDF

Request

Blade Directives

You can register Blade Directives by calling the directive method on the class. You can change the name of a directive with the optional first argument.

Decimal Money Formatter

Note: This directive requires the moneyphp/money package.

Register the directive, for example by adding it to your AppSerivceProvider:

ProtoneMedia\LaravelMixins\Blade\DecimalMoneyFormatter::directive();

You can customize the name of the directive and the default currency code:

ProtoneMedia\LaravelMixins\Blade\DecimalMoneyFormatter::directive('decimals', 'EUR');

The first argument of the directive is the amount in cents. The second optional parameter is the currency.

// 0.99
@decimals(99)

// 1.00
@decimals(100)

// 100
@decimals(100, 'XTS')

Intl Money Formatter

Note: This directive requires the moneyphp/money package.

Register the directive, for example by adding it to your AppSerivceProvider:

ProtoneMedia\LaravelMixins\Blade\IntlMoneyFormatter::directive();

You can customize the name of the directive, the default currency code and the locale:

ProtoneMedia\LaravelMixins\Blade\IntlMoneyFormatter::directive('money', 'EUR', 'nl_NL');

The first argument of the directive is the amount in cents. The optional second parameter is the currency. The optional third parameter is the locale.

// € 0,99
@money(99)

// € 1,00
@money(100)

// US$ 1,00
@money(100, 'USD')

// 1 000,00 $US
@money(100, 'USD', 'fr')

Commands

Generate Sitemap

Note: This command requires the spatie/laravel-sitemap package.

You can register the command by adding it to your App\Console\Kernel file, or by calling the register method on the class.

ProtoneMedia\LaravelMixins\Commands\GenerateSitemap::register();

You can also set a custom signature:

ProtoneMedia\LaravelMixins\Commands\GenerateSitemap::register('generate-sitemap');

It generates a sitemap of your entire site and stores in in the public folder as sitemap.xml.

php artisan sitemap:generate

Validation Rules

Current password

Passes if the value matches the password of the authenticated user.

$rule = new ProtoneMedia\LaravelMixins\Rules\CurrentPassword;

Dimensions With Margin

Extension of the Dimensions rule with a margin option. Handy when you're working with ratios with repeating decimals.

use ProtoneMedia\LaravelMixins\Rules\DimensionsWithMargin;

$rule = DimensionsWithMargin::make()->ratio(20 / 9)->margin(1),

Host

Verifies if the URL matches the given hosts.

use ProtoneMedia\LaravelMixins\Rules\Host;

$rule = Host::make(['facebook.com', 'fb.me']);

In Keys

Verifies if the given key or index exists in the array.

use ProtoneMedia\LaravelMixins\Rules\InKeys;

$rule = new InKeys(['laravel' => 'Laravel Framework', 'tailwindcss' => 'Tailwind CSS framework']);

// same as

use Illuminate\Validation\Rules\In;

$rule = new In(['laravel', 'tailwindcss']);

Max Words

Passes if the values contains no more words than specified.

use ProtoneMedia\LaravelMixins\Rules\MaxWords;

$rule = MaxWords::make(250);

URL Without Scheme

Passes if the URL is valid, even without a scheme.

$rule = new ProtoneMedia\LaravelMixins\Rules\UrlWithoutScheme;

String macros

You can add new method by using the mixins.

Compact

Str::mixin(new ProtoneMedia\LaravelMixins\String\Compact);

$string = "Hoe simpeler hoe beter. Want hoe minder keuze je een speler laat, hoe groter de kans dat hij het juiste doet.";

// Hoe simpeler hoe beter. Want hoe ... de kans dat hij het juiste doet.
echo Str::compact($string);

It has an optional second argument to specify the length on each side. With the optional third argument, you can specify the sepeator.

// Hoe simpeler hoe - het juiste doet.
echo Str::compact($string, 16, ' - ');

Human Filesize

Converts a filesize into a human-readable version of the string.

Str::mixin(new ProtoneMedia\LaravelMixins\String\HumanFilesize);

$size = 3456789;

// '3.3 MB'
Str::humanFilesize($size));

Text

Note: This macro requires the html2text/html2text package.

Converts HTML to plain text.

Protone Media

"; // Protone Media Str::text($html); ">
Str::mixin(new ProtoneMedia\LaravelMixins\String\Text);

$html = "

Protone Media

"
; // Protone Media Str::text($html);

URL

Prepends https:// is the scheme is missing from the given URL.

Str::mixin(new ProtoneMedia\LaravelMixins\String\Url);

$url = "protone.media";

// https://protone.media
Str::url($url);

PDF Regeneration

Note: Requires the symfony/process package.

Regenerates the PDF content with Ghostscript.

$ghostscript = new ProtoneMedia\LaravelMixins\Pdf\Ghostscript;

$regeneratedPdf = $ghostscript->regeneratePdf(
    file_get_contents('/uploads/invoice.pdf')
);

You can specify the path of the ghostscript binary as well:

$ghostscript = new Ghostscript('gs-binary');

Convert Base64 input data to files

Add the ConvertsBase64ToFiles trait and base64FileKeys method to your form request.

use Illuminate\Foundation\Http\FormRequest;
use ProtoneMedia\LaravelMixins\Request\ConvertsBase64ToFiles;

class ImageRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    protected function base64FileKeys(): array
    {
        return [
            'jpg_image' => 'Logo.jpg',
        ];
    }

    public function rules()
    {
        return [
            'jpg_image' => ['required', 'file', 'image'],
        ];
    }
}

Now you can get the files like regular uploaded files:

$jpgFile = $request->file('jpg_image');

// Logo.jpg
$jpgFile->getClientOriginalName();

This trait supports nested data as well. You can either reference the keys by a nested array, or with a dotted notation:

class ImageRequest extends FormRequest
{
    use ConvertsBase64ToFiles;

    protected function base64FileKeys(): array
    {
        return [
            'company.logo' => 'Logo.jpg',
            'user' => [
                'avatar' => 'Avatar.jpg',
            ],
        ];
    }
}

Want to know more about this trait? Check out the blog post.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Other Laravel packages

  • Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel Form Components: Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel WebDAV: WebDAV driver for Laravel's Filesystem.
  • Laravel Eloquent Where Not: This Laravel package allows you to flip/invert an Eloquent scope, or really any query constraint.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

Treeware

This package is Treeware. If you use it in production, then we ask that you buy the world a tree to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You might also like...
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

A collection of extensions for Laravel development in Visual Studio Code

Laravel Extension Pack for Visual Studio Code Includes the basic extensions to get started with Laravel development in Visual Studio Code. Laravel Ext

A collection of open source projects built using Laravel.

Open Laravel A repository of open source projects built using Laravel. Getting Started Clone the project repository by running the command below if yo

A package to filter laravel model based on query params or retrieved model collection

Laravel Filterable A package to filter laravel model based on query params or retrived model collection. Installation Require/Install the package usin

Collection of classes you can use to standardize data formats in your Laravel application.
Collection of classes you can use to standardize data formats in your Laravel application.

Laravel Formatters This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Co

A collection of classes to be extended/used in laravel apps for quick development

laraquick A collection of classes to be extended/used in laravel applications for quick development. Introduction The library contains traits with wel

Mirror Laravel model inside Firestore collection.

Laravel Firestore Mirror This package can be used to store copy of Laravel model inside Firestore collection. Installation Install package: composer r

Collection of Google Maps API Web Services for Laravel

Collection of Google Maps API Web Services for Laravel Provides convenient way of setting up and making requests to Maps API from Laravel application.

A Collection of Providers for Laravel Socialite

A Collection of Providers for Laravel Socialite Documentation Full documentation for using these providers can be found at the Documentation. Contribu

Laravel-hours-helper - Creates a Collection of times with a given interval.

Laravel Hours Helper With laravel-hours-helper you can create a collection of dates and/of times with a specific interval (in minutes) for a specific

A query database collection for use with Laravel Pipeline

A query database collection for use with Laravel Pipeline This package contains a collection of class that can be used with Laravel Pipeline. Let's se

A collection of pre-made simple Laravel Blade form components.
A collection of pre-made simple Laravel Blade form components.

Laravel Form Components Library A collection of pre-made simple Laravel Blade form components. Installation & setup You can install the package via co

[READ-ONLY] Collection library in CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Collection Library The collection classes provide a set of tools to manipulate arrays or Traversable objects. If you have ever used underscore

[DEPRECATED] Collection of PSR-7 middlewares

This package is deprecated in favor of the new PSR-15 standard. Check it out here psr7-middlewares Collection of PSR-7 middlewares. Requirements PHP

Collection pipeline library for PHP

Knapsack Collection pipeline library for PHP Knapsack is a collection library for PHP = 5.6 that implements most of the sequence operations proposed

SecLists is the security tester's companion. It's a collection of multiple types of lists used during security assessments, collected in one place. List types include usernames, passwords, URLs, sensitive data patterns, fuzzing payloads, web shells, and many more.
Library that provides collection, processing, and rendering functionality for PHP code coverage information.

phpunit/php-code-coverage Provides collection, processing, and rendering functionality for PHP code coverage information. Installation You can add thi

A yii-log-target of collection(Bark、Chanify、DingTalk、FeiShu、ServerChan、WeWork、XiZhi).

A yii-log-target of collection(Bark、Chanify、DingTalk、FeiShu、ServerChan、WeWork、XiZhi). - 集合了多种 yii-log-target(Bark、Chanify、钉钉群机器人、飞书群机器人、Server 酱、企业微信群机器人、息知)。

Comments
  • Trait ConvertBase64ToFiles does not work with nested data

    Trait ConvertBase64ToFiles does not work with nested data

    Hey :wave: Unfortunately, current implementation does not work correctly. Let's assume that we have the following request:

    {
        "data": {
            "attributes": {
                "avatar": "YW55dGhpbmc="
            }
        }
    }
    

    Now, when you're using the Form Request in your controller, the base64 encoded data won't get properly validated. In addition, calling the file method on the $request instance will give you null.

    The reason for this is that Laravel uses "dot" notation to access the arrays, while Symfony's ParameterBag treats dotted keys as they are. In result there is a file with the data.attributes.avatar key (so $request->file('data.attributes.avatar') returns null; you should probably use $request->files->get('data.attributes.avatar') instead), and at the same time validation will fail cause there is no file within the input attributes.

    There is more. Removing parameter (https://github.com/protonemedia/laravel-mixins/blob/master/src/Request/ConvertsBase64ToFiles.php#L51) won't work either in this case. You should replace whole input for the request instead. For example:

    $this->replace(Arr::except($this->input(), $key));
    

    On the other hand, if you'd like to support accessing file using "dot" notation and validation, it should probably look like:

    $attributes = $this->input();
    Arr::set($attributes, $key, $uploadedFile);
    
    $this->replace($attributes);
    

    Then you could overwrite the "file" method in the ConvertsBase64ToFiles trait:

    public function file($key = null, $default = null)
    {
        return $this->has($key) ? $this->input($key) : parent::file($key, $default);
    }
    
    bug 
    opened by andrzejkupczyk 4
  • How to get real file extention when using base64 string

    How to get real file extention when using base64 string

    Hi Thanks for your good package. I'm using the base64 file option but I want to get real file extension. according to docs I make a request and put this code inside it:

    protected function base64FileKeys(): array
        {
            return [
                'file' => time() . '_Ticket.jpg',    // i want to get file extension dynamically not hard coded!
            ];
        } 
    

    it's work and ok but all of my files are not jpg! I want to use pdf or png too. so how can I get real file extension (uploaded file) and put it to mentioned code?

    opened by mrmmg 1
Releases(3.4.0)
Owner
Protone Media
We are a Dutch software company that develops apps, websites, and cloud platforms. As we're building projects, we gladly contribute to OSS by sharing our work.
Protone Media
A fork of Laravel Valet to work in Linux.

Introduction Valet Linux is a Laravel development environment for Linux minimalists. No Vagrant, no /etc/hosts file. You can even share your sites pub

Carlos Priego 1.2k Dec 31, 2022
Dockerized version of Laravel Homestead

laraedit-docker Dockerized version of Laravel Homestead Documentation For now you can check out the wiki for details on using the container. Once the

LaraEdit 444 Dec 7, 2022
Docker Containers for simple Laravel development.

Docker containers of Laravel development. Docker Containers for simple Laravel development. Prerequisites This package only works for Linux users righ

Steve Azzopardi 14 May 19, 2022
Laravel 5 with Dockerized Gulp, PHP-FPM, MySQL and nginx using docker-compose

docker-laravel Laravel 5 with Dockerized PHP-FPM, MySQL and nginx using docker-compose Usage Get Composer docker-compose run --rm phpnginx curl -O htt

Harsh Vakharia 83 Feb 8, 2022
A package that allows you to generate simple and fast Docker configurations for your Laravel application!

A package that allows you to generate simple and fast Docker configurations for your Laravel application!

Lucas Nepomuceno 3 Oct 8, 2022
Docker-based workflow management system for Laravel

DevOption Workflows Workflows is a Docker-based workflow management system for Laravel applications. Installation You can install the package via comp

devoption.io 1 Jan 5, 2022
ServD - a Docker PHP development environment heavily inspired by Laravel Valet and Laradock

ServD ServD is a Docker PHP development environment heavily inspired by Laravel Valet and Laradock, it supports multiple projects within a working dir

Matt Clinton 2 May 13, 2022
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel

Underscore.php The PHP manipulation toolbelt First off : Underscore.php is not a PHP port of Underscore.js (well ok I mean it was at first). It's does

Emma Fabre 1.1k Dec 11, 2022
A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDowell

PHPAlgorithms A collection of common algorithms implemented in PHP. The collection is based on "Cracking the Coding Interview" by Gayle Laakmann McDow

Doğan Can Uçar 921 Dec 18, 2022
A set of useful Laravel collection macros

A set of useful Laravel collection macros This repository contains some useful collection macros. Spatie is a webdesign agency based in Antwerp, Belgi

Spatie 1.5k Dec 31, 2022