Good friends, I have the following problem in laravel. I want to create a record in a table called movies that is related to a category table by means of a foreign key. Going to the view new.blade.php shows me the following error:
(1/1) RelationNotFoundException
Call to undefined relationship [category] on model [App \ Category].
Table Movies
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 50)->required();
$table->string('description', 50)->nullable();
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->timestamps();
});
}
Movie Model
class Movie extends Model
{
protected $table = 'movies';
protected $primaryKey = 'id';
protected $fillable = ['name', 'description', 'category_id'];
protected $guarded = ['id'];
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
}
Category Model
class Category extends Model
{
protected $table = 'categories';
protected $primaryKey = 'id';
protected $fillable = ['name', 'description'];
protected $guarded = ['id'];
public function movies()
{
return $this->hasMany('App\Movie');
}
}
MovieController driver @ create
public function create()
{
$categoria = Category::with('category')->get();
return \View::make('new', compact('categoria'));
}
View create new.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
{!! Form::open(['route' => 'movie.store', 'method' => 'post', 'novalidate']) !!}
<div class="form-group">
{!! Form::label('full_name', 'Nombre') !!}
{!! Form::text('name', null, ['class' => 'form-control' , 'required' => 'required']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Descripción') !!}
{!! Form::text('description', null, ['class' => 'form-control' , 'required' => 'required']) !!}
</div>
<div class="form-group">
{!! Form::label('category', 'Categoria') !!}
<select name="category_id">
@foreach($categoria as $catego)
<option value="{{$catego->category->id}}">{{$catego->category->name}}</option>
@endforeach
</select>
</div>
<div class="form-group">
{!! Form::submit('Enviar', ['class' => 'btn btn-success ' ] ) !!}
</div>
{!! Form::close() !!}
</div>
</div>
{{$categoria}}
</div>
@endsection