Laravel: forPage() で page によって返値が配列になったりオブジェクトになったり

環境:

Laravel@9.52.4

 

事象:

Laravel でforPage() を使ってPagination を実装したがページによってオブジェクトが返ってくる。

 

↓↓正常な挙動(配列が返る)

↓↓異常な挙動(オブジェクトが返る)

↑↑(indexがfilter()により抜けがある)

solution)

同じロジックでpaginate していたがfilter処理をかましていたので異常な挙動な時はfilter が効いていた。collection->filter() で返る値も配列だが index が抜けているとオブジェクトとしてレスポンスを返してしまう。

したがってindex をつめる必要がある。

pagenate処理中にfilter()関数を使うなら常に結果の$filteredに

$filtered->values() でindexを詰める必要がある。

 

Laravel: migration file を削除してしまい php artisan migrate:reset でエラー

環境:

Laravel@9.52.4

 

migrate 済みの migration ファイルを削除してしまい、php artisan migrate:reset で Migration not found とエラーが出てしまった場合。

 

solution)

php artisan migrate:fresh

>>> DB全てのテーブルが削除された後、migrate する処理

 

ref:

stackoverflow.com

Laravel: Cannot trigger ORM model event static::restored

環境:

laravel@8.83.23

 

事象:

Model を soft-delete し、その後 restore 時に特定の処理をしたいが処理が実行されない。

 

cannot works:

@models/User.php

protected static fucntion boot() {

  parent::boot();

  static::deleted(function ($user) {

    $user->profileDetail()->delete();  // works fine

  })

  static::updated(function ($user) {

    $user->name = "updated";

    $user->save();  // works fine

  })

  static::restored(function ($user) {

    $user->profileDetail()->restore();  // cannot works ????

  })

}

 

原因:

User を restore するときに 一意の model を指定していなかったため

 

User::where('id', $request->id)->withTrashed()->restore(); // requested user will be restore but cannot trigger static::restored(function ($user))

 

solution)

User::where('id', $request->id)->withTrashed()->first()->restore();

Laravel + MongoDB: error: Indirect modification of overloaded property App\....

環境:

laravel@8.83.23

jensseger/laravel-mongodb@3.8.0

 

Model Structure

Profile: {

  roles: [’admin’]

}

$profile = App\Profile::find(1);

$profile->roles = array_push($profile->roles, 'superAdmin')

 

>>> error: Indirect modification of overloaded property App\Profile

 

solution)

値を編集するのではなく、新たな値を定義する

$roles = array_values($profile->roles)

array_push($roles, 'superAdmin')

$profile->roles = $roles

$profile->save()