php - 如何在 Controller 中从 MySQL 访问数据属性

标签 php mysql laravel

我正在学习 Laravel 框架,我不知道如何访问 Controller 中的属性。

public function uuid(Request $request)
{
    if($request->get('uuid') == null) return abort(404);
    $uuid = $request->get('uuid');
    $users = DB::table('users')->select('*')->where('uuid', $uuid)->get();

    $result = array([
        'id' => $users['id'],
        'username' => $users['username'],
        'uuid' => $users['uuid'],
    ]);

    return view ('dashboard')->with('username', $result['username']);
}

在我的dashboard.blade.php中

{{$用户名}}

当我进入仪表板时,它显示这样的错误

错误异常(E_NOTICE) 未定义索引:用户名

最佳答案

使用First()而不是get(),您将获得对象,以便访问数据。

$users = DB::table('users')->select('*')->where('uuid', $uuid)->first();

$result = array([
    'id' => $users->id,
    'username' => $users->username,
    'uuid' => $users->uuid,
]);

return view ('dashboard')->with('username', $result['username']);

现在排序一下方法。

 $user = DB::table('users')->select('*')->where('uuid', $uuid)->first();
 $username = '';
 if(!empty($user)){
    $username = $user->username 
 }

return view ('dashboard',compact('username'));

关于php - 如何在 Controller 中从 MySQL 访问数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57344821/

相关文章:

php - 如何在wordpress插件开发中获得激活的插件列表?

php - 自定义 map /坐标

php - mysqli fetch_object 在结果集数组的第一个元素中返回非对象

mysql - 用于选择年份在两个日期之间的行的 SQL 查询

php - 在 Laravel 中删除时将外键值设置为默认值

php - 路线 :list - 404 error on oauth/token 中缺少 Laravel Passport 路线

laravel - 如何使用模态 Laravel 5.8 更新特定行

PHP MySQLi 错误处理 1062 重复键输入

php - 想要显示按月分组的得分最高者的详细信息

java - Hibernate:如何从 ScrollableResults 检索我的实体?