php - Call to a member function error in Laravel
Get the solution ↓↓↓
I'm building a blog on Laravel 7 and when I try to create a post I get this error:
Call to a member function categories() on bool
Here is my store method from my controller:
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:
$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
So how do I change that code to work? Thanks
Answer
Solution:
DB::table('posts')->insert($data);
Returnstrue|false based on successful / failed execution of query. If you want to write like
$post->categories()->attach($request->categories);
Then you need modePost and create instance like this:
$post = new Post;
$post->title = $request->title;
// ...
$post->save();
And then you will have instance ofPost class
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: malformed utf-8 characters, possibly incorrectly encoded
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

