laravel 尝试读取null上的属性\“id\”

xzv2uavs  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(161)

我试图使一个职位,每次我得到错误'试图读取属性“id”的null'...附件是有问题的项目的代码,这是控制器代码

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\post;

class postController extends Controller
{
  
    //create a post
    public function store(Request $request)
    {
        $attrs = $request->validate([
            'body' => 'required|string',
        ]);

        $post = post::create([
            'body' => $attrs['body'],
            'user_id' => auth()->user()->id,
        ]);

        return response([
            'message' => 'post created',
            'post' => $post
        ], 200);

    }

字符串

czq61nw1

czq61nw11#

检查用户是否经过身份验证,以及签入数据库ID是否自动递增。

public function store(Request $request)
{
   
    if (auth()->check()) {
        $attrs = $request->validate([
            'body' => 'required|string',
        ]);

        $post = post::create([
            'body' => $attrs['body'],
            'user_id' => auth()->user()->id,
        ]);

        return response([
            'message' => 'post created',
            'post' => $post
        ], 200);
    } else {
        return response(['message' => 'Unauthorized'], 401);
    }
}

字符串

相关问题