이준오
이준오

Reputation: 11

in laravel I set foriegn key but it does not work

I want to make file attachment in laravel in 5.4 but one to many relationship does not work.

but it works article-User relationship

it is attachments source

    public function up()
    {
        Schema::create('attachments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('article_id')->unsigned()->index();
            $table->string('filename');
            $table->integer('bytes')->nullable()->unsigned();
            $table->string('mime')->nullable();
            $table->timestamps();
            $table->foreign('article_id')->references('id')->on('articles')->onUpdate('cascade')->onDelete('cascade');
        });
    }

it is articles source

   public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->index();
            $table->string('title');
            $table->text('content');
            $table->string('image');
            $table->string('file');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
        });
    }

it is article model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title', 'content'];
    public function user()
        {
                return $this->belongsTo(User::class);
        }


        public function attachments()
        {
        return $this->hasMany(Attachment::class);
        }
}

it is attachment model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attachment extends Model
{
        protected $fillable = ['filename', 'bytes', 'mime'];
        public function article()
        {
        return $this->belongsTo(Article::class);
        }
        public function getBytesAttribute($value)
        {
                return format_filesize($value);
        }
        public function getUrlAttribute()
        {
                return url('files/'.$this->filename);
        }
}

and error is

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into `attachments` (`filename`, `bytes`, `mime`, `article_id`, `updated_at`, `created_at`) values (aMqJUvEaLpXrAtKOre().docx, 111207, application/octet-stream, , 2017-10-28 09:33:32, 2017-10-28 09:33:32))

article - user chain is works as well but not in article - attachment ... plz help me.. tanks to read.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
class ArticlesController extends Controller
{

    public function index()
    {
//        $articles = \App\Article::with('user')->get();
          $articles = \App\Article::latest()->paginate(5);
        return view('pages.article', compact('articles'));
    }


    public function create()
    {
        return view('pages.articlecreate');
    }

    public function store(Request $request)
    {
        if($request->hasFile('files')) {
                $files = $request->file('files');

                foreach($files as $file) {
                        $filename = str_random().filter_var($file->getClientOriginalName(), FILTER_SANITIZE_URL);
                        $file->move(public_path('files'), $filename);
                        $article = new \App\Article();
                        $article->attachments()->create([
                                'filename' => $filename,
                                'bytes' => $file->getClientSize(),
                                'mime' => $file->getClientMimeType()
                        ]);
                }
        }
        $rules = [
                'title' => ['required'],
                'content' => ['required', 'min:10'],
        $validator = \Validator::make($request->all(), $rules);
        if ($validator->fails()){
        return back()->withErrors($validator)->withInput();}
        $article = $request->user()->articles()->create($request->all());
        if(! $article) {
          return back()->with('flash_message', 'FAILD.')->withInput();
        }
        return redirect(route('articles.index'))->with('flash_message', 'SAVED.');
    }


    public function show(\App\Article $article)
    {
        //
        return view('pages.articleshow', compact('article')); //171021
    }

    public function edit(\App\Article $article)
    {
        return view('pages.articleedit', compact('article')); //171022
    }


    public function update(Request $request, \App\Article $article)
    {
        $article->update($request->all());
        return redirect(route('articles.show', $article->id));
    }

    public function destroy(Request $request, \App\Article $article)
    {
        $article->delete($request->all());
        return redirect('articles');
    }
}

Upvotes: 0

Views: 44

Answers (1)

Hedegare
Hedegare

Reputation: 2047

You need to add an article_id when you create an attachment. For that to happen you first need to create your article:

$article = $request->user()->articles()->create($request->all());

And then create you attachments:

if($request->hasFile('files')) {
    $files = $request->file('files');
    foreach($files as $file) {
       $filename = str_random().filter_var($file->getClientOriginalName(), FILTER_SANITIZE_URL);
       $file->move(public_path('files'), $filename);
       $article = new \App\Article();
       $article->attachments()->create([
           'article_id' => $article->id,
           'filename' => $filename,
           'bytes' => $file->getClientSize(),
           'mime' => $file->getClientMimeType()
       ]);
   }
}

Upvotes: 1

Related Questions