Kikismedia's avatar

Attempt to assign property "image" on null

this is the error i am getting when i tried to create a post with image Attempt to assign property "image" on null

 public function createPost()

    {

        if (auth()->check()) {

            $this->validate();

 

            $post = Post::create([

                'user_id' => auth()->user()->id,

                'title' => $this->title,

                'category_id' => $this->category,

                'body' => $this->body,

                'slug' => Str::slug($this->title),

 

                $image = $this->photo->storeAs('posts/', Str::random(30)),

                $this->post->image = $image,

                // $this->post->save()

                // session()->flash("message", "Featured image successfully uploaded");

 

            ]);

 

 

            $users = auth()->user();

            $users->increment('points', 10);

 

            session()->flash('success_message', 'Post was added successfully!');

 

            $this->reset();

 

            return redirect()->route('post.index');

        }
0 likes
6 replies
Sinnbeck's avatar

Shouldnt that just be

$post->image = $image,
Kikismedia's avatar

@Sinnbeck thanks that's worked, no errors but the image are not been uploaded to the database

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Also you arent closing the array inside create() correctly

 $post = Post::create([

                'user_id' => auth()->user()->id,

                'title' => $this->title,

                'category_id' => $this->category,

                'body' => $this->body,

                'slug' => Str::slug($this->title),

            ]); //closing goes here
 

                $image = $this->photo->storeAs('posts/', Str::random(30)),

                $post->image = $image,

                $post->save(); //remove $this here has well

                // session()->flash("message", "Featured image successfully uploaded");

 
1 like
Sinnbeck's avatar

@Kikismedia Good. I suggest that you compare my example with your original and see if you understand the difference. Feel free to ask questions if you dont :)

Snapey's avatar

or

$post = Post::create([
        'user_id' => auth()->user()->id,
        'title' => $this->title,
        'category_id' => $this->category,
        'body' => $this->body,
        'slug' => Str::slug($this->title),
        'image' => $this->photo->storeAs('posts/', Str::random(30)) ?? null,
    ]);
2 likes

Please or to participate in this conversation.