Laravel "\Request::route()->getName()" give null results - laravel

I'm using Laravel with Spatie Permissions package, and it's working fine!
I'm trying also to use the Authorizable trait for managing the Roles and Permissions.
The problem seems to be $routeName = explode('.', \Request::route()->getName());.
I expect to have from \Request::route()->getName() the result posts.index but I have null.
\Request::route()->getName() works only if I defined the property "name" into the route by using ->name('posts/index') (and the result is posts/index )
why \Request::route()->getName() is null in my app ? What I'm doing wrong ?

To get route name ,you need to use
$name = Route::currentRouteName();
and use Illuminate\Support\Facades\Route;
Request::route()->getName() works only for laravel < 5.*

you can use
Route::currentRouteName(); //use Illuminate\Support\Facades\Route;
but also you can get action of route by
Route::getCurrentRoute()->getActionName();

I'm not sure why are you getting this but the route must have ->name() (if you want to use route names) if it was not a resource route.

Related

Laravel Route Controller issue

I am trying to add a new route to my application and can't seem to get it to work. I keep getting a 404 error. It looks like the physical path is looking at the wrong directory. Currently looking at D:\Web\FormMapper\blog\public\forms but should be looking at D:\Web\FormMapper\blog\resources\view\layout\pages\forms.blade.php
My request URL:
http://localhost/FormMapper/ /works fine
http://localhost/FormMapper/forms /doesn't work
http://localhost/FormMapper/forms.php /No input file specified.
my FormsController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormsController extends Controller
{
public function index()
{
return view('layouts.pages.forms');
}
}
My web.php:
Route::get('/', function () {
return view('layouts/pages/login');
});
Route::get('/forms', 'FormsController#index');
My folder structure looks like this:
My config/view.php
return [
'paths' => [
resource_path('views'),
],
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];
you must use dot for this. In your controller change to this:
return view('layouts.pages.forms');
If your route only needs to return a view, you may use the Route::view method. Like the redirect method, this method provides a simple shortcut so that you do not have to define a full route or controller. The view method accepts a URI as its first argument and a view name as its second argument. In addition, you may provide an array of data to pass to the view as an optional third argument:
Route::view('/', 'layouts.pages.login');
Route::view('/forms', 'layouts.pages.forms', ['foo' => 'bar']);
Check docs
After tracking digging deeper I determined that the issue was that IIS requires URL rewrite rules in place for Laravel to work properly. The index.php and '/' route would work b/c it was the default page but any other pages wouldn't. To test this I used the
php artisan serve
approach to it. and everything worked properly. Unfortunately I am unable to do this in production so I needed to get it to work with IIS.

In RouteAction.php line 84: Invalid route action

When I create a controller in laravel 5.4 I get this error
In RouteAction.php line 84:
Invalid route action:
[App\Http\Controllers\Admin\DashboardController].
I do not create Admin/DashboardController. Still makes a errors
web.php
Route::group(['namespace' => 'Admin', 'middleware' => ['auth:web', 'CheckAdmin'], 'prefix' => 'admin'],function (){
$this->resource('authorities', 'AuthoritiesController');
$this->resource('complaints', 'ComplaintsController');
$this->resource('schools-list', 'SchoolsListController');
$this->resource('inspection-failed', 'InspectionFailedController');
$this->resource('inspection-register', 'InspectionRegisterController');
$this->resource('inspection-results', 'InspectionResultsController');
$this->resource('inspectors-list', 'InspectionListController');
$this->resource('investigators', 'InvestigatorsController');
$this->resource('notification-infringement', 'NotificationInfringementController');
$this->resource('system-experts', 'SystemExpertsController');
$this->resource('submit-information', 'SubmitInformationController');
$this->resource('primary-committee-meeting', 'PrimaryCommitteeMeetingController');
$this->resource('list-violations-school', 'ListViolationsSchoolController');
$this->resource('announcing', 'AnnouncingController');
$this->resource('display-vote', 'DisplayVoteController');
$this->resource('announcing-supervisory-vote', 'AnnouncingSupervisoryVoteController');
$this->resource('supervisory-board-vote', 'SupervisoryBoardVoteController');
$this->resource('defense', 'DefenseController');
$this->resource('votiing-supervisory-board', 'VotiingSupervisoryBoardController');
$this->get('dashboard', 'DashboardController');
});
Because it is invalid. As you're using GET route, you must specify method name(unless you used ::resource):
$this->get('dashboard', 'DashboardController#methodName');
If you are using laravel 8 you need to add your controller and method name inside the array, otherwise, it will throw an error.
Route::get('/projects', User\ProjectController::class, 'index')->name('user.projects');
TO
Route::get('/projects', [User\ProjectController::class, 'index'])->name('user.projects');
I also face a similar problem:
<?php
/*
|--------------------------------------------------------------------------
| 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('/', 'Frontend\FrontendController#index')->name('home');
Route::get('/post', 'Frontend\FrontendController#post')->name('post');
Route::get('/contact', 'Frontend\FrontendController#contact')->name('contact_us');
Route::group(['prefix' => 'admin'], function () {
Route::get('/create', 'Backend\BackendController#index');
//User Route
Route::get('/registration', '');
});
And I just remove the Route::get('/registration', ''); and it's work for me :)
try removes route cache file by
php artisan route:clear
Those who are new to Laravel or learning use
Route::resource('resource_name','controller_name')
to avoid this kind of error when you type:
php artisan route:list
In cmd or any other command line.
i think its because of :: before the class name instead use #
Route::get('/about','App\Http\Controllers\DemoController::about'); (Not working gives an error)
Route::get('/about','App\Http\Controllers\DemoController#about'); (But this statement works)
I hit the same issue but with a different cause. So I'm documenting here just in case someone else hits the same cause.
Specifically if you are using a Single Action Controller (ie: with __invoke), if you haven't added or omitted the correct use Laravel will hide the missing controller with "Invalid route action: [XController]."
This will fail
<?php
use Illuminate\Support\Facades\Route;
Route::post('/order', XController::class);
This will pass
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\XController;
Route::post('/order', XController::class);
I think its a bit unfortunate that Laravel masks the underlying issue, but I think it only applies to invokable controllers, even though its a silly mistake on my behalf.
Lastly if you set the route like below:
Route::post('example', PostController::class);
You should have an __invoke method in your controller.
For recent versions of laravel, try adding square brackets like
Route::post('login',[AuthController::class,'login'])
instead of
Route::post('login', AuthController::class,'login']).
The second route will throw the error Invalid route action: since you are not invoking the route. Another alternative you can add an __invoke function on your controller if you are using the second route as mentioned above.

Current route showing null Laravel

I am new to Laravel. I am using Laravel 5.4. For some purpose, I need the current route. For this, I am using the following code in my controller.
$name = Route::currentRouteName();
dd($name);
But, its always showing null. Any help will be appreciated.
I don't know what's problem with your code but you can get URL of current route with following way as well,
$name = URL::current();
To view value you can dump $name,
dd($name);
You can try with following:
$name = Route::current()->getName();
dd($name)

Sharing across view in Laravel 5.4

I have a project where users are assgned to a client and I wannt to share that info across views.
In AppServiceProvider I added
use View;
use Auth;
and then amended boot to
if ( Auth::check() )
{
$cid = Auth::user()->client_id;
$company = \App\Clients::first($cid);
view::share('company',$company);
}
but if I dd($company) I get
Undefined variable: company
This is because of the Auth is not working in AppServiceProvider
So your If condition return false
if you share data with all the views then your code like this without check Auth. then It will work.
$company = 'Some value';
view::share('company',$company);
dd($company); // for print output.
Solution - For Alternate option you have to make Helper class.
At the time the providers boot is run, the Auth guard has not been booted, so Auth::check() returns false, and Auth::user() returns null.
You could do the View::share in a middleware, or perhaps in the constructor of a controller (the base controller to share it across the whole application, or some particular controller if you need it in some subset of routes).

Laravel how to route old urls

I am using Laravel 4.
I have an old url that needs to be routable. It doesn't really matter what it's purpose is but it exists within the paypal systems and will be called regularly but cannot be changed (which is ridiculous I know).
I realise that this isn't the format url's are supposed to take in Laravel, but this is the url that will be called and I need to find a way to route it:
http://domain.com/forum/index.php?app=subscriptions&r_f_g=xxx-paypal
(xxx will be different on every request)
I can't figure out how to route this with laravel, i'd like to route it to the method PaypalController#ipbIpn so i've tried something like this:
Route::post('forum/index.php?app=subscriptions&r_f_g={id}-paypal', 'PaypalController#ipbIpn');
But this doesn't work, infact I can't even get this to work:
Route::post('forum/index.php', 'PaypalController#ipbIpn');
But this will:
Route::post('forum/index', 'PaypalController#ipbIpn');
So the question is how can I route the url, as it is at the top of this question, using Laravel?
For completeness I should say that this will always be a post not a get, but that shouldn't really make any difference to the solution.
Use this:
Route::post('forum/{file}', 'PaypalController#ipbIpn');
And then in the controller, use
public function forum($file) {
$request = Route::getRequest();
$q = (array) $request->query; // GET
$parameters = array();
foreach($q as $key => $pararr) {
$parameters = array_merge($parameters, $pararr);
}
}
You can then access the get parameters via e.g.
echo $parameters['app'];
you can use route redirection to mask and ending .php route ex:
Route::get('forum/index', ['uses'=> 'PaypalController#ipbIpn']);
Route::redirect('forum/index.php', 'forum/index');

Resources