@temwa Can you please paste your entire controller code over here.
Dec 11, 2017
21
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;
}
}
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.