skip to Main Content

I’m new ton Laravel (also to StackOverflow), and I’m trying to show data in my home.blade.php table from PhpMyAdmin using a foreach loop. However, it’s not working correctly, and I can’t figure out where the problem is. I have other tables working with foreach, and I’ve followed the same steps with this table.

User Model

protected $table = 'users';

protected $fillable = ['id','name','edad','direccion_personal','celular','foto','email','direccion_sucursal_id'];

UserController

public function index()
{
    $Usuarios = User::all();
    $array = ['usuarios' => $Usuarios];

    return view('home')->with($array);
}

Finally, here’s my tbody:

<tbody>
@foreach ($usuarios as $Usuarios)
    <div>
        <tr>
            <th scope="row" style="text-align:center;">{{ $Usuarios->id }}</th>
            <td style="text-align:center;">{{ $Usuarios->nombre }}</td>
            .
            .
            .
        </tr>
    </div>
</tbody>
@endforeach

3

Answers


  1. I see you’re having troubles with the foreach loop. is not working correctly… but, I’m not sure what kind of problem is… if my answer does not work for you, please update your question so you can get more help

    I see you close your inside the foreach loop.
    That way you will end with lots of closing tags with just one opening…

    Try moving that close tag outside the loop

    <tbody>
    @foreach ($usuarios as $Usuarios)
     <div>
      <tr>
        <th scope="row" style="text-align:center;">{{$Usuarios->id}}</th>
        <td style="text-align:center;">{{$Usuarios->nombre}}</td>
           .
           .
           .
      </tr>
     </div>
    @endforeach
    </tbody>
    Login or Signup to reply.
  2. Why the array?

        public function index(){
            $usuarios = User::all();
            return view('home', compact('usuarios'));
        }
    
    

    Then:

    <tbody>
    
    @foreach ($usuarios as $us)
     <div>
      <tr>
        <th scope="row" style="text-align:center;">{{$us->id}}</th>
        <td style="text-align:center;">{{$us->nombre}}</td>
           .
           .
           .
      </tr>
     </div>
    @endforeach
    </tbody>
    
    Login or Signup to reply.
  3. Your foreach closes outside the </tbody> tag, and opens inside it. Your table body is thus closed after the first iteration of the loop, and never opened again, so with each iteration you now have an additional </tbody> line. This is invalid markup, and will break your site’s output.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search