Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: save image in database

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'));
    }
like image 838
Ruben Avatar asked Feb 17 '20 11:02

Ruben


People also ask

Where to save image in Laravel?

I need it to store only the filename of the image and extension, as I'm saving it to the laravel app/storage/uploads folder. response from the form. use App\Person; use Image; the file will be moved inside the storage folder under the uploads folder .


1 Answers

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();
}
like image 124
Robin Gillitzer Avatar answered Oct 12 '22 05:10

Robin Gillitzer