LARAVEL8: Trying to access 'id' property on Null-PHP Chinese Network Q&A
LARAVEL8: Trying to access 'id' property on Null
P粉794851975
P粉794851975 2023-11-05 13:06:23
0
1
544

I'm new to Laravel and I'm learning it from Laracast. Here is my problem, I am creating a comment form and the php code for it looks like this:

@csrf

Want to participate?

This is the corresponding route:

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

Controller:, I suspect there may be something wrong here'user_id'=> request()->user()->id, I tried multiple ways to implement this approach , for exampleauth()-> id, Auth::user()->id

validate([ 'body'=>'required' ]); $post->comments()->create([ 'user_id'=> request()->user()->id, 'body' => request('body') ]); return back(); } }

This is the migration table of comments

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

Post migration table:

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

If I click the publish button I get the above error, I have tried my best to fix this but I can't resolve it. Can anyone help me what's wrong with my code? My question may seem naive as I am new to the stackoverflow community

P粉794851975
P粉794851975

reply all (1)
P粉952365143

Use this code for the controller

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

User must log in

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!