首頁  >  問答  >  主體

LARAVEL8:嘗試存取 Null 上的「id」屬性

我是 Laravel 的新手,我正在從 Laracast 學習它。 這是我的問題,我正在創建一個評論表單,它的 php 程式碼如下所示:

<section class="col-span-8 col-start-5 mt-10 space-y-6">
    <!-- Post form -->
    <form method="POST" action="/post/{{ $post->slug }}/comments" class="border border-gray-200 p-6 rounded-xl">
        @csrf
        <header class="flex items-center">
            <img src="https://i.pravatar.cc/100?id={{ auth()->id() }}" alt="" width="40" height="40" class="rounded-full">
            <h2 class="ml-3 ">Want to participate?</h2>
        </header>
        <div class="mt-6">
            <textarea class="w-full text-sm focus:outline-none focus:ring"
             name="body"  
             cols="30" rows="10"
              placeholder="Quick,think of something to say!" ></textarea>
        </div>
    
        <div>
            <button type="submit" class="bg-blue-500 text-white uppercase font-semi-bold text-xs py-2 px-10 rounded-2xl hover:bg-blue-600">Post</button>
        </div>

這是對應的路線:

Route::post('post/{post:slug}/comments',[PostCommentsController::class, 'store']);

控制器:,我懷疑這裡可能有問題'user_id'=> request()->user()->id,我嘗試了多種方法來實現這種方法,例如auth()-> id, Auth::user()->id

<?php

namespace AppHttpControllers;

use AppModelsPost;


class PostCommentsController extends Controller
{
    public function store(Post $post){

        
        request()->validate([
            'body'=>'required'
        ]);

        $post->comments()->create([
            'user_id'=> request()->user()->id,
            'body' => request('body')
        ]);

        return back();
    }
}

這是評論的遷移表

Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained()->cascadeOnDelete();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->text('body');
            $table->timestamps();

帖子遷移表:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->foreignId('category_id');
    $table->string('slug')->unique();
    $table->string('title');
    $table->text('excerpt');
    $table->text('body');
    $table->timestamps();
    $table->timestamp('published_at')->nullable();
});

如果我點擊發布按鈕,我會收到上述錯誤,我已盡力解決此問題,但我無法解決。有人可以幫助我我的程式碼有什麼問題嗎?我的問題可能看起來很天真,因為我是 stackoverflow 社群的新手

P粉794851975P粉794851975318 天前601

全部回覆(1)我來回復

  • P粉952365143

    P粉9523651432023-11-06 00:33:48

    將此程式碼用於控制器

    class PostCommentsController extends Controller
    {
    public function store(Post $post){
    
        
        request()->validate([
            'body'=>'required'
        ]);
    
        $post->comments()->create([
            'user_id'=> optional(auth()->user())->id,
            'body' => request('body')
        ]);
    
        return back();
    }
    }

    用戶必須登入

    回覆
    0
  • 取消回覆