php - Laravel 从数据库中获取数据

标签 php mysql laravel laravel-5

我想从名为“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/

相关文章:

php - 如何删除数组中的+

php - 如何在代码中使用 PHP Namespace

php - 想要使用 $_POST ['email' ] 在 php 邮件功能中设置收件人电子邮件

mysql - 如何在动态消息中选择我或我的 friend 创建的帖子?

mysql - Eloquent 外键

php - 24 小时日期增量 (PHP/Laravel)

PHP 和 NVP(名称-值对)列表?

MySQL- View : definition changes after saving?

laravel - 在 laravel 中设置页面元标题的正确方法是什么

php - 注册页面未注册用户