【问题标题】:Laravel: save image in databaseLaravel:将图像保存在数据库中
【发布时间】:2020-06-01 07:17:14
【问题描述】:

我正在尝试将图像存储在与文章表相关的图像表中

当我这样做时,会出现以下错误:

间接修改重载属性 App\Article::$thumbnail 无效

我的文章模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'title', 'exerpt', 'body'
    ];

    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }

    public function thumbnail()
    {
        return $this->hasOne(Image::class);
    }
}

我的图像模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function article()
    {
        return $this->belongsTo(Article::class);
    }
}

还有我的 ArticleController 中的 store 方法:

public function store(Request $request)
    {
        $article = new Article($this->validateArticle($request));

        //hardcoded for now
        $article->user_id = 1;

        $thumbnail = '';

        $destinationPath = storage_path('app/public/thumbnails');

        $file = $request->thumbnail;

        $fileName = $file->clientExtension();

        $file->move($destinationPath, $fileName);

        $article->thumbnail->title = $file;

        $article->save();

        $article->tags()->attach(request('tags'));

        return redirect(route('articles'));
    }

【问题讨论】:

    标签: php database laravel


    【解决方案1】:

    与您的 Laravel 版本相关,这可能适合您:

    $article = new Article( $this->validateArticle( $request ) );
    $article->user_id = 1;
    $article->save();
    $article->tags()->attach( request( 'tags' ) );
    
    
    if( $request->hasFile( 'thumbnail' ) ) {
        $destinationPath = storage_path( 'app/public/thumbnails' );
        $file = $request->thumbnail;
        $fileName = time() . '.'.$file->clientExtension();
        $file->move( $destinationPath, $fileName );
    
        $image = new Image;
        $image->title = $fileName;
        $image->article_id = $article->id;
        $image->save();
    }
    

    【讨论】:

    • 是的,这对我有用!我猜你不能直接将值保存到相关对象?我也完全忘记了article_id……嗯,现在是星期一。
    猜你喜欢
    • 1970-01-01
    • 2019-04-21
    • 2011-02-14
    • 2020-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 2015-01-08
    • 2013-02-09
    相关资源
    最近更新 更多