artisan dbコマンドはLaravelのプロジェクトのデータベースの情報を表示してくれるコマンドでしたが、artisan modelはLaravelのModelのためのコマンドです。見てみましょう。
model:show
※初めての方は、まずartisan dbコマンド読んでください。準備が要ります。
すでに準備がされた方は、早速artisan modelを実行しましょう。
$ php artisan model:show User
と実行すると、
有用な情報がいっぱいありますが、説明が必要ですね。
Attributes
artisan db:table usersの実行においてもDBテーブルの項目やデータタイプが表示されますが、上ではそれらに加えて、fillable、hidden、castの属性もいくつかの項目で表示されています。
以下のModelの定義を見るとそれらの属性が上で表示されているがわかります。
...
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
さらに、accessorの定義を加えてみましょう。
...
class User extends Authenticatable
{
...
public function getNameAttribute()
{
return Str::upper($this->attributes['name']); // 大文字に変換
}
}
再度実行すると、
表示されていますね。
Relations
上のRelationsのセクションでは、HasApiTokensとNotifiableのトレイトで定義されているRelationが表示されていますが、それでは少しわかりづらいので、PostsのModelを作成して、以下のようにUsersにRelationを定義します。
...
class User extends Authenticatable
{
...
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
再度実行すると、
しっかり表示されていますね。
Observers
これは、モデルに関連するDB処理イベントのメソッドを表示します。例えば、以下のようにDBレコード作成後の処理を定義して、
...
class User extends Authenticatable
{
...
public static function booted()
{
static::created(function ($user) {
// レコードが作成された後に実行する処理
});
}
}
再度実行すると、
最も便利なartisan dbコマンドの使い方
前回の説明において、このコマンドで一番大事なことを忘れていました。というか、最近になってたまたまオプションなしで実行して気づいたことです。
php artisan dbとオプションなしで実行すると、
$ php artisan db mysql: [Warning] Using a password on the command line interface can be insecure. Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 369 Server version: 8.0.33 MySQL Community Server - GPL Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql>
そうなんです。mysqlのコマンドを.envで指定したログインとパスワードを使って実行してくれるのです。便利ですね。
最後に
artisanコマンドはLaravelを使う開発者にとってなくてはならない重要なツールですが、機能が多すぎてとてもオプションを覚えることができません。まして毎回バージョンごとに数が増えるし。
しかし、とても便利なサイト見つけました。
ドロップダウンで、バージョンも変えることもできます。
メルマガ購読の申し込みはこちらから。




