我想从名为“users”的数据库表中获取数据并在表中显示输出。
我写了下面的代码,但它不起作用。
我正在使用 Laravel 5.5
@extends('layouts.app')
@section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
@foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
Error: Undefined Variable: users
最佳答案
问题是您试图在您的 (Blade) 模板中混合使用 PHP。尽管使用 @php
指令可以做到这一点,但这是一种不好的做法:您的 View 不应包含任何业务逻辑。
理想情况下,您希望从您的 Controller 传递这些数据。它应该看起来像这样:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
阅读更多关于将数据传递给 View 的信息 here .
关于php - Laravel 从数据库中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48766910/