簡體   English   中英

如何在blade.php文件上顯示數據庫中的數據存儲

[英]How to display data store in the database on a blade.php file

我嘗試從index.blade.php文件中的單個 auth 用戶檢索數據

<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);
    }

用戶數據在我的用戶表中

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)。

由於在控制器中您使用了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);
}

這個

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

必須是

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

您正在從控制器發送用戶對象。 如果您需要訪問對象屬性,則必須使用語法 object->property。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM