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

lara66806's avatar

How to test succesful POST of an entity when validated column is merged into request

Hi All!

I have a unique scenario that allows me to not test on of my Routes. I have a Post with the column author_id which I am trying to include after the form request so that it forces the post author_id to be the Authenticated user. This prevents a malicious User from changing a User ID in the form fields and adding a Post as a different User.

However... I've found that I cannot test this code and I receive 403 errors on trying to pass a Post with author_id, as author_id is not included in the SavePost validation rules. I also cannot remove author_id and post because Auth::user()->id is not recognised in the controller method when running as a test.

My Test

 $post = factory(Post::class)->create(
    [
         'author_id' => $this->user->id
    ]
);

$this->post('/posts', $post->toArray())
    ->assertStatus(200);

My POST method

public function store(SavePost $request)
{
    $request->merge(['author_id' => Auth::user()->id]);

    $post = Post::create($request->all());
}

I could just include author_id in the validation rules as it's not currently in the Post create form so what are the odds of someone guessing the field and adding?

Anyone ever had similar encounters when looking after the security of basic POST/UPDATE methods?

0 likes
3 replies
tykus's avatar

Not such a unique situation; simply authenticate the user whenever you send the request using the actingAs() helper:

 $post = factory(Post::class)->create([
    'author_id' => $this->user->id
]);

$this->actingAs($this->user)->post('/posts', $post->toArray())
    ->assertStatus(200);
lara66806's avatar

Apologies, I should have also stated that I am acting as a User, just within the construct. It is also definitely a valid User as it works for all other tests.

lara66806's avatar

After doing some research I have found that Laravel Policies https://laravel.com/docs/5.8/authorization is exactly what I'm looking for when it comes to update methods. However on a store method I don't have access to an existing Post author_id to compare the existing user->id too. I just want to pass through the authenticated user to be the author_id.

Please or to participate in this conversation.