The error "No query results for model [App\Models\Resource]" typically occurs when you try to retrieve a model instance that doesn't exist in the database. However, in your case, you are using the pluck method, which should not throw this error. The pluck method returns an array of values for a given column and does not throw an exception if no results are found.
Here are a few steps to troubleshoot and resolve this issue:
-
Check the Model and Namespace: Ensure that the
Resourcemodel exists and is correctly namespaced. The model should be located atApp\Models\Resource. -
Check Database Connection: Ensure that your application is correctly connected to the database and that the
resourcestable exists. -
Check Data in Database: Ensure that there are records in the
resourcestable that match theteam_idandtypeconditions. -
Error Handling: Add error handling to your service method to catch any potential issues.
Here is an updated version of your service and controller code with added error handling:
Service Code
namespace App\Services;
use App\Models\Resource;
use Illuminate\Support\Facades\Log;
class AircraftService
{
public function getAllModels($workspace_id)
{
try {
$models = Resource::where('team_id', $workspace_id)
->where('type', 'aircraft')
->distinct()
->pluck('model');
return $models;
} catch (\Exception $e) {
Log::error('Error fetching models: ' . $e->getMessage());
return collect(); // Return an empty collection in case of error
}
}
}
Controller Code
namespace App\Http\Controllers;
use App\Services\AircraftService;
use Illuminate\Http\JsonResponse;
class AircraftController extends Controller
{
protected $service;
public function __construct(AircraftService $service)
{
$this->service = $service;
}
public function getModels($workspace_id): JsonResponse
{
$models = $this->service->getAllModels($workspace_id);
return response()->json($models);
}
}
Route
use App\Http\Controllers\AircraftController;
Route::get('/{workspace_id}/aircrafts/models', [AircraftController::class, 'getModels'])->name('workspace.aircrafts.models');
Additional Debugging
If the issue persists, you can add some debugging statements to check the values being used in the query:
public function getAllModels($workspace_id)
{
try {
Log::info('Fetching models for workspace_id: ' . $workspace_id);
$models = Resource::where('team_id', $workspace_id)
->where('type', 'aircraft')
->distinct()
->pluck('model');
Log::info('Models fetched: ' . $models->toJson());
return $models;
} catch (\Exception $e) {
Log::error('Error fetching models: ' . $e->getMessage());
return collect(); // Return an empty collection in case of error
}
}
This will log the workspace_id and the fetched models, which can help you identify any issues with the data or query.
By following these steps, you should be able to identify and resolve the issue causing the "No query results for model" error.