Skip to content

Instantly share code, notes, and snippets.

@benfurfie
Last active December 4, 2022 23:06
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benfurfie/8e8c60ed3c02a0fe33b607d929fcb708 to your computer and use it in GitHub Desktop.
Save benfurfie/8e8c60ed3c02a0fe33b607d929fcb708 to your computer and use it in GitHub Desktop.
Laravel Cheatsheet

Laravel Cheatsheet

Artisan

Making a model with a controller, migration, as a resource

php artisan make:model Name -mcr

Factories

How do I use faker with enums?

'something' => $faker->randomElement(['foo' ,'bar', 'baz'])

How do I conditionally set values with faker?

$factory->define(Model::class, function (Faker $faker) {
    /**
     * Set up the type of organisation.
     */
    $type = $faker->randomElement(['organisation', 'charity']);

    /**
     * Set the charity number to null by default.
     */
    $charityNumber = null;

    /**
     * Check the type of organisation, and if charity, create dummy number.
     */
    if($type == 'charity') {
        $charityNumber = $faker->numberBetween(100000,999999) . '-0';
    }

    return [
        'name' => $faker->company,
        'type' => $type,
        'charityNumber' => $charityNumber
    ];
});

How do I ensure data generated by faker is unique?

You can ensure that any data randomly generated by faker is unique by using the unique() method, like so:

return [
    'email' => $faker->unique()->email,
]

Testing

When using Laravel 5.8 and above, and you want to use the setUp method, you need to return it as : void. E.g.

class ProductTest extends TestCase
{
    protected $product;

    public function setUp() : void
    {
        $this->product = new Product();
        $this->product->manufacturer = 'Apple';
        $this->product->name = 'iPhone 11 Pro';
        $this->product->price = '4999';
    }
    
    public function testProductHasName()
    {  
        $this->assertEquals('iPhone 11 Pro', $this->product->name());
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment