Laravel:データベースに画像を保存します

ルーベン:

私は記事のテーブルに関連している私のイメージのテーブルに画像を保存しようとしています

私は、次のようなエラーが表示され、これを行うと:

オーバーロードされたプロパティのApp \条:: $サムネイルの間接的な変更は効果がありません

私の記事モデル:

<?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'));
    }
ロビンGillitzer:

あなたLaravelのバージョンに関連して、あなたのためにこの5月作品:

$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();
}

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=9924&siteId=1