pass variables in Laravel

1

I'm starting to create a CRUD. In the index method of the controller I have put this:

public function index(){
    $productos=Producto::get();
    return view('productos.index')->with('productos',$productos);
}

And in the index.blade.php view:

foreach($productos as $producto)
    echo "<tr>";?>
    <td class="text-center">{{$producto->id}}</td>
    <td class="text-center">{{$producto->nombre}}</td>
    <td class="text-center">{{$producto->precio}}</td>
    <td>
        <a href="{{ route('producto.show',$producto->id) }}" class="btn btn-info">Ver</a> 
    </td><?php
    echo "</tr>";

Trying to run the application in the browser tells me that it can not find $ products:

  

"Undefined variable: products (View: C: \ xampp \ htdocs \ ad \ dam2d \ resources \ views \ products \ index.blade.php)"

    
asked by Charly Utrilla 08.02.2018 в 13:19
source

2 answers

0

Test to:

public function index(){
  $productos=Producto::get();
  return view('productos.index' , compact("productos"));
}

I assume that the path of 'products.index' in the Routes is well configured.

    
answered by 08.02.2018 / 13:39
source
3

I answer this question in order to explain the real problem and give a solution with best practices that give a guide to future visitors on how to use and take advantage of Laravel.

Considering that the OP indicates that its problem was not to include the namespace of Producto , according to the standard PSR-2 (which is used by Laravel), the statement to include the class by use is preferable, therefore the controller code would be the following way:

<?php

namespace App\Http\Controllers;

use App\Producto;

class MyController extends Controller
{
    public function index()
    {
        $productos = Producto::get();

        return view('productos.index')->with('productos', $productos);          
    }

    // otros métodos
}

Regarding the view, we must remember that in Blade it is not necessary to use the tags <?php ... ?> for any reason, as with echo , this is a bad practice. The correct syntax is:

@foreach($productos as $producto)
    <tr>
      <td class="text-center">{{$producto->id}}</td>
      <td class="text-center">{{$producto->nombre}}</td>
      <td class="text-center">{{$producto->precio}}</td>
      <td>
        <a href="{{ route('producto.show', $producto->id) }}" class="btn btn-info">Ver</a> 
      </td>
    </tr>
@endforeach
    
answered by 10.02.2018 в 04:04