Browse AI Field GuideForum Podcast
All ThreadsLeaderboard
  1. Discussions

    1. Popular This Week
    2. Popular All Time
    3. Solved
    4. Unsolved
    5. No Replies Yet

nekooee's avatar

when run test the middleware can't access database data

when run test the middleware can't access database data. my middleware (Localization.php) is: public function handle(Request $request, Closure $next) { $locale = $request->segment(1); $languages = Language::enabledLanguages()->get(); foreach ($languages->toArray() as $key => $language) { $locales[$key] = $language['locale'];

nekooee's avatar
nekooee's avatar nekooee4yrs agoTesting
5
1
Last reply by nekooee 4yrs ago
umairparacha's avatar

My registration test is falling

Here is my code <?php namespace Tests\Feature; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Testing\RefreshDatabase; use Laravel\Jetstream\Jetstream; use Tests\TestCase; class RegistrationTest extends TestCase { use RefreshDatabase; public function test_registration_screen_can_be_rendered() { $response = $this->get('/register')

umairparacha's avatar
umairparacha's avatar umairparac...4yrs agoTesting
2
1
Last reply by umairparacha 4yrs ago
orest's avatar

test vue components

If for example you have a like button Vue component, which is reused in many Vue components. Do you make a test specifically for that like button and that's it ? Do you test every time you use it in a view/component ?

orest's avatar
orest's avatar orest4yrs agoTesting
0
1
FrazeColder's avatar

PHPUnit how to write a Laravel Nova Observer test

Hi, I would like to write a test for my CommentObserver. This observer is only registered in the NovaServiceProvider but not the AppServiceProvider. This means I cannot test my observer by using my own Controllers. In my eyes I have 3 ways to test my observer: Either performing a feature test by sending a post request to the Nova API Mocking the observer by calling the functio

FrazeColder's avatar
FrazeColder's avatar bugsysha4yrs agoTesting
15
3
Last reply by bugsysha 4yrs ago
GimmeMylanta's avatar

Logout test using sanctum not returning as expected

Hey All, I am in the process of writing Sanctum tests, and I have come to the Logout method, but it seems to be doing some strange things. My Logout route is; Route::post('logout', [Auth\AuthenticationController::class, 'logout'])->middleware('auth:sanctum'); Notice it has the auth.sanctum middleware attached to it which should cause a unauthorized if someone tries to hit i

GimmeMylanta's avatar
GimmeMylanta's avatar GimmeMylan...4yrs agoLaravel
0
1
david001's avatar

Dusk not showing green status on correct test

Hi, My dusk test was alright before. It used to show me green status in my terminal and red whenever test fails. But now on correct test it showing this message instead of green status. My test is correct. Need your help. Thanks example public function testExample() { $this->browse(function (Browser $browser) { $browser->loginAs(User::find(1))

david001's avatar
david001's avatar david0015yrs agoTesting
0
1
danilchican's avatar

request()->route() is empty using phpunit test

Hi everyone! Laravel: 6.20 I need to test my GET http request but I faced with the issue related to request()->route() function call. I have a trait with custom boot method which is used in Post model. Inside boot method to apply a global scope or not I have a condition: if(!request()->routeIs('admin.*')) { static::addGlobalScope('published', function (Builder $b

danilchican's avatar
danilchican's avatar danilchica...5yrs agoEloquent
0
1
Ezrab_'s avatar

Laravel unit test doesn't validate correctly

I'm using laravel fortify's default login and register functionalities to test the login route in my application. For some reason though my test is failing. { "message": "The given data was invalid." "errors": { "email": [ 0 => "These credentials do not match our records." ] } } My code is: public functio

Ezrab_'s avatar
Ezrab_'s avatar tykus5yrs agoLaravel
4
1
Last reply by tykus 5yrs ago
Cobs's avatar

Should I test my permissions in Feature tests ?

Hello, I use policies to check if a user is allowed to use a specific API route. Should I bother testing permissions with a Feature test. Well, obviously, my permissions should be tested but I can't find an easy way to setup or mock the permission system other than creating the whole fixture into the database. Moreover the policy class is already unit tested. Any idea about how

Cobs's avatar
Cobs's avatar Cobs5yrs agoTesting
2
1
Last reply by Cobs 5yrs ago
malsowayegh's avatar

API test: testing with filters

Hello, I have the following json response of a filtered request by status_id = 2 { "data": [ { "id": 1, "fund_code": "FD5-9-1", "status_id": 2, "reason": "Dolor est blanditiis aspernatur non laboriosam maxime.", "amount": 112.44

malsowayegh's avatar
malsowayegh's avatar bugsysha5yrs agoTesting
1
1
Last reply by bugsysha 5yrs ago
boxxroom's avatar

No notifiable given. (PHPUnit / artisan test)

I seem to be experiencing (what I feel) is weird behaviour with a given test. The weird behaviour being when tested in isolation I get green. When testing the entire suit and/or test folder it lives in it fails. No notifiable given. The Test: /** @test */ public function it_can_send_a_notification_when_a_user_has_completed_enrolment() { $this->withoutExcepti

boxxroom's avatar
boxxroom's avatar boxxroom5yrs agoTesting
0
1
laracastsluvr's avatar

Possible to change DB Driver on specific test class?

Hello, my question is same as the title. Is it possible to use a different database driver for one specific test class? I'm currently using in_memory sqlite for testing, but I have a specific feature I need to test which makes use of MySQL user declared variables using the := assignment operator. The := assignment operator (or maybe user variables) isn't supported by SQLite fro

laracastsluvr's avatar
laracastsluvr's avatar laracastsl...4yrs agoTesting
4
1
Last reply by laracastsluvr 4yrs ago
sevenTopo's avatar

Unit Test : Access child properties from parent class

Hi Folks ! I have a situation here related to PHP OOP...im trying to write unit test for the class TypeAlert.php bellow : final class TypeAlert extends Enum { const INFO = 0; const SUCESS = 1; const WARNING = 2; const ERROR = 3; } In the other hand i have the parent class defined as bellow Enum.php: use App\Enums\Exceptions\EnumN

sevenTopo's avatar
sevenTopo's avatar sevenTopo5yrs agoLaravel
2
1
Last reply by sevenTopo 5yrs ago
ssquare's avatar

Simple store test getting failed

I am trying to learn a test in laravel, and I have written a simple test to test the store action. But, it is showing error as : • Tests\Feature\CustomerTest > create customer success Illuminate\Database\QueryException SQLSTATE[HY000]: General error: 1 no such table: users (SQL: insert into "users" ("name", "email", "email_verifie

ssquare's avatar
ssquare's avatar Sergiu175yrs agoTesting
1
1
Last reply by Sergiu17 5yrs ago
Foks's avatar

Test passes, but doesn't on GitHub via GitHub actions

Hi! So lately I've noticed that my GitHub action test suite has begun to fail, which I initially tracked down to failing test locally. Now that my test passes locally, I expect them to pass on GitHub actions, but they don't. Any ideas on why this could happen?

Foks's avatar
Foks's avatar waldemar_e...2yrs agoTesting
8
169
Last reply by waldemar_enns 2yrs ago
dorinniscu's avatar

PHPUnit test fails when testing images

Laravel Version: 8.45.1 PHP Version: 8.0.7 Database Driver & Version: MySQL 8.0.25 I am trying to create a test to check the response status for an image. The image works fine in browser: https://mydomain.test/storage/images/j2L3G12eel9sqsuNSGOYmcdqwUdchZtsfFGMeY90.jpg Also Http get works fine: $response = Http::get('https://mydomain.test/storage/images/j2L3G12eel9sqsuNSG

dorinniscu's avatar
dorinniscu's avatar bugsysha5yrs agoTesting
1
1
Last reply by bugsysha 5yrs ago
ahoi's avatar

Test Passport-Login

Hello everybody, I'd like to write a test that checks whether a user is able to log in using the LoginController's method. This is the controller's method: public function login(Request $request) { $this->validate($request, $this->rules(), $this->validationErrorMessages()); $request = Request::create('/oauth/token', 'POST', [

ahoi's avatar
ahoi's avatar ahoi5yrs agoTesting
6
1
Last reply by ahoi 5yrs ago
pratamatama's avatar

Do you double test TDD-based API in 3rd party app like Postman?

So, I just finished my TDD, I wonder if it is necessary to double test it in Postman.. What do you think?

pratamatama's avatar
pratamatama's avatar pratamatam...5yrs agoTesting
2
1
Last reply by pratamatama 5yrs ago
ahmeda's avatar

General error: 1 no such table: fresh.admins in Laravel Unit Test

I have created the following unit test: <?php namespace Tests\Feature\Auth; use Tests\TestCase; use Asu\Domain\Admins\Admin; use Illuminate\Foundation\Testing\RefreshDatabase; class LoginAdminTest extends TestCase { use RefreshDatabase; /** @test */ public function admin_can_login_and_see_his_token() { $admin = Admin::factory()->create();

ahmeda's avatar
ahmeda's avatar tykus5yrs agoTesting
3
1
Last reply by tykus 5yrs ago
bhojkamal's avatar

Need to design & develop exact like COPD Assessment Test (CAT) website survey form

COPD Assessment Test (CAT) website questionnaire needed - exact same. Hello, I need to develop exact template - design and develop like this - COPD Assessment Test CAT for my patient record system. In my project, I have used LARAVEL 8 and VUE.js 3 and Bootstrap 5. I have designed other screening question already. I need to add this too. If you guys have seen or know such desig

bhojkamal's avatar
bhojkamal's avatar bhojkamal5yrs agoVue
14
1
Last reply by bhojkamal 5yrs ago
kritika07's avatar

CASE SQL query not working in test suite

CASE SQL query not working in test suite

kritika07's avatar
kritika07's avatar kritika075yrs agoTesting
3
1
Last reply by kritika07 5yrs ago
zaster's avatar

Testing - Single Test Feature

php artisan test --filter UserTest gives the below output PASS Tests\Feature\AuthUserTest ✓ an auth user can visit user profile page PASS Tests\Feature\UserTest ✓ a guest can access welcome page ✓ a guest can access login page ✓ a guest can access register page I need to run only the UserTest Feature

zaster's avatar
zaster's avatar hsndevs3yrs agoTesting
17
49
Last reply by hsndevs 3yrs ago
zaster's avatar

Test unit not found

I get this error Test directory "/home/myusername/myproject/./tests/Unit" not found When I run php artisan test

zaster's avatar
zaster's avatar zaster5yrs agoLaravel
2
1
Last reply by zaster 5yrs ago
jose.ares's avatar

Laravel Sanctum feature test logout HTTP incorrect response

Hi all, I'm having issues when implementing feature tests for logging out Laravel Sanctum. I have the middleware applied to some route like so: Route::group(['middleware' => ['auth:sanctum', 'user.active']], function () { Route::get('/profile', 'Auth\Controllers\ProfileController@show')->name('profile.show'); }); Login is working fine, returning a JSON response with a

jose.ares's avatar
jose.ares's avatar bugsysha5yrs agoLaravel
1
1
Last reply by bugsysha 5yrs ago
Sinres's avatar

Test User Controller and recive bad verify email url

Hello Guy's! In my API project when I created new users then user receive email verification on email address. He successively receives an email about changing the default password. Everything works fine manually but when I create test create new user and run this by artisan test I receive email without :8000 only to verify email button url for set default password url all it's

Sinres's avatar
Sinres's avatar Bcrypt5yrs agoLaravel
1
1
Last reply by Bcrypt 5yrs ago
jgravois's avatar

Simplest Test ($this->assertAuthenticatedAs($user);) Failing???

Ok, I feel like I read the entire Google last night ... arrggg! I cannot get this test to pass nor can I see why. If I comment out $this->assertAuthenticatedAs($user);, it passes. /** @test */ public function user_can_login_with_proper_credentials (): void { $this->withExceptionHandling(); $user = User::factory()->create([ 'email' =

jgravois's avatar
jgravois's avatar jgravois5yrs agoTesting
2
1
Last reply by jgravois 5yrs ago
Crazylife's avatar

How to write a test case for generate PDF?

How do i test if i passed correct data to generate PDF? $data = Model::where('id', 1)->first(); $date = Carbon::parse($data->created_at)->format('d/m/Y'); $pdf = PDF::loadView('printPDF', compact('data', 'date')); return $pdf->download($data->runningNumber . '.pdf'); This is the sample of my controller. How can i create a test case for this? I want to check

Crazylife's avatar
Crazylife's avatar laracoft5yrs agoGeneral
6
1
Last reply by laracoft 5yrs ago
saulsolorzano's avatar

Job not being dispatched in test

Hi! I'm using laravel 8.5 and laravel Sail. I'm trying to test a job but is not being dispatched, no matter what I do. Here's my code Event::fake(); TheProductDoesNotExists::dispatch($this->channel, $document['product'], $document['name']); Event::assertDispatched(TheProductDoesNotExists::class); And I get The expected [App\Jobs\TheProductDoesNotExists] event was not dispa

saulsolorzano's avatar
saulsolorzano's avatar rodrigo.pe...5yrs agoTesting
3
2
Last reply by rodrigo.pedra 5yrs ago
ecd's avatar

How to test validation rules withoutExceptionHandling

Hello, I'm onto a new personal project and following Uncle Bob's advices (Clean Code) I thought it'd be good to give it a shot to test every line of code. That includes testing validation rules, which I wasn't familiar with until now. But I have a bit of a phpunit workflow problem. I'd like to add $this->withoutExceptionHandling() to my TestCase's setUp() because it is painf

ecd's avatar
ecd's avatar ecd5yrs agoTesting
4
1
Last reply by ecd 5yrs ago
jrdavidson's avatar

Session Data Missing For Test

I'm trying to figure out what I'm doing wrong in my test. Currently my test passes until it hits the assertSessionHas('company_id', null) part of the test. Currently the test is failing due to Session is missing expected key [company_id]. I go through the browser and I see the company_id in the session. Not sure what I"m doing wrong. /** @test */ public function a_sup

jrdavidson's avatar
jrdavidson's avatar chaudigv5yrs agoTesting
1
1
Last reply by chaudigv 5yrs ago
Fiton012's avatar

Model factory increment value and reset for each test

I have my ProductFactory as below: class ProductFactory extends Factory { protected $model = Product::class; public function definition(): array { static $order_column = 1; return [ 'title' => $this->faker->sentence, 'order_column' => $order_column++, ]; } } This works as it increments the order_col

Fiton012's avatar
Fiton012's avatar martinbean5yrs agoTesting
1
1
Last reply by martinbean 5yrs ago
Swaz's avatar

How do you test Inertia.js?

I know there used to be an Inertia testing packing, but it has since been merged into Laravel as the new json testing helpers. But I don't understand how I would test a simple controller method like this: public function show(Client $client) { return Inertia::render('Clients/Show', [ 'client' => [ 'id' => $client->id, 'name' => $c

Swaz's avatar
Swaz's avatar kei_mx2yrs agoInertia
6
6
Last reply by kei_mx 2yrs ago
deansatch's avatar

use localhost instead of test domain with homestead

I need to develop with Google's oauth2 api which requires a top level domain, but it also allows localhost. The app I'm working on is currently setup in homestead with a .test domain but for this I am going to need it to be served as http://localhost instead. Any ideas how I can do that? I've tried specifying it in my yaml file (map: localhost) but it didn't work

deansatch's avatar
deansatch's avatar rpm5yrs agoLaravel
4
1
Last reply by rpm 5yrs ago
Drummer's avatar

How to create a test for a pivot table?

I want to create a test for the controller. There are three tables, Roles, Categories and Categories_roles, the connection is many to many. Controller: /** * Update connections. * * @return \Illuminate\Contracts\Support\Renderable */ public function update(Request $request) { $input = $request->get('category', []); foreach (Category::all() as $category) {

Drummer's avatar
Drummer's avatar fylzero5yrs agoLaravel
1
1
Last reply by fylzero 5yrs ago
Kusanagi's avatar

Test my website for ram usage...

Hello, is there a way to test my website to see how fast it is with a certain number of traffic, so that I could better plan on which web hosting server I should get ?

Kusanagi's avatar
Kusanagi's avatar jeevamugun...5yrs agoTesting
4
1
Last reply by jeevamugunthan 5yrs ago
mohib_ullah's avatar

Phpunit test faild on a new package

i was trying to test my newly created package by running bellow code public function testBasicTest() { $response = $this->call('GET','/'); $response->assertStatus(200); } and getting this error vagrant@homestead:~/home-rent/Catalog$ composer test > vendor/bin/phpunit

mohib_ullah's avatar
mohib_ullah's avatar tisuchi5yrs agoTesting
1
1
Last reply by tisuchi 5yrs ago
Fiton012's avatar

Test a notification is shown that is outside of Livewire component

I have a module Product\Update that when is updated an event is dispatched using $this->dispatchBrowserEvent('notify', '`Product updated successfully.'); This event is send to the browser and a toaster notification is poped-up. The toaster notification is outside of the Product\Update component but in the html <body>. As I checked the below code fails because

Fiton012's avatar
Fiton012's avatar tykus5yrs agoLivewire
1
1
Last reply by tykus 5yrs ago
Ajvanho's avatar

Command test

How to test console command ? Received Mockery_1_Illuminate_Console_OutputStyle::askQuestion(), but no expectations were specified public function test_command_import_wordpress() { $this->artisan('import:wordpress') ->expectsOutput('Wordpress database imported successfully!'); }

Ajvanho's avatar
Ajvanho's avatar martinbean5yrs agoLaravel
1
1
Last reply by martinbean 5yrs ago
mustafaabdujalil's avatar

Unit test

I generated pdf and download it by using barryvdh/laravel-dompdf package and I want to ceate unit test for this function any help please

mustafaabdujalil's avatar
mustafaabdujalil's avatar mustafaabd...5yrs agoLaravel
2
1
Last reply by mustafaabdujalil 5yrs ago
soufyaneyassin's avatar

PHPUnit test laravel

hey everyone i'am trying to run the following test: public function a_user_can_register() { $user = User::factory()->create(); $response = $this->post('/register', $user); $response->assertRedirect('/register-step-2'); $this->assertDatabaseHas('users', $user); } but i am getting this error : SQLSTATE[HY000] [1045] Access denied for

soufyaneyassin's avatar
soufyaneyassin's avatar bugsysha5yrs agoLaravel
2
1
Last reply by bugsysha 5yrs ago
ssquare's avatar

Failing Laravel Login Test

I am using fortify but trying to customize the login by using sanctum. My login code looks like: FortifyServiceProvider.php Fortify::authenticateUsing(function (Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', 'device_name' => 'required', ]

ssquare's avatar
ssquare's avatar tykus5yrs agoLaravel
3
1
Last reply by tykus 5yrs ago
ignium's avatar

Single test fails with BindingResolutionException after migrating to Laravel 8.x

I recently upgraded (with Laravel Shift) to Laravel 8.x and after tweaking a few of my tests, my entire test suite passes except for a single test with the following error: There was 1 error: Tests\Feature\UserProfileVerificationFeatureTest::an_admin_profile_will_be_verified_once_edited Illuminate\Contracts\Container\BindingResolutionException: Target class [web] does not exi

ignium's avatar
ignium's avatar neilstee5yrs agoLaravel
14
2
Last reply by neilstee 5yrs ago
laracoft's avatar

Model does not seem to refresh/fresh in test

I have the following test that intermittently fails. It always passes if I put a breakpoint before asserting, seems to be a race condition, but I can't pinpoint where. Tests are being done on a real MySql database. I also tried both $updated = $d->fresh(); and $d->refresh(); and they always fail (not intermittently). How do I make sure $updated indeed gets reloaded? publi

laracoft's avatar
laracoft's avatar neilstee5yrs agoEloquent
9
1
Last reply by neilstee 5yrs ago
JonattanD's avatar

Test fails when running all test

I have multiple test and when I run each of them individually they all pass, but when I run all test at once one of them always fails, in this case it's the "user_can_login" test, it fails with a 401(Unauthorized). <?php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class UserTest extends TestCase { use Refr

JonattanD's avatar
JonattanD's avatar JonattanD5yrs agoTesting
8
1
Last reply by JonattanD 5yrs ago
phpMick's avatar

Test tokenCan()

Hi, I'm trying to test some code which is protected by tokenCan() (https://laravel.com/docs/8.x/passport#checking-scopes-on-a-token-instance). How can I test this code? The tokenCan() always fails because middleware is disabled in my tests (and therefore there isn't a token). Cheers, Mick

phpMick's avatar
phpMick's avatar phpMick5yrs agoTesting
3
1
Last reply by phpMick 5yrs ago
stefanhaerter's avatar

Laravel Artisan Test Command

Hi everyone, I use Laravel 8 in a project with Tests. I wrote a custom artisan command which runs the test command and mails its output to a mail address. Unfortunately, in the output there are ANSI sequences. If I try to run the command "php artisan test --no-ansi", I get the response "Unknown option "--no-ansi"". Has anyone a tip? Kind regards St

stefanhaerter's avatar
stefanhaerter's avatar stefanhaer...5yrs agoTesting
6
1
Last reply by stefanhaerter 5yrs ago
BrokeYourBike's avatar

How to test the job with dispatchSync?

I have a job, that dispatched the other job. class JobA implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public function handle() { // some code here JobB::dispatch(); } } Before dispatchNow deprecation, I used to test my job like this: class JobATest extends TestCase { use RefreshDatabase; /** @test */ public

BrokeYourBike's avatar
BrokeYourBike's avatar BrokeYourB...5yrs agoTesting
1
1
Last reply by BrokeYourBike 5yrs ago
Ajvanho's avatar

Test DB::table

How to test DB:table, create factory, without model ? $post= DB::table('posts')->insert([ 'txt' => 'htyehytyteh', 'code' => 200, ]);

Ajvanho's avatar
Ajvanho's avatar Ajvanho5yrs agoLaravel
2
1
Last reply by Ajvanho 5yrs ago
Wakanda's avatar

Derive a Laravel search query from a provided test.

Hi, I am working on a project that has some tests implemented and i would want to derive a search query based on the provided test case Test public function test_index_returns_based_on_name_search() { Company::factory()->count(20)->create(); Company::factory()->create(['name' => 'Test Name']); $result = $this->getJson(route("c

Wakanda's avatar
Wakanda's avatar Wakanda5yrs agoLaravel
5
1
Last reply by Wakanda 5yrs ago
sylvain92's avatar

unit test view::share return

hi i try to test unit but view::share trigger an issue ErrorException: Undefined variable: $newestPosts here my code in PageTest public function testHomepage() { $this->withoutExceptionHandling(); $response = $this->get('/'); $response->assertStatus(200); } in app.blade.php @foreach($newestPosts as $post) <a href="{{ route

sylvain92's avatar
sylvain92's avatar martinbean5yrs agoTesting
6
1
Last reply by martinbean 5yrs ago

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.

Want us to email you occasionally with Laracasts news?

Nine out of ten doctors recommend Laracasts over competing brands. Come inside, see for yourself, and massively level up your development skills in the process.

Learn
BrowseSeriesCreatorSeriesLaravel PathLarabitsPlayground
Discuss
ForumPodcastSupport
Extras
Gift CertificatesApparelFAQiOS AppTerms
Social
X(Twitter)TikTokYoutube

© Laracasts 2026. All rights reserved. Yes, all of them. That means you, Todd.

Proudly hosted with Laravel Forge and DigitalOcean.