Undefined property: stdClass :: $ comments laravel

1

I have an error when returning a foreign key in the view, initially in the path 'index' there is no problem, ṕero when changing the query a bit and changing the route, this index view is no longer useful .

ROUTES

Route::get('/', 'SessionController@iniciarSession');
Route::get('/index', 'IndexController@index'); 
Route::get('/categoria/{nombre}', 'IndexController@cambiarCategoria');
Route::post('/temitas', 'TemaController@crearTema');

CONTROLLER

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;  
use Illuminate\Http\Request;
use App\Tema;
use App\Categoria;
class indexController extends Controller
{
 private $temas;
 private $categorias;

 public function index(Request $request){
  $usuario = $request->session()->get('login');
  if($usuario == null){
   return redirect('/');
  }
  $temas = Tema::all();
  $categorias = Categoria::all();
  return view('index',compact('temas','categorias'));
 }

 //es aqui donde tengo problemas

 public function cambiarCategoria($nombre){
  $categoria = DB::table('Categoria')
                  ->where('nombre',$nombre)
                  ->first();
  $categorias = Categoria::all();
  if($categoria== null){
   return abort(404);
  }else{
   $temas = DB::table('Tema')
              ->where('Categoria',$categoria->idCategoria)
              ->get();
   return view('index',compact('temas','categorias'));

  }
 }
}

VISTA

@foreach ($temas as $tema)
<a class="col-2 p-0 tema">
  <div class="capa"></div>
  <div class="imagen">
    <img src="storage/images/{{$tema->imagen}}" alt="">
  </div>
  <div class="info">
    //aqui me da el error
    <span class="mr-1">{{count($tema->comentarios)}}</span>  <i class="fas  fa-comment"></i>                                  
  </div>
  <div class="titulo">
    {{$tema->titulo}}
  </div>
</a>
<p></p>
@endforeach
    
asked by DAEGO 26.07.2018 в 02:09
source

1 answer

0

I can not attest that the logic of your functions works correctly because we do not have details of the models, but the error originates in the view when doing the following:

<...>{{ count($tema->comentarios) }}</...>

In that sentence you are trying to access a property dynamically, treating $tema as an object doing $tema->comentarios , something that is no longer because when you return the view you made use of the function Compact () :

return view('index',compact('temas','categorias'));

What that function does-own PHP-is to generate an array / associative array of the variables that you send.

That's why the error that throws you is the following:

  

Undefined property: stdClass :: $ comments laravel

Well, that property does not exist there.

Solution

In your view, instead of:

<...>{{ count($tema->comentarios) }}</...>

you could access the properties as if it were an arrangement:

<...>{{ count($tema['comentarios']) }}</...>
    
answered by 26.07.2018 в 19:14