2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravel adminの$show->fieldでリレーション使う場合

Posted at

同じフィールド内にリレーションで持たせた値を表示したい!
フィールドが分かれた感じの説明はよく見るけど、一緒の項目として並んでいるのが探してもわからず...
laravel-adminで準備されているasメソッドを使ってみた。
これが正解かはわかりません。

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    public function code()
    {
        return $this->hasMany(Code::class, 'company_id', 'id');
    }
}
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Code extends Model
{
    protected $fillable = [
        'code',
        'company_id',
        'admin_user_id'
    ];

    public function company()
    {
        return $this->belongsTo(Company::class, 'company_id', 'id');
    }
}
    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(Code::with('company')->findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('code', __('Code'));
        $show->field('company', __('Company id'))->as(function ($company) {
            return $company->name;
        });
        $show->field('admin_user_id', __('User id'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?