laravel artisan error when listing routes - php

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.

Related

Laravel Feature Tests always return 404

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)

Laravel Auth Login Page Just Refreshes

I am using Laravel 5.4. I ran the make:auth command to scaffold out my auth controllers and views. I can register a new account without issue as it is showing up in my database. However when I try to login, the login page simply refreshes without any errors being thrown. In the login controller I have the redirect set to '/home' but this isn't happening. Any idea what could be causing this? I have a feeling this is because I made the required tweaks to allow users to login with a username rather than email. But I'm not sure what is causing my login not to work when everything else works fine.
Below is my login controller.
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
public function username()
{
return 'username';
}
}
Do a quick check to see if the route is being handled.
You might have to add Auth::routes(); in your web.php
Resource:
laravel 5.3 new Auth::routes()
Once you've run php artisan make:auth you need to also run the migrations with php artisan migrate have you done this?
I had this problem using Laravel 8.0 and found no helpful response over the internet... until I taught of checking the APP_URL set in my env...
Because I have other apps set up on other ports on the same localhost, I simply changed APP_URL from http://localhost to http://localhost:8003/, i.e, specifying the port this App is on.
Other steps I took that may contributes include generating new APP_KEY and refreshing my migration.
It's been many years, but, this took my 3 days to figure... I hope it helps someone.

Laravel Routes on Resource Controller. Using Show method with id = create instead of the create method

Below is my routes.php file in Laravel 5.1
When I access the /question/create url, the show method (meant for /question/{id} url) is called instead of the create method in the QuestionController.
I probably don't fully understand how the routes file interprets what I have below. Can someone help me understand how my file is being interpreted and why the show method is being called instead of the create method?
Note: This was working just fine when I did not have any route groups and middleware. Before I broke it, the routes file just had the resource controllers listed plain and simple (e.g. Route::resource('question','QuestionController'); )
<?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.
|
*/
//Home Route
Route::get('/','HomeController#getHome');
// Simple Static Routes (FAQ, PRIVACY POLICY, HONOR CODE, TERMS AND CONDITIONS ETC.). No Controller Required.
Route::get('faq',function(){
return view('legal/faq');
});
Route::get('privacypolicy',function(){
return view('legal/privacypolicy');
});
Route::get('honorcode',function(){
return view('legal/honorcode');
});
Route::get('termsandconditions',function(){
return view('legal/termsandconditions');
});
// Authentication routes (Middleware called by Controller)
Route::get('auth/login', 'Auth\AuthController#getLogin');
Route::post('auth/login', 'Auth\AuthController#postLogin');
Route::get('auth/logout', 'Auth\AuthController#getLogout');
// Registration routes (Middleware called by Controller)
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
// Anyone can see the Home Page and Browse Questions, Courses and Universities
$routes = ['only' => ['index','show']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
// Routes Protected by Auth Middleware
Route::group(['middleware' => 'auth'],function(){
/*
* Students can view Solutions and Their Profiles
*/
Route::get('solution/{id}','QuestionController#postSolution');
Route::resource('user','UserController',['only' => ['show']]);
/*
* Only Editors have the ability to view the Create Questions Page,
* Store, Edit and Delete Questions that they created, that have not been solved yet
* Create, Edit and Delete Courses and Universities
*/
Route::group(['middleware' => 'editor'],function(){
$routes = ['only' => ['create','store','edit','update','destroy']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
/*
* Only Admins have the ability to delete resources
*/
Route::group(['middleware' => 'admin'],function(){
Route::get('admin/execute','AdminController#getExecute');
});
});
});
I see you have
$routes = ['only' => ['index','show']];
Route::resource('question','QuestionController',$routes);
Route::resource('course','CourseController',$routes);
Route::resource('university','UniversityController',$routes);
Before the group.
Right now because your route show is before the others like create It thinks create is a wildcard of show. So you should put the lines above at the bottom of the file.
Extra
I notice you have this in your group route
$routes = ['only' => ['create','store','edit','update','destroy']];
Its faster to write it as
$routes = ['except' => ['index','show']];
Except makes sure all routes are available except for the given routes.
And to see which routes are used you can enter the following in your terminal.
Php artisan route:list
Your resource controller has only 2 routes allowed based on your routes file : index and show.
$routes = ['only' => ['index','show']]; //
For example if this url home/create is server by a resource controller where you applied the above filter, the method show will be fired automatically. If you want the create method, just add it to your filter and run composer dump-autoload.

Laravel's route doesn't see controller's action

I'm trying to learn Laravel, and I created controller (using artisan's php artisan controller:make AlbumController). Then, I added some functions there, mainly function parse:
/**
* Parse the album.
*
* #param int $id
* #return Response
*/
public function parse($id)
{
return 'http://api.deezer.com/'.$id;
}
In routes.php I added
Route::resource('album', 'AlbumController');
But when I try to access the parse page (http://localhost/album/parse/123) Laravel returns throw new NotFoundHttpException();.
What did I do wrong?
parse is not an included route in Laravel's resourse controller. Run php artisan routes to see your current route structure.
If you want to use the parse method in your controller you should define the route manually. Add something like
Route::get('album/parse/{id}', ['uses' => 'AlbumController#parse']);
to your routes file.
As an aside, the resource controller can be a handy way to get your CRUD routes up and running but it is good practice to define most of your routes explicitly as your routes.php file is useful documentation for your application and it makes the workings of it much easier to follow.
You need to change the route to
Route::get('album/parse/{id}', 'AlbumController#parse');
More of routing with parameters can you find HERE inside the Laravel Docs
And the docs with some information about Routing with Controllers
An little part of my route to give you an idea of how it could look:
Route::get('/partijen/nieuw', 'PartijenController#nieuw');
Route::post('/partijen/nieuw', 'PartijenController#save_new');
Route::get('/partijen/edit/{id}', 'PartijenController#edit');
Route::post('/partijen/edit/{id}', 'PartijenController#save_edit');

FOSRestBundle: How to Avoid Automatic Pluralization of POST /login Route?

I have this Action to handle the user login also via REST api call:
/**
* Login Action
*
* #param Request $request
*/
public function postLoginAction(Request $request)
{
This is what php app/console router:debug shows me:
en__RG__post_login POST ANY ANY /api/1/logins.{_format}
In this case the automatic pluralization to "logins" is not so nice... any ideas how to get only "login"?
You can manage default route pluralization by overriding fos_rest.inflector.doctrine service. refer this issue and followed pull request.
or
for change pluralization of single route it can be done by using Manual definition of routes please refer this documentation from FOSRESTBUNDLE repository

Categories