@sturm post your update method, definitely something is there
putJson() results in "No query results for model"
Modifying a tutorial from Laravel Daily, I have two models, User and Vehicle, that share a many-to-many relationship through the user_vehicle table. This is done because it's possible that two (or more) users can be listed as drivers of the same vehicle. And, of course, they could be drivers of more than one vehicle.
I have a partial test built that creates one of each, attaches them to each other, and then attempts to call an endpoint to update the Vehicle. However, it never even hits the endpoint and, instead, I get a "No query results for model" error message in the response.
Here's the test in question. It doesn't assert anything just yet because I cannot even get to that point; I'm just logging out the content of the response:
public function testUserCanUpdateTheirVehicle()
{
$user = User::factory()->create();
$vehicle = Vehicle::factory()
->hasAttached($user)
->create();
$response = $this->actingAs($user)->putJson('/api/v1/vehicles/' . $vehicle->id, [
'plate_number' => 'AAA123',
]);
var_dump($response->getContent());
The content of the response:
string(13771) "{
"message": "No query results for model [App\Models\Vehicle] 1",
"exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
"file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php",
"line": 408,
"trace": [
[...]
The error seems to happen on the line where I am attempting to call the endpoint using a putJson() method while actingAs() the user. The endpoint in my API's router:
Route::apiResource('vehicles', VehicleController::class);
There's no point in my posting the update() controller method in question because, as far as I can tell, the test never even goes into it.
Is my syntax wrong on that line of the test? Did I forget something?
@Sturm found it. You forgot to change the Global scope, so it's trying to search for a vehicle with user_id field which isn't filled anymore:
app/Models/Vehicle.php:
class Vehicle extends Model
{
protected static function booted(): void
{
static::addGlobalScope('user', function (Builder $builder) {
$builder->where('user_id', auth()->id());
});
}
Please or to participate in this conversation.