php 从 Laravel 中的数据库获取数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48766910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetching data from Database in Laravel
提问by user9332352
I want to fetch data from database table named 'users' and display the output in a table.
我想从名为“users”的数据库表中获取数据并在表中显示输出。
I have written below code but it's not working.
我写了下面的代码,但它不起作用。
I am using Laravel 5.5
我正在使用 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
错误:未定义变量:用户
回答by Emile Pels
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with @php
directives, this is bad practice: your view should not contain any business logic.
问题是您试图在您的(刀片)模板中混合 PHP。尽管使用@php
指令可以这样做,但这是不好的做法:您的视图不应包含任何业务逻辑。
Ideally you want to pass this data from your controller. It should look something like this:
理想情况下,您希望从控制器传递此数据。它应该是这样的:
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);
}
}
Read more on passing data to views here.
回答by Nikola Gavric
You are doing it all wrong, the point of MVC
design is to have your controllers
do the application logic, your views to represent a representation of that data
and models to contain the data you need
, in your case you are missing the point completely by using DB::table
inside of your view, so here is an example code which you might need to correct a bit:
你做错了,MVC
设计的重点是让你controllers
做应用程序逻辑,你的视图代表 arepresentation of that data
和模型contain the data you need
,在你的情况下你完全错过了DB::table
在你的视图内部使用的点,所以这里是一个例子您可能需要更正一下的代码:
The example below doesn't show MVC
pattern since the data
is passed from inside a closure of a route
下面的示例没有显示MVC
模式,因为data
是从 a 的闭包内部传递的route
web.php
网页.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
视图.blade.php
@foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
@endforeach
Change VIEW-NAME-HERE
with the name of your view
file, for example index
or users.index
改变VIEW-NAME-HERE
你的名字view
的文件,例如index
或users.index