I have some CATEGORIES and the categories have an "item" that I called ENTRY
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 191);
$table->string('slug', 191)->unique();
$table->unsignedInteger('entry_id')->default(1);
$table->foreign('entry_id')->references('id')->on('entries')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();
});
Create the relationships in the corresponding models.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name', 'slug', 'entry_id'];
public function posts(){
return $this->hasMany(Post::class);
}
public function entries(){
return $this->belongsTo(Entry::class);
}
}
and in Entry
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Entry extends Model
{
protected $fillable = ['name', 'slug'];
// Vendrian a ser los "Rubros" -> 'POST', 'EVENT', 'COURSE', 'INSTALLATION', 'CLASSIFIEDS'
public function categories(){
return $this->hasMany(Category::class);
}
public function events(){
return $this->hasMany(Event::class);
}
public function courses(){
return $this->hasMany(Course::class);
}
public function installations(){
return $this->hasMany(Installation::class);
}
public function classifieds(){
return $this->hasMany(Classified::class);
}
}
Now when I want to display everything in a datatables on the backend I do the following:
public function index()
{
$categories = Category::all();
return view('backend-admin.categories.index', compact('categories'));
}
and in the index.blade.php I do
@foreach($categories as $category)
<tr>
<td>{{ $category->id }}</td>
<td>{{ $category->name }}</td>
<td>{{ $category->entry->name }}</td>
<td width="105px">
{!! Form::open(['route' => ['categories-admin.destroy', $category->id], 'method' => 'DELETE']) !!}
<a href="{{ route('categories-admin.show', $category->id) }}" class="btn btn-primary btn-sm"><i class="fa fa-eye"></i></a>
<a href="{{ route('categories-admin.edit', $category->id) }}" class="btn btn-warning btn-sm"><i class="fa fa-edit"></i></a>
<span><button class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button></span>
{!! Form::close() !!}
</td>
</tr>
@endforeach
Can someone explain to me what I'm doing wrong?
Taking into account that it is a one-to-many relationship, and following the Laravel naming conventions, the relationship in the Category model should be called entry and not entries, as explained in the comments, the category belongs to an item:
In addition to this, I suggest using Eager Loading to load the relation before passing it to the DataTable, in order to avoid the N+1 problem:
More information about Eager Loading in the documentation: https://laravel.com/docs/5.8/eloquent-relationships#eager-loading