LARAVEL8:尝试访问 Null 上的“id”属性
P粉794851975
P粉794851975 2023-11-05 13:06:23
0
1
402

我是 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粉794851975
P粉794851975

最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!