movor/laravel-custom-casts

为Laravel模型属性创建自定义类型转换

v0.2.1 2018-11-30 16:51 UTC

This package is not auto-updated.

Last update: 2024-09-21 00:14:18 UTC


README

Build Downloads Stable License

为Laravel模型属性创建自定义类型转换

默认情况下,从版本5开始,Laravel支持属性转换。如果我们在我们自己的模型上定义$cast属性,Laravel将帮助我们将定义的属性转换为常见的数据类型。目前支持的数据类型转换(Laravel 5.6)包括:integerrealfloatdoublestringbooleanobjectarraycollectiondatedatetimetimestamp

如果这些默认的数据类型转换不够用,并且你想创建自己的,你就在正确的道路上。

❗❗❗ 正在迁移GIT仓库 ❗❗❗

此包的repo和维护将继续在

vkovic/laravel-custom-casts.

🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚 🚚

兼容性

此包与Laravel版本>= 5.1兼容

安装

通过composer安装此包

composer require movor/laravel-custom-casts

示例:转换用户图像

保存图像时,需要完成两件事

  1. 将图像名称(有时带路径)保存到相应的数据库字段
  2. 将图像物理地保存在磁盘上

为了本例的指导,我们将使用在app/User.php中找到的默认Laravel用户模型。

除了基本、预定义的字段:nameemailpassword之外,我们还想允许用户上传他的头像。假设我们已经有了一个带有image字段的users表(你应该为此创建seeder)。

为了利用自定义转换,我们需要向用户模型添加一个特质,并通过$casts属性将其链接到转换类。

// File: app/User.php

namespace App;

use App\CustomCasts\ImageCast;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Movor\LaravelCustomCasts\HasCustomCasts;

class User extends Authenticatable
{
    use Notifiable, HasCustomCasts;

    protected $fillable = [
        'name', 'email', 'password', 'image'
    ];

    protected $hidden = [
        'password', 'remember_token'
    ];

    protected $casts = [
        'image' => ImageCast::class
    ];
}

// ...

下一步是创建一个处理转换的类。它必须实现setAttribute方法,该方法将负责保存图像(从UploadedFile对象,在这种情况下是通过表单上传)并生成图像名称和路径——以在数据库中保留。

// File: app/CustomCasts/ImageCast.php

namespace App\CustomCasts;

use Movor\LaravelCustomCasts\CustomCastBase;
use Illuminate\Http\UploadedFile;

class ImageCast extends CustomCastBase
{
    public function setAttribute($file)
    {
        // Define storage folder
        // (relative to "storage/app" folder in Laravel project)
        // Don't forget to create it !!!
        $storageDir = 'images';

        // Generate random image name
        $filename = str_random() . '.' . $file->extension();

        // Save image to predefined folder
        $file->storeAs($storageDir, $filename);

        // This will be stored in db field: "image"
        return $storageDir . '/' . $filename;
    }
}

让我们跳转到用户创建的例子。这将触发我们的自定义转换逻辑。

假设我们有一个处理用户创建的用户控制器。你应该自己创建这个。

下面的代码只是一个简单的示例,仅作为指导使用。

// File: app/Http/Controllers/UserController.php

// ...

protected function create(Request $request)
{
    User::create([
        'name' => $request->name,
        'email' => $request->email,
        'password' => bcrypt($request->password),
        // Past the whole Illuminate\Http\UploadedFile object,
        // we'll handle it in our ImageCast class
        'image' => $request->file('image')
    ]);
}

// ...

访问相应的路由输入基本详情并附加图像。之后,我们将创建我们的用户并存储图像。

但是,我们也应该处理在用户被删除时删除图像。这可以通过利用底层eloquent事件处理来实现。每次触发eloquent事件时,逻辑都会在我们的自定义转换类中查找具有相同名称的公共方法。

可能的方法名称包括:retrievedcreatingcreatedupdatingupdatedsavingsaveddeletingdeletedrestoringrestored

// File: app/CustomCasts/ImageCast.php

// Add at the top
use Storage;

// ...

// This method will be triggered after model has been deleted
public function deleted()
{
    // We can access underlying model with $this->model
    // and attribute name that is being casted with $this->attribute

    // Retrieve image path and delete it from the disk
    $imagePath = $this->model->image;
    Storage::delete($imagePath);
}

// ...

这应该涵盖了自定义转换的基本用法。