1

I've got two different tables, one is called articles, the other one images I Want to create an article that contains multiple images,

How can I create with Laravel 5.5 a many-to-many relation? I've followed this post on laracast: https://laracasts.com/discuss/channels/laravel/multiple-images-in-article-galerry

here is the code

ARTICLE MODEL

public function images() {
    return $this->belongsToMany('App\Image');
}

IMAGE MODEL

public function articles() {
    return $this->belongsToMany('App\Article'); 
}

ARTICLE-IMAGE MIGRATION(TABLE)

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArticleImageTable extends Migration {

    public function up()
    {
        Schema::create('article_image', function(Blueprint $table)
        {
            $table->increments('id');
            $table->integer('article_id')->unsigned()->index();
            $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
            $table->integer('image_id')->unsigned()->index();
            $table->foreign('image_id')->references('id')->on('images')->onDelete('cascade');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('article_image');
    }

}



ARTICLES CONTROLLER


<?php namespace App\Http\Controllers;

use App\Article;

class ArticlesController extends Controller
{

    public function index()
    {
        $articles = Article::with('images')->get();

        return view('articles.index', compact('articles'));
    }

    public function show($id)
    {
        $article = Article::find($id);

        $article->load('images');

        return view('articles.show', compact('article'));
    }

}

MY PROBLEM IS How do i continue from here(that is display both the articles and the images)

simon
  • 11
  • 3

0 Answers0