Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yanikkumar's avatar

Getting response()->json() as undefined in consolelog

I was working on overtrue/laravel-follow package and was using ajax call to follow a user and unfollow. scripts file includes:

$(document).ready(function(){
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $('.btn-follow').click(function() {
        let user_id = $(this).data('id');
        let object = $(this);

        $.ajax({
            type: 'POST',
            url: '/follow',
            data: { user_id: user_id },
            dataType: 'json',
            success: function(data) {
                console.log(data.success);
            },
        });
    });
});

User Controller Follow method:

public function follow(Request $request)
    {
        $authUser = Auth::user();
        $user = User::findOrFail($request->user_id);

        if ($authUser !== null && $authUser instanceof User) {
            $response = $authUser->toggleFollow($user);
        	return response()->json(['success' => $response]);
		}
    }

Routes:

Route::post('/follow', 'UserController@follow')->name('user.follow');

I'm getting undefined object in the console and no object with attached and detached. What is the problem

PS: It is surprising that method is still working and follow unfollow is working behind the scene

0 likes
30 replies
MichalOravec's avatar
public function follow(Request $request)
{
    if (Auth::check() && $user = User::find($request->user_id)) {
        return response()->json(['success' => Auth::user()->toggleFollow($user)]);
    }

    return response()->json(['success' => false]);
}
yanikkumar's avatar

here it says toggleFollow($user) is an undefined method.

and if I use instance of User again like this

if ($authUser instanceof User && $user = User::find($request->user_id)) {
            return response()->json(['success' => $authUser->toggleFollow($user)]);
        }

        return response()->json(['success' => false]);

still getting null

OOPS! :)

1 like
MichalOravec's avatar

Which means User model doesn't have toggleFollow method...

yanikkumar's avatar

I've added these ofc

use Overtrue\LaravelFollow\Followable;

class User extends Authenticatable
{
    use Followable;
}
MichalOravec's avatar

Remove vendor folder from your project and run

composer install

And never change anything in vendor folder.

1 like
yanikkumar's avatar

Did that but still the same problem. And I never changed anything in vendor.

yanikkumar's avatar

@michaloravec

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.1.3",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "^7.2",
        "intervention/image": "^2.5",
        "laravel/framework": "5.8.*",
        "laravel/socialite": "^4.2.0",
        "laravel/tinker": "^1.0",
        "nesbot/carbon": "^2.45",
        "overtrue/laravel-follow": "^2.2",
        "unisharp/laravel-filemanager": "^2.2"
    },
    "require-dev": {
        "beyondcode/laravel-dump-server": "^1.0",
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^3.0",
        "phpunit/phpunit": "^7.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\Foundation\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

yanikkumar's avatar

@michaloravec

It is just my old project I was upgrading some stuff. I upgraded to version 6 the problem is same.

MostafaGamal's avatar

First, return your request to make sure that you successfully sent it to your controller

public function follow(Request $request)
{
    retuen $request
}

if the data sent successfully to your controller then make sure that you have a user with this id, may be you sent the wrong id

$user = User::findOrFail($request->user_id); // make sure you have a user with this id
return $user

show us the code of toggleFollow method

yanikkumar's avatar

Everything is ok. as I said everything is working i.e. user is getting followed and unfollowed but the console log it logs undefined.

toggleFollow is a method inside followable trait

MostafaGamal's avatar

if the database is updated and everything work as expected then I think you forgot to return value in toggleFollow method

yanikkumar's avatar

Brother it is all correct in the traits no problem with trait, the response code is ok but the response in getting null

Snapey's avatar

have you been advised that the toggleFollow() function has a return value?

MostafaGamal's avatar

If it has no return value then why he assigned it to the $response variable ??

Snapey's avatar

for 'shits and giggles' as they say

yanikkumar's avatar

Someone suggested We shouldn't be touching the traits files of the package.Should I add something in that?

public function follow($user)
    {
        $isPending = $user->needsToApproveFollowRequests() ?: false;

        $this->followings()->attach($user, [
            'accepted_at' => $isPending ? null : now()
        ]);

        return ['pending' => $isPending];
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model|int $user
     */
    public function unfollow($user)
    {
        $this->followings()->detach($user);
    }

    /**
     * @param \Illuminate\Database\Eloquent\Model|int $user
     *
     */
    public function toggleFollow($user)
    {
        $this->isFollowing($user) ? $this->unfollow($user) : $this->follow($user);
    }

Here is the methods in the trait files. PS: I don't know why are you mocking that way?

MostafaGamal's avatar

@yanikkumar attach and detach methods both of them return null Try sync() method which returns an array of attached ids

if you want to unsync then pass an empty array to sync method

Snapey's avatar

You will see toggleFollow has no return value, hence null in your response.

And don't touch files in the vendor folder.

If you want the package to behave differently, either raise an issue with the author or create your own fork

Snapey's avatar

@mostafagamal he's using a package. The code he shows is not his to change,

He could of course just write his own version of the trait inside his model, but what's the point? I'm not really sure why he is set on getting a response other than 200.

MostafaGamal's avatar

@snapey Sorry, I didn't read this line:

Someone suggested We shouldn't be touching the traits files of the package. Should I add something in that?

I thought he is using his own trait.

yanikkumar's avatar

@snapey Code is working all good. I was just trying to use jquery and access the attach and detach method so that I can easily change the text value once follow button is clicked.

MostafaGamal's avatar

@yanikkumar You can check whether the status code is 200 in case you are just trying to change the text of the button

Snapey's avatar
Snapey
Best Answer
Level 122

query the follower status after toggle and return that.

$user = User::find($request->user_id));

Auth::user()->toggleFollow($user);

return response()->json(['following' => Auth::user()->isFollowing($user)]);

will return 200 status and true if following and false if not

2 likes
yanikkumar's avatar

Thankyou so much you cleared out my way sir. That was really helpful. I found out the way to continue further. Also this was a good idea to perform the action. Really appreciated, I was working on for getting 200 status with this but it was always returning true

$authUser->toggleFollow($user);

return response()->json(['success' => true]);

but @snapey thanks. Thanks again and thankyou all of you for your help.

Please or to participate in this conversation.