You see, I'm doing a Laravel project in which I have a table called Plants and another call Comments. The story is that I want to allow users to write comments to ask about plants. In relation to this, I want to create a view in which you can see the comments by filtering them according to what plant you are talking about.
Here I show the index.blade.php with the view of the comments:
@extends('layouts.app')
@section('content')
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="text-center text-mute"> {{ __("Todos los comentarios") }} </h1>
@forelse($comentario as $c)
<div class="panel panel-default">
<div class="panel-heading">
<h3>
Código del usuario: {{$c->usuario}}<br>
Código de la planta: {{ $c->planta }}
</h3>
</div>
<div class="panel-body">
{{ $c->comentario }}
</div>
</div>
@empty
<div class="alert alert-danger">
{{ __("No hay ningún comentario sobre plantas en este momento") }}
</div>
@endforelse
</div>
</div>
@endsection
This view will be mentioned in the file web.php:
Route::get('/comentarios/{planta}','ComentarioController@show');
And here the CommentController.php file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Comentario;
use App\plantas;
class ComentarioController extends Controller{
public function show(Comentario $come){
$comentario=$come->vegetal()->with('comentarios')->paginate(5);
return view('comentarios.index', compact('planta','comentario'));
}
}
Comment.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comentario extends Model{
protected $table = 'comentarios';
protected $fillable = [
'planta', 'usuario', 'comentario',
];
public function vegetal(){
return $this->belongsTo(plantas::class, 'planta');
}
public function usuario(){
return $this->belongsTo(User::class, 'usuario');
}
}
And the table Plantas.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class plantas extends Model{
protected $table = 'plantas';
protected $fillable = [
'nombre', 'descripcion',
];
public function comentarios(){
return $this->hasMany(Comentario::class,'planta');
}
}
For my test I have prepared 2 plants and to each one I have prepared a comment:
Each of the titles in the plant view includes a link to the list of plant comments, but ...
What have you done wrong so that the comments are not shown?
Edit, I have tried to make a modification in the CommentController file:
class ComentarioController extends Controller{
public function show(Comentario $come){
$comentario=$come->paginate(5);
return view('comentarios.index', compact('planta','comentario'));
}
}
Clearly the bug is in the fragment "vegetable () -> with ('comments') - >". Now the question is to discover what I'm doing wrong.