DEV Community

Cover image for Laravel 9: Stub Migrations!
Reza Khademi
Reza Khademi

Posted on • Edited on

8 2

Laravel 9: Stub Migrations!

Soon, Laravel 9 wil release and there are some new features that we can use them.

This series is going to be a sequel about Laravel framework version 9 and in each article we will review a new feature!

1. Laravel 9: Stub Migration

Since Laravel 8.37, there is no need to create a migration with a specific class name. If we have so many migrations and probably forgot about their class name or we are afraid to have collisions in new migration, this feature coming handy and nice.

According to the pull request on github this feature is backward compatible.

So how do we can create it?

Just run this command: php artisan make:migration and it will give you this:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


return new class extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {

            $table->string('nick_name')->nullable();
        });
    }
};

Enter fullscreen mode Exit fullscreen mode

It's an anonymous migration which will do any things to any model you decide, just you have no worries about class names anymore.

That's it... Any question?

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (2)

Collapse
 
lordisp profile image

but how can I call the up method of a specific migration?

before:

(new FooBar)->up();
Enter fullscreen mode Exit fullscreen mode

after:

???
Enter fullscreen mode Exit fullscreen mode
Collapse
 
thiagorb profile image
Thiago Romão Barcala • Edited

@lordisp Firstly, your "before" wouldn't work, because migration classes couldn't be autoloaded. You would need to require/include the file manually, and it could be done only once, otherwise PHP would panic while trying to define the class for the second time. You would also pollute your global namespace.

Secondly, did you ever need to do that? I doubt...

You can do what you described with the following snippet:

$migration = require('app/database/migrations/2019_01_01_000000_add_content_to_posts_table.php');
$migration->up();
Enter fullscreen mode Exit fullscreen mode

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay