I'm struggling to make my Feature Tests run with Laravel. I ran out of options. This is the error I get (with withoutExceptionHandling to show the URL):
• Tests\Feature\ClientTest > example
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
GET http://localhost/sunny-camping/welcome
at vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php:416
412▕ * #return \Symfony\Component\HttpFoundation\Response
413▕ */
414▕ protected function renderException($request, Throwable $e)
415▕ {
➜ 416▕ return $this->app[ExceptionHandler::class]->render($request, $e);
417▕ }
418▕
419▕ /**
420▕ * Get the application's route middleware groups.
+1 vendor frames
2 tests/Feature/ClientTest.php:19
Illuminate\Foundation\Testing\TestCase::get()
Obviously if I click the URL everything works fine, but the test gives me 404... The page itself is default welcome page from Laravel. Now for the files:
ClientTest.php
<?php
namespace Tests\Feature;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
class ClientTest extends TestCase
{
/**
* A basic feature test example.
*
* #return void
*/
public function test_example()
{
$this->withoutExceptionHandling();
$response = $this->get('/welcome');
$response->assertStatus(200);
}
}
web.php
<?php
use App\Http\Controllers\Admin\ClientController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/{year?}', [HomeController::class, 'home'])->where('year', '[0-9]+')->name('home');
Route::prefix('/admin')->group(function () {
Route::prefix('/clients')->group(function () {
Route::get('/add-client', [ClientController::class, 'addClient']);
Route::get('/edit/{id}', [ClientController::class, 'edit'])->name('admin.clients.edit');
Route::put('/add', [ClientController::class, 'add']);
Route::patch('/update/{id}', [ClientController::class, 'update']);
Route::delete('/delete/{id}', [ClientController::class, 'delete']);
Route::get('/paginated-json', [ClientController::class, 'paginatedJson']);
Route::get('/find-json/{id}', [ClientController::class, 'findJson']);
});
Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('admin.dashboard');
Route::get('/clients', [AdminController::class, 'clients'])->name('admin.clients');
Route::get('/bills', [AdminController::class, 'bills']);
Route::redirect('/', 'admin/dashboard');
});
Route::get('/welcome', function () {
return view('welcome');
});
I'm running everything from Windows Subsystem Linux, using Apache and MariaDB.
So far I tried multiple things:
php artisan serve (no clue why but it helped some people, not me though)
Different URIs
Making .env.testing file with APP_URL set to the same as .env file
Adding APP_URL to phpunit.xml file <server name="APP_URL" value="http://localhost/sunny-camping"/>
Pasting full URLs as the URI
Copying URIs from php artisan routes:list
Using `route('myroutename')' instead of URI
All of this to no avail. I keep getting 404 and I have no clue how to fix this. I went through multiple queries and over 2 pages of Google and found no solution...
Any ideas are appreciated.
Turns out, tests act in a (to me) very weird way. They use a different APP_URL than everything else.
So to fix this, you either have to set you APP_URL to just http://localhost in your .env.testing file, or add <server name="APP_URL" value="http://localhost"/> to your phpunit.xml file, given similar file structure. (Unfortunately I don't understand this enough to be able to tell how this will behave if your project is in deeper folders or non-local server)
Related
I have this error when a user returns from login to the admin page (i.e http://127.0.0.1:8000/admin), it should throw a 403 error if he/she doesn't sign in as the admin (i.e if he is not the admin)
Admin also experience this same error
Here's My Route
Laravel Version: 9.24.0
Please anyone should help
Here are my codes on web.php
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Route::middleware(['auth','admin'])->name('admin.')->prefix('admin')->group(function() {
Route::get('/', [AdminController::class, 'index'])->name('index');
});
require __DIR__.'/auth.php';
in app\Providers\RouteServiceProvider.php
uncomment this line
protected $namespace = 'App\\Http\\Controllers';
then command do
php artisan optimize
// or
php artisan optimize:clear
Thank you everyone for your help
I have identified the problem, I didn't add this on my kernel
'admin' => \App\Http\Middleware\Admin::class
i'm trying to make an example project to learn laravel. I set up the project on my computer and everything worked fine: I have my web.php that routes / to a view, but before that it collects devices so it can show you some data.
I decided to try and host it on a Debian AWS instance so I cloned my repo in /var/www/, migrated the database, wrote the .env, composer install, set folder ownership to admin user and permissions to storage and bootstrap.
Once i configured nginx i tried it by navigating to the url and the answer was Class "App\Models\Device" not found.
I checked the namespaces, file names, I even read that debian is a sucker for caps sensitivity so i double checked every capital letter in every name and since app folder is named app and not App i even tried to import it as app\Models\Device but to no avail.
I also tried with composer dump-autoload as many on SO suggested, but nothing changed at all.
Am i missing something?
Device.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Device extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'serial',
'livello_acqua',
'umidita',
'temperatura',
'livello_mangime',
'stato_rele_1',
'stato_rele_2',
'stato_rele_3',
'stato_rele_4',
'descrizione',
];
public static function findBySerial($serial){
return Device::where('serial', $serial)->get();
}
public static function findByUser($id){
return Device::where('user_id', $id)->get();
}
}
web.php
<?php
use app\Models\Device; //\app\Models\Device - App\Models\Device - \App\Model\Device
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
$devices = Device::all();
return view('index')->with(['devices' => $devices]);
});
Structure:
- app
- - Models
- - - Device
- - ...
- ...
- routes
- - web.php
- ...
I think i'm going nuts, i just tried again with App\Models\Device and got the error, re-changed it to app\Models\Device and got the error again and finally re-re-changed it to App\Models\Device and now it works...... have no idea why or how...
Try to import it like so use App\Models\Device; instead of use app\Models\Device;
See this link also
This question already has an answer here:
Updates to Laravel route file have no effect
(1 answer)
Closed 1 year ago.
While being on learning curve with laravel, I have created the new project and installed jetstream on it, have experimented with preprocessor's configurations, and some other basic stuff. Right now when I have added the simplest it does not work:
Route::get('foo', function () {
return 'Hello World';
});
And all the previously added routes work fine.
Here is the whole web.php file:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('/testcomp', function(){
return view('testcompmain');
});
Route::get('laravelProj3/login', function(){
return view('laravelProj3.auth.login');
});
Route::get('foo', function () {
return 'Hello World';
});
If any other files are helpful here, please let me know I will post them.
Is there any way to reset, or rebuild the project to force it to work again?
What if something like this happens while I am working on real project?
Can I somehow automatically copy all files that I added to newly build working application?
Is there any way except debugging to find where is the problem?
Update #1: Here is what I have found while debugging:
"Exception has occurred.
Symfony\Component\Routing\Exception\ResourceNotFoundException: No routes found for "/foo"."
Your route has been cached. It reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes. If you want to clear the cached file, then simply hit :
php artisan route:clear
You can cache your route again by :
php artisan route:cache
For more info see the official documentation of Route Caching, Optimizing Views, Environment
Am new to laravel firebase realtime database and am trying to connect to the firebase database but because of one reason or another am not able to. I have a database in firebase console and i have included a json private key in my FirebaseController. this is the error i get.
Kreait\Firebase\Exception\InvalidArgumentException
Invalid service account specification
FirebaseController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FirebaseController extends Controller
{
public function index(){
$database = app('firebase.database');
$reference = $database->getReference('subjects');
$value = $reference->getValue();
return $value;
}
}
Web.php file
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('/firebase','FirebaseController#index');
``
The problem for me was: I had set the FIREBASE_DATABASE_URL parameter without need.
So to anyone else seeing this, if your path is correct, check if you have this parameter set on your .env, if it is, remove it and run: php artisan config:cache and php artisan cache:clear.
Remember: on linux place firebase config files etc in a folder that user 'apache' can read!
So, for example, do not place such files in /home/myname/firebase.json. Even if you go chmod 777 firebase.json, this file may not be accessible by user 'apache'....
Then you do not need to use env variables.
$factory = (new Factory())->withServiceAccount(DIR.'/vendor/firebase-adminsdk.json');
I'm a bit new to laravel and have come across something I don't know how to fix, or even where to start looking. Can anyone explain this, please?
When I run php artisan route:list
I get:
[Symfony\Component\Debug\Exception\FatalErrorException]
syntax error, unexpected ','
I've only made a couple of changes to routes.php. Have since commented those out and cleared the cache, but this still shows, regardless.
Update - Contents of routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
/**
* Blade adjustments to make it work with Angular.js
*/
Blade::setContentTags('<%', '%>'); // for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>'); // for escaped data
/**
* Send requests to Angular.js (may need rethinking eventually because this is
* essentially a whitelist)
*/
Route::get('/{page?}', function($name = 'dash') {
return View::make('index');
})->where('page', '(dash|todo|help|settings)');
// Commented out to make Angular.js pages work
//Route::get('/', 'DashboardController#index');
//Route::get('home', 'HomeController#index');
/**
* Page View Routes
* Author: Anthony Sinclair
* Date: 31/03/2015
*/
/** User GET for new Users created via the UI */
Route::get('user/new', 'UserController#create');
/** User POST for catching Users created via the UI */
Route::post('user/new', 'UserController#store');
/**
* RESTful API routes
* Author: Anthony Sinclair
* Date: 30/03/2015
*/
Route::group(array('prefix' => 'api/v1', 'before'=>'auth'), function(){
/** User based API call routing */
Route::resource('user', 'UserController');
/** People based API call routing */
Route::resource('recipient', 'PeopleController');
/** Survey based API call routing */
Route::resource('survey', 'SurveyController');
/** Survey Response based API call routing */
Route::resource('response', 'SurveyResponseController');
Route::resource('response/token/{survey_token}', 'SurveyResponseController#getResponsesForSurvey');
/** Survey Instigator - The sending of Surveys */
Route::resource('send/{survey_id}', 'SurveyInstigatorController#sendSurvey');
});
/** Nps based API call routing */
Route::get('/api/v1/nps/{survey_id}', 'NpsController#getNpsScore');
Route::get('/api/v1/nps/{survey_id}/{filter}', 'NpsController#getNpsScoreFilteredByMonths');
Route::get('/api/v1/nps/{survey_id}/{filter}/{modifier}', 'NpsController#getNpsScoreFilteredByModifier');
Route::get('/api/v1/nps/response/{survey_id}/{recipient_id}/{nps_score}', 'SurveyResponseController#requestSurveyResponse');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController'
]);
Even checking my routes.php - shows no errors:
php -l app\http\routes.php
No syntax errors detected in app\http\routes.php
Try to go to storage/framework and delete routes.php. I suspect that the syntax error might have been cached.
I had this error, but only when ran on my local computer. If I ran route:list on server, it worked fine. The problem was my computer was using PHP v5.6 and the server was using PHP v7.0.
I was using the new ?? operator in a controller, so it was throwing a syntax error cause PHP v5.6 doesn't understand that operator.