mercredi 26 septembre 2018

relation between files table and books table laravel

I have some migrations books,users,categories,authors and files

i made a pivot table for books and files,"book_file" table:

 public function up()
    {
        Schema::create('book_files', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('book_id');
            $table->unsignedInteger('file_id');

            $table->foreign('book_id')
                ->references('id')
                ->on('books')
                ->onDelete('cascade')
                ->onUpdate('cascade');


            $table->foreign('file_id')
                ->references('id')
                ->on('files')
                ->onDelete('cascade')
                ->onUpdate('cascade');

            $table->timestamps();
        });
    }

and Book model code:

public function files(){
        return $this->belongsToMany(File::class,'files','book_files');
    }

File model code:

    protected $fillable = [
        'name',
    ];



    public function books()
    {
        return $this->belongsTo(Book::class);
    }

BookController:

    public function create()
    {
        $categories = Category::all();
        $authors = Author::all();
        $files= File::all();
        return view('books.create', compact('categories','authors','files'));
    }

    public function store(Request $request)
    {
        $this->validate($request,
            [
                'name'=>'required|string|max:256',
                'pages'=>'required|integer|numeric',
                'ISBN'=>'required|string|numeric',
                'price'=>'required|integer|numeric',
                'published_at'=>'required|date|date',
                'file'=>'required',

            ]
        );


        if ($request->hasFile('file')) {
            $filename = $request->file('file')->getClientOriginalName();
            $request->file->storeAs('public', $filename);
            $file = new File;
            $file->name = $filename;

            $file->save();

        }

            $book =  Auth::User()->books()->create($request->except('_token'));
        $book->categories()->attach($request->get('category_id'));
        $book->authors()->attach($request->get('author_id'));
        $book->files()->attach($request->get('file_id'));
        return redirect('/books');
    }

files uploading in database works true but my pivot table (book_file) doesn't change! what is wrong? I am beginner in laravel,please help,thanks.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2xUpOoq
via IFTTT

Aucun commentaire:

Enregistrer un commentaire