Laravel: save image in database

Ruben :

I am trying to store an image in my images table that is related to the articles table

When I do this the following error appears:

Indirect modification of overloaded property App\Article::$thumbnail has no effect.

My Article Model:

<?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);
    }
}

My Image Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

And the store method in my ArticleController:

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'));
    }
Robin Gillitzer :

Related to your Laravel version, this may works for you:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9712&siteId=1