【问题标题】:How to display data store in the database on a blade.php file如何在blade.php文件上显示数据库中的数据存储
【发布时间】:2020-04-03 09:04:27
【问题描述】:

我尝试从我的 index.blade.php 文件中的单个身份验证用户检索数据

<h3 class="profile-username text-center">{{$user ?? ''->lastname}}</h3>

使用我的 ProfileController

public function index($user){
        $user_id = auth()->user()->id;
        $user = User::findOrFail($user_id);
        return view('profiles.index')->with('users',$user);
    }

并且用户数据在我的 users 表中

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('accno')->unique();
            $table->string('acc_type');
            $table->string('firstname');
            $table->string('middlename');
            $table->string('lastname');
            $table->string('address');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('phoneno')->unique();
            $table->string('sex');
            $table->string('martial_status');
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

路线

Route::get('/profile/{user}', 'ProfilesController@index')->name('profiles.show');

我不断收到这个 Laravel 错误:

试图获取非对象的属性“姓氏”(查看:C:\Users\user pc\Desktop\dkn\resources\views\profiles\index.blade.php)。

【问题讨论】:

  • 这是什么? {{$user ?? ''-&gt;lastname}} .. 你的意思是 $user-&gt;lastname
  • 我在 index.blade.php 文件中回显 php

标签: php laravel


【解决方案1】:

这个

{{$user ?? ''->lastname}}

必须是

{{ $user->lastname ?? '' }}

您正在从控制器发送一个用户对象。如果你需要访问一个对象属性,你必须使用语法 object->property。

【讨论】:

  • 会触发编译错误。将?? 更改为单个?? => 否则。 ?? => if-isset - 返回
【解决方案2】:

由于在控制器中您使用了findOrFail(),当您到达刀片时,您 100% 拥有来自数据库的 User 实例。所以你不需要在那里检查它。

<h3 class="profile-username text-center">{{$user->lastname}}</h3>

如果你想检查它,这样做

<h3 class="profile-username text-center">{{$user->lastname ?? ''}}</h3>

<h3 class="profile-username text-center">{{$user ? $user->lastname : ''}}</h3>

顺便说一句,您不需要从数据库中恢复用户,因为它已经在 laravel auth 中

public function index($user){
    $user = auth()->user();
    return view('profiles.index')->with('users',$user);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2017-01-22
    • 2012-06-03
    相关资源
    最近更新 更多