Hi,
this is my category model
<?php
class Category extends \Eloquent {
protected $fillable = [];
protected $table = 'category';
public function types()
{
return $this->hasMany('Types');
}
}
and thi is my types model
<?php
class Types extends \Eloquent {
protected $fillable = [];
protected $table ='types';
public function category()
{
return $this->belongsTo('Category');
}
}
In my controller
public function index()
{
$data['category_list'] = Category::all();
$data['types_list'] = $data['category_list']->types();
$data['page_title']= 'Gestione eventi';
return View::make('eventi_tipo.index', $data);
}
public function store()
{
$tipologia = new Type;
$tipologia->tipologia = ucfirst(trim(Input::get('type')));
$tipologia->categoria_id = Input::get('category');
$tipologia->save();
return Redirect::action('TypesController@index');
}
And I have this error:
Call to undefined method Illuminate\Database\Eloquent\Collection::tipo()
How to show in a table the category and non the id of category?
Sorry for my bad english.
The error doesn't come from the code you showed, it's probably in the view and the reason for that is that I believe you try to do something like this:
$category->types->tipo();
That being said, you try to call Types
method on the Collection
of Types
models not on a single model.
OK. I hope to explain better.
I have two tables
mysql> select * from eventi_tipo;
+----+-----------+--------------+
| id | Type | category_id |
+----+-----------+--------------+
| 2 | Opera | 1 |
| 3 | Film | 2 |
| 4 | Balletto | 1 |
| 6 | Horror | 2 |
+----+-----------+--------------+
4 rows in set (0.00 sec)
mysql> select * from categories;
+----+-----------+
| id | category |
+----+-----------+
| 1 | Teatro |
| 2 | Film |
+----+-----------+
2 rows in set (0.00 sec)
Now in my controller Types I have this
public function index()
{
$types = Types::with('categories')->get();
return View::make('eventi_tipo.index', $type);
}
And in my models:
<?php
class Category extends \Eloquent {
protected $fillable = [];
protected $table = 'categories';
public function types()
{
return $this->hasMany('Types','category_id');
}
}
<?php
class EventiTipo extends \Eloquent {
protected $fillable = [];
protected $table ='types';
public function categories()
{
return $this->belongsTo('Categories');
}
}
The problem is the in my result I have the ID of th categories and not their name (Teatro, Film)
Solved
<?php
class Type extends \Eloquent {
protected $fillable = [];
protected $table ='types';
public function categories()
{
return $this->belongsTo('Categories','category_id');
}
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community