Wednesday, 30 October 2024

PHP Laravel

Using MySQL

#choose MySql and do not run migration when ask
laravel new example-app
   
# change .env with mysql user name and password

# run migration
php artisan migrate

Create a new table

To create new table and new model. Here we use task model as example.


# create a migration and a model class. migration script is in 
# this folder database/migrations
# model class is in this folder app/Models
php artisan make:model Task -m

The next step is to edit the migration script to add new columns

public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string("title");
            $table->text("description");
            $table->text("long_description")->nullable();
            $table->boolean("completed")->default(false);
        });
    }

The last step is run migration to create table tasks.

php artisan migrate

(optional) seed the table

To make seed work, need to HasFactory trait in model class

use Illuminate\Database\Eloquent\Factories\HasFactory;
class Payment extends Model
{
    use HasFactory;

    //
}

# create a factory
php artisan make:factory TaskFactory --model=Task

# seed database
php artisan db:seed

Start local server

# after run, go to http://localhost:8000
php artisan serve

Show route

 php artisan route:list

Start command line

php artisan tinker