【问题标题】:Laravel 8 - Trait boot not firingLaravel 8 - 特质启动不触发
【发布时间】:2020-11-06 22:44:27
【问题描述】:

我在我的项目中使用Spatie Media Library。我在media 表中添加了用户ID 列,以跟踪谁上传或更新了图像(图像具有与之关联的元数据)。但是media class 中的引导方法没有触发。

我的media 班级是:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Spatie\MediaLibrary\MediaCollections\Models\Media as BaseMedia;

class Media extends BaseMedia
{
    /**
     * Table name
     *
     * @var string
     */
    protected $table = 'media';

    /**
     * Append
     *
     * @var array
     */
    protected $appends = ['url', 'ext'];

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        /**
         * Creating the record
         */
        static::creating(function ($obj) {

            $user = auth()->user();

            if (! $user) {
                if (! $obj->creator_id) {
                    $obj->creator_id = 1;
                    $obj->updater_id = 1;
                }
            } else {
                $obj->creator_id = $user->id;
                $obj->updater_id = $user->id;
            }

        });

        /**
         * Updating the record
         */
        static::updating(function ($obj) {

            $user = auth()->user();

            if (! $user) {
                $obj->updater_id = 1;
            } else {
                $obj->updater_id = $user->id;
            }

        });

       /**
        * Global scope to retrieve creator and updater
        */
        static::addGlobalScope('CreatorUpdater', function (Builder $builder) 
        {
            $builder->with('creator', 'updater');
        });

    }

    /**
     * Get Url
     *
     * @return string
     */
    public function getUrlAttribute()
    {
        return $this->getFullUrl();
    }

    /**
     * Get Ext
     *
     * @return mixed
     */
    public function getExtAttribute()
    {
        $arr = explode('.', $this->file_name);

        return $arr[count($arr) - 1];
    }

    /**
     * Creator
     */
    public function creator()
    {
        return $this->hasOne(User::class, 'id', 'creator_id');
    }

    /**
     * Updater
     */
    public function updater()
    {
        return $this->hasOne(User::class, 'id', 'updater_id');
    }
}

我错过了什么?如果我在boot 方法中使用Log,我不会得到任何日志条目。

【问题讨论】:

    标签: laravel media-library


    【解决方案1】:

    啊!我只需要将媒体库指向我的模型而不是 Spatie 的。

    media-library.php 配置文件中:

    /*
     * The fully qualified class name of the media model.
     */
    'media_model' => App\Models\Media::class,
    

    【讨论】:

      猜你喜欢
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多