Giter Club home page Giter Club logo

laravel-useful-additions's Introduction

A collection of useful Laravel additions!

Latest Version on Packagist Tests Check & fix styling License

Here we will share some useful Laravel additions we need in our daily work.

Traits

Commands

Installation

You can install the package via composer:

composer require laracraft-tech/laravel-useful-additions

Then publish the config file with:

php artisan vendor:publish --tag="useful-additions-config"

Traits

UsefulEnums

This trait is only available with PHP 8.1 or higher installed.


names, values, array

This could be very handy if you like to loop over all of your enum types, or you maybe want to use the enum as an array, for instance in a migration.

use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulEnums;

enum PaymentType: int
{
    use UsefulEnums;

    case Pending = 1;
    case Failed = 2;
    case Success = 3;
}

PaymentType::names();   // return ['Pending', 'Failed', 'Success']
PaymentType::values();  // return [1, 2, 3]
PaymentType::array();   // return ['Pending' => 1, 'Failed' => 2, 'Success' => 3]

UsefulScopes


selectAllBut

Select all columns but given excluded array.

use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes;

$class = new class extends Model
{
    use UsefulScopes;

    protected $timestamps = false;
    protected $table = 'scope_tests';
};

$class->create([
    'foo' => 'foo',
    'bar' => 'bar',
    'quz' => 'quz',
]);

$class::query()->selectAllBut(['foo'])->first()->toArray();
// return ['bar' => 'bar', 'quz' => 'quz']

Note: Since you can't do a native "select all but x,y,z" in mysql, we need to query (and cache) the existing columns of the table, and then exclude the given columns which should be ignored (not selected) from the existing columns.

Cache: Column names of each table will be cached until contents of migrations directory is added or deleted. Modifying the contents of files inside the migrations directory will not re-cache the columns. Consider to clear the cache whenever you make a new deployment/migration!


fromToday, fromYesterday

Select all entries created today or yesterday.

use LaracraftTech\LaravelUsefulAdditions\Traits\UsefulScopes;

$class = new class extends Model
{
    use UsefulScopes;

    protected $timestamps = true;
    protected $table = 'scope_tests';
};

$class->create(['foo' => 'foo1', 'bar' => 'bar1', 'quz' => 'quz1']);
$class->create(['foo' => 'foo2', 'bar' => 'bar2', 'quz' => 'quz2', 'created_at' => now()->yesterday()]);

$class::select('foo')->fromToday()->first()->toArray(); // return ['foo' => 'foo1']
$class::select('foo')->fromYesterday()->first()->toArray(); // return ['foo' => 'foo2']

RefreshDatabaseFast


This is a trait which makes the migration of your database in your test suite much, much faster! The base idea comes from Mayahi. It basically only migrates your database if the migration files has changed. So the first migrate:fresh takes a while (depending on how many migrations you have), and then it's incredible fast.

Optionally you can set USEFUL_ADDITIONS_SEED_AFTER_FAST_DB_REFRESH to true if you like to seed your database after the migration.

Also make sure to add the .phpunit.database.checksum to your .gitignore file!

Pest:

use LaracraftTech\LaravelUsefulAdditions\Traits\RefreshDatabaseFast;

uses(RefreshDatabaseFast::class);

it('does_something', function() {
    // ...
});

PHPUnit:

use LaracraftTech\LaravelUsefulAdditions\Traits\RefreshDatabaseFast;
use Tests\TestCase;

class MyTest extends TestCase
{
    use RefreshDatabaseFast;
    
    /** @test **/
    public function it_does_something()
    {
        // ...
    }
}

Commands

db:truncate


This command truncates all the tables of your current database connection. Checkout --help to see arguments and options. It for instance, lets you also truncate only specific tables or disable foreigen key checks or maybe run in force mode.

php artisan db:truncate
INFO  Start truncating tables.

Truncating table: failed_jobs .............................................. 135ms DONE
Truncating table: migrations ................................................ 87ms DONE
Truncating table: password_reset_tokens ..................................... 79ms DONE
Truncating table: personal_access_tokens .................................... 86ms DONE
Truncating table: users ..................................................... 78ms DONE

INFO  Finished truncating tables.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

laravel-useful-additions's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar sairahcaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

laravel-useful-additions's Issues

RefreshDatabaseFast fails after first run

In the DatabaseMigrations trait:

/**
     * Define hooks to migrate the database before and after each test.
     *
     * @return void
     */
    public function runDatabaseMigrations()
    {
        $this->beforeRefreshingDatabase();
        $this->refreshTestDatabase();
        $this->afterRefreshingDatabase();

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:rollback');

            RefreshDatabaseState::$migrated = false;
        });
    }

The "migrate:rollback" call is basically reverting all of the fresh migration, so the second time the tests run, the checksum matches while the database is completely empty.

Not sure if this is due to a code update, or if there's a best practices way of avoiding this.

For now, I've overridden the runDatabaseMigrations method to remove the rollback command.

RefreshDatabaseFast is seeding before migrating.

I couldn't figure out why seeding was not working, but in the runMigrationsIfNecessary method of the Trait, you are first seeding (upon checking the configuration parameter, that's correct) but then you're doing a migrate fresh completely emptying the seeding :)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.