Apr 14, 2015
0
Level 4
Laravel 5 Adding Many One To Many relationships
I have a problem with storing multiple One to Many relationships value to the DB .
Migration:
Schema::create('articles', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title');
$table->string('slug', 100)->unique();
$table->LongText('body');
$table->text('excerp');
$table->integer('img_id')->unsigned()->nullable();
$table->integer('img_gal_id')->unsigned()->nullable();
$table->timestamp('published_at');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('img_gal_id')->references('id')->on('image_galleries');
$table->foreign('img_id')->references('id')->on('images');
});
Form
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title', null, ['class' => 'form-container']) !!}
{!! Form::label('images', 'Article Image') !!}
{!! Form::file('images[]', ['class' => 'form-container', 'multiple']) !!}
and so on....
Part of Article.php
protected $fillable = ['title', 'user_id','slug', 'body', 'excerp','published_at', 'img_id', 'img_gal_id'];
/ **
* Articles from a user.
* One To Many Relasion
* @var array
*/
public function user()
{
return $this->BelongsTo('App\User');
}
/**
* Main Image for article.
* Many to One Relasion
* @var array
*/
public function Image()
{
return $this->BelongsTo('App\Image');
}
Image
/**
*One to many relasionship with article entity
*/
public function articles()
{
return $this->HasMany('App\Article');
}
Controller
public function store(CreateArticleRequest $request)
{
$images = Input::file('images');
$imgobj = new Image;
// Imgprof = Upload the file and store it to db
$imgobj-> Imgprof($images);
// Uploaded img id :
$Uploadedimgid = $imgobj->Getimgids();
$article = \Auth::user()->articles()->create($request->all());
}
I am storing 2 obj to db (Image - imgobj and Article)
I've managed to store users id to the db, but now how to store the value of $uploadedimgid to the same $article(to img_id)?
I tried to append image()->$imgobj but no success.
Thanks!
Please or to participate in this conversation.