【问题标题】:How to get data from database to view page in laravel 8?如何从数据库中获取数据以在 laravel 8 中查看页面?
【发布时间】:2021-05-11 12:18:45
【问题描述】:

我正在尝试使用 Laravel 8 将数据从数据库获取到我的视图页面。

表的名字是"users" [id, name, email, etc...]它是从Jetstream自动生成的,连接和登录注册工作正常! p>

我只想查看表用户列表(id和名称)。

这是我的 editprofile.blade.php 文件:

<x-app-layout>
<x-slot name="header">
    <h2 class="font-semibold text-xl text-gray-800 leading-tight">
        {{ __('Edit Profile') }}
    </h2>
</x-slot>

<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
          <h1>This is a private page </h1>

          @foreach($petani as $key => $data)
              <tr>
                <th>{{$data->id}}</th>
                <th>{{$data->name}}</th>             
              </tr>
          @endforeach
        </div>
    </div>
</div>

这是我的 routes/web.php 文件 (刀片位于名为 profile 的文件夹下,因此路径为 profile/editprofile.blade.php

Route::get('profile/editprofile', function () {
$petani = DB::table('users')->get();

return view('profile/editprofile', ['petani' => $petani]);
});

请问如何在我的页面中显示数据?

【问题讨论】:

    标签: php laravel laravel-8


    【解决方案1】:

    为什么不直接使用官方文档中显示的 Eloquent 模型。 因此,要查询所有用户,您可以执行以下操作:

    Route::get('profile/editprofile', function () {
      $usres = \App\User::all();
      return view('profile/editprofile', ['petani' => $usres]);
    });
    

    【讨论】:

    • 我在尝试您提出的解决方案时遇到此错误:找不到错误类'App\User'
    • 您的应用程序中是否有用户模型?如果没有,您可以随时创建它。但请先尝试搜索它。
    • 是的,我有一个由 Jetsream 自动创建的用户模型
    • 然后将我的代码中的 '\App\User' 替换为您的模型。我不确定使用 Jetstream 生成的模型的命名空间是什么。它可能是“\App\Models\User”,但您应该更清楚地在代码中看到它。
    猜你喜欢
    • 2017-08-22
    • 1970-01-01
    • 2021-10-19
    • 2019-05-24
    • 2021-07-02
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多