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

temwa's avatar
Level 1

Laravel - No query results for model When Using An Array Passed Via Ajax

I am getting the error;

No query results for model [App\UserProfile] 0

When I use findOrFail using an array passed with AJAX in a foreach loop. If I manually create the array in PHP, the entity is found using the array values. When I do a print_r() on the array in PHP, the array is present in both the AJAX array and the manually created array.

AJAX Code

function checkChatOnlineStatus()
{
    var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}

    $.ajax({
        url: '/check-chat-online-status',
        method: 'get',
        data: {chatUserProfileIds: chatUserProfileIds},
        dataType: 'json',
        success: function(response) {

        }
    });
}

PHP Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\UserProfile;

class CheckRunningParametersController extends Controller
{
    public function checkChatOnlineStatus()
    {
        $chatUserProfileIds = $_GET['chatUserProfileIds'] ? $_GET['chatUserProfileIds'] : NULL;
        //$chatUserProfileIds = array('key-60' => 60, 'key-52' => 52, 'key-2' => 2, 'key-3' => 3);

        /* Check Status For Chat Contacts */
        if ($chatUserProfileIds != NULL)
        {
            foreach ($chatUserProfileIds as $key => $value)
            {


                $userProfile = UserProfile::findOrFail((int)$value);

                $chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();

            }
        }

        return $chatOnlineStatus;
    }
}
0 likes
21 replies
temwa's avatar
Level 1

@Dhaval_patel , The above PHP Code is the entire controller (CheckRunningParametersController)

Goldoni's avatar

Hi, try that

// routes/web.php

Route::get('check-chat-online-status/{chatUserProfileIds ?}', 'CheckRunningParametersController@checkChatOnlineStatus');
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\UserProfile;

class CheckRunningParametersController extends Controller
{
  public function checkChatOnlineStatus($chatUserProfileIds = null)
    {
        /* Check Status For Chat Contacts */
        $chatOnlineStatus['contacts'] = [];

        if (! is_null($chatUserProfileIds))
        {
            $users = UserProfile::whereIn('id',  array_values(chatUserProfileIds ))->get();

        $chatOnlineStatus['contacts'] = $users->map(function ($user) {
                 return [$user->id, $user->isOnline();
            });
        }

         return Response::json($chatOnlineStatus, 200, [], JSON_NUMERIC_CHECK);
    }
}

Saikishore's avatar

Hi

As per my knowledge, it is not a good idea to use "Get" method for array content.

Also check the json you are using .. It is not in Array format.

var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}

try to convert json to Array formate in PHP and then send this array to foreach

json_decode($chatUserProfileIds); 
temwa's avatar
Level 1

@Goldoni , how do I format the URL in the Javascript to pass the array through the route parameters?

temwa's avatar
Level 1

@kishoresai438 , I have changest method to POST, converted JSON to PHP array;

$chatUserProfileIds = isset($_POST['chatUserProfileIds']) ? json_decode($_POST['chatUserProfileIds'], true) ;

I can't do dd() for an AJAX request but print_r() gives;

print_r($chatUserProfileIds);

//Result

array(4) {
  ["key-60"]=>
  int(60)
  ["key-52"]=>
  int(52)
  ["key-2"]=>
  int(2)
  ["key-3"]=>
  int(3)
}

Still doesnt work.

Saikishore's avatar

What is the result for this..

foreach ($chatUserProfileIds as $key => $value)
            {

    echo $value; exit;
                $userProfile = UserProfile::findOrFail((int)$value);

                $chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();

            }
Saikishore's avatar

try with this..

$userProfile = UserProfile::find($value);
if($userProfile) {
//write your logic...
}
temwa's avatar
Level 1

@kishoresai438 , with that I get

Call to a member function isOnline() on null in CheckRunningParametersController.php (line 31)

Saikishore's avatar

ok!!!

isOnline is table column (or) method in your Model?

if it is method use the below.....

$userProfile = UserProfile::find($value);
if($userProfile) {
//write your logic... 
    $chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
} else {
   //write your logic, if not found the record... 
}

if it is column name,

$userProfile = UserProfile::find($value);
if($userProfile) {
//write your logic...
    $chatOnlineStatus['contacts'][$key] = $userProfile->isOnline;
} else {
   //write your logic, if not found the record... 
}
temwa's avatar
Level 1

@kishoresai438 , the record is there in the database. the same code works if I use a manual array and not one passed from the AJAX request.

So, if I say ;

$chatUserProfileIds = array('key-60' => 60, 'key-2' => 2, 'key-3' => 3, 'key-52' => 52);

It finds the record just fine, but will not find it if I say

$chatUserProfileIds = isset($_POST['chatUserProfileIds']) ? json_decode($_POST['chatUserProfileIds'], true):
temwa's avatar
Level 1

@Dhaval_patel . Very weird indeed. When I try with Query Builder, I get the error bellow but the method isOnline() is in the model "UserProfile" that is included with a use statement at the beginning of the controller.

Call to undefined method Illuminate\Database\Query\Builder::isOnline()

Dhaval_patel's avatar

@temwa Okay let's debug line by line

foreach ($chatUserProfileIds as $key => $value)
            {
                $userProfile = UserProfile::findOrFail((int)$value);
        echo $userProfile; exit;
                $chatOnlineStatus['contacts'][$key] = $userProfile->isOnline();
            }

Is this working for 60?

temwa's avatar
Level 1

Okay @Dhaval_patel . That is working for 60;

// Result
{id: 60, user_id: 133, email: "[email protected]", name: "Barnett Msiska", city: null,…}
bio
:
null
city
:
null
country
:
null
cover_image
:
"../../../no-image/cover-noimage.png"
created_at
:
"2017-12-02 11:52:32"
email
:
"[email protected]"
id
:
60
name
:
"Barnett Msiska"
updated_at
:
"2017-12-02 11:52:32"
user_id
:
133
user_image
:
"../../../no-image/user-noimage.png"
Dhaval_patel's avatar

Cool now please debug or show us the model's method isOnline() must be corrupted

temwa's avatar
Level 1

@Dhaval_patel , I dont think the problem is with the isOnline() method. If I place an echo statement or a print_r() statement before the call to find(), it executes without an error. If I remove that statement to echo or print_r() statement just before calling find() it flags the error;

No query results for model [App\UserProfile] 0

Here is the method, however;

// App\UserProfile

    /* User Online Status */
    public function isOnline()
    {
        return Cache::has('user-is-online-' . $this->id);
    }
Dhaval_patel's avatar

@temwa then definitely there is a problem in your array one of its value is not present in userprofile table.

temwa's avatar
Level 1

@Dhaval_patel . The values are there in the array and as you saw with the echo statement you asked me to do, it does go through with the echo statement but not the database query.

Besides, it gets stuck on the first pass which is id- 60 and I have checked that id is there in the ajax array, the manual array and in the database except it doesn't work for the AJAX array unless an echo or print_r is called first.

There is surely a problem with the AJAX array and it's not that a value is missing. Its got to be something else with that value that's causing the query to fail. I just don't know what.

temwa's avatar
temwa
OP
Best Answer
Level 1

I found the problem. Silly mistake really. I moved the assignment of data to the JavaScript object used in the array to the global scope and that seems to work.

// Moved this to global scope in the Javascript
var chatUserProfileIds = {"key-60":60,"key-52":52,"key-2":2,"key-3":3}

Please or to participate in this conversation.