简体   繁体   English

在 Laravel 中调用成员函数错误

[英]Call to a member function error in Laravel

I'm building a blog on Laravel 7 and when I try to create a post I get this error:我正在 Laravel 7 上建立一个博客,当我尝试创建一个帖子时,我收到此错误:

Call to a member function categories() on bool

Here is my store method from my controller:这是我的控制器中的 store 方法:

public function store(Request $request)
    {
        // Validate incoming data
        $this->validate($request, [
            'title' => 'required',
            'image' => 'required',
            'categories' => 'required',
            'body' => 'required',
        ]);

        $data = array();
        $data['title'] = $request->title;
        $data['slug'] = str_slug($request->title);
        $data['user_id'] = Auth::id();
        $data['meta_title'] = $request->meta_title;
        $data['meta_description'] = $request->meta_description;
        $image = $request->file('image');
        $data['body'] = $request->body;
        $data['created_at'] = \Carbon\Carbon::now();

        $slug = str_slug($request->title);
        
        if($image) {
            $image_name = $slug . "-" . date('dmy_H_s_i');
            $ext = strtolower($image->getClientOriginalExtension());
            $image_full_name = $image_name . '.' . $ext;

            $upload_path = "public/assets/frontend/uploads/posts/";
            $image_url = $upload_path . $image_full_name;
            $success = $image->move($upload_path, $image_full_name);

            $data['image'] = $image_url;
            $post = DB::table('posts')->insert($data);
            

            $post->categories()->attach($request->categories);
            return redirect(route('admin.posts.index'))->with('successMsg', 'Post has been saved successfully!');
        }
}

The laravel error page has a problem with this line: laravel 错误页面有这行有问题:

$post->categories()->attach($request->categories);

I have a separate table in my database to connect a post id with a category id, it's called category_post The post content is inserted into the database except the new record in the category_post table我的数据库中有一个单独的表,用于将帖子ID 与类别ID 连接起来,称为category_post 除了category_post 表中的新记录外,将帖子内容插入到数据库中

So how do I change that code to work?那么如何更改该代码以使其正常工作? Thanks谢谢

DB::table('posts')->insert($data);

Returns true|false based on successful / failed execution of query.根据查询的成功/失败执行返回true|false If you want to write like如果你想写

$post->categories()->attach($request->categories);

Then you need mode Post and create instance like this:然后你需要模式Post并创建这样的实例:

$post = new Post;
$post->title = $request->title;
// ...
$post->save();

And then you will have instance of Post class然后你将拥有Post类的实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM