Click here to Skip to main content
14,700,041 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am trying to make a like and dislike button with ajax to save it to the database.
But, it works sometimes and sometimes it gives error response in the network tab of inspect, Call to a member function save() on a non-object.

this is my LikeController.php :

<?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Depress;
    use App\Http\Requests;
    
    class LikeController extends Controller
    {
        public function postLike(Request $request)
        {
            $post_id = $request->input('postId');
            //dd($post_id);
            $post = Depress::find($post_id);
            $post['like'] = $post['like'] + 1;
            $post->save();
            return null;
        }
    
        public function postDislike(Request $request)
        {
            $post_id = $request->input('postId');
            $post = Depress::find($post_id);
            $post['dislike'] = $post['dislike'] + 1;
            $post->save();
            return null;
        }
    }


The problem seems to be in

$post->save();


But, I don't know what is the problem.

Anyone please come to the rescue, I have been stuck here for the past 2 days.

<pre lang="PHP">


What I have tried:

I have tried to dd($post) and it seems to give proper value.
Posted
Updated 30-Jun-16 3:54am
Comments
Sergey Alexandrovich Kryukov 29-Jun-16 12:17pm
   
Use the debugger and/or logging. It could be the undefined object or something else. For some information, test typeof on this object.
—SA

1 solution

I do not think, this code has any issue.

$post = Depress::find($post_id);
$post['like'] = $post['like'] + 1;
$post->save();


This should work definitely, only if $post_id has the right value (the one it presents in the DB).

What I have tried
I did check the above thing and I found this error Call to a member function save() on a non-object when $post_id contains the id (1000) which is not present in the DB.

Please check the same (check whether id exist in DB or not) and if you still face the same issue, please typecast $post_id to integer and then check it.

I hope this will help you.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900