Route Error: Symfony 4 No route found for "GET /blog" - php

I am having this error:
Symfony\Component\HttpKernel\Exception\NotFoundHttpException: No route
found for "GET /blog" (from "http://localhost:8000/produits")
I added the annotation #Route in the method in my controller (like I saw in other website):
/**
* #Route("/blog", name="article.index")
* #return Response
* */
public function index():Response
{
return $this->render("blog/article.html.twig", [
"current_menu" => 'articles'
]);
}
I tried to add methods={"GET","HEAD"} in #Route but I have the same error
How do I solve this problem?

This one worked for me (adding / to the end of route path):
/**
* #Route("/blog/", name="article.index")
* #return Response
* */
public function index():Response
{
return $this->render("blog/article.html.twig", [
"current_menu" => 'articles'
]);
}

You will also at least need use Symfony\Component\Routing\Annotation\Route; at the start of the file (among the other 'use' lines), Some framework setup for Route annotations could also need to be enabled. Also, how does blog/article.html.twig refer to the route or path?
A freshly installed Symfony 4 instance will need composer require doctrine/annotations package, unless its already been installed by some other package.
https://symfony.com/doc/current/routing.html#creating-routes has more details.

Related

Laravel two 404 styles

I have a main site and an admin control panel.
I want to have different 404 pages for each version.
How should I do this? I currently have the following code in my app/Exceptions/Handles.php file:
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
if($exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException)
{
$view = $request->is('admin/*') ? 'acp.errors.404' : 'errors.404' ;
return response()->view($view, [], 404);
}
return parent::render($request, $exception);
}
But I use the package spatie/laravel-permission and get the following error;
Trying to get property 'role' of non-object (View: F:\Development\RPR\site\resources\views\layouts\acp.blade.php) (View: F:\Development\RPR\site\resources\views\layouts\acp.blade.php)
I use in acp.blade.php auth()->user()->role, to get the user role, which just works fine without any exception. How should I fix this?
Here are two ways to accomplish different 404 views depending on the route. Both will allow you to have these error pages:
/resources/views/acp/errors/404.blade.php
/resources/views/errors/404.blade.php
The directories will be checked in order until a view is found, which means you can selectively add custom error views and fall through to the default when none exist. If the route did not match, then it will not look for a custom error page.
Option 1
Override registerErrorViewPaths() inside app/Exceptions/Handler.php:
/**
* Register the error template hint paths.
*
* #return void
*/
protected function registerErrorViewPaths()
{
parent::registerErrorViewPaths();
if (request()->is('admin/*')) {
View::prependNamespace(
'errors',
realpath(base_path('resources/views/acp/errors'))
);
}
}
Option 2
Create a ViewServiceProvider:
php artisan make:provider ViewServiceProvider
Register your provider in config/app.php:
'providers' => [
// ...
App\Providers\ViewServiceProvider::class,
],
Edit the boot method of your provider:
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
if (request()->is('admin/*')) {
View::prependNamespace(
'errors',
realpath(base_path('resources/views/acp/errors'))
);
}
}
For the second part of the question, auth()->user() is only available when the session middleware has run. If the 404 was caused by the route not existing, then the request does not go through the web middleware and unfortunately sessions and auth information will not be available. However, if the 404 was caused by a ModelNotFoundException triggered inside a controller, then the web middleware probably did run and you can access the user.
Inside your error view you have to check if the user is signed in:
#guest
<p>Hello, guest</p>
#else
<p>Hello, {{ auth()->user()->name }}</p>
#endguest
If this is not good enough for your use case, then you might want to try Route::fallback(), which allows you to define a controller for serving 404 pages and does run web middleware.

Laravel 5.7.6 resource route with auth

I'm starting my first Laravel project (first MVC / OOPHP project infact) and could use some help with routes.
I followed the guide at https://medium.com/employbl/easily-build-administrator-login-into-a-laravel-5-app-8a942e4fef37 to add a check if user is admin when loading a page. It works for normal view routes, e.g.
Route::get('/admin/something', 'AdminController#admin_something')
->middleware('is_admin')
->name('admin');
But I now have a resource route and get an error when I add the two -> lines to the route. So this works with no auth:
Route::resource('thingies', 'ThingyController');
But with this:
Route::resource('thingies', 'ThingyController')
->middleware('is_admin')
->name('admin');
I get the error Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR)
Too few arguments to function Illuminate\Routing\PendingResourceRegistration::name(), 1 passed in /var/www/routes/web.php on line 24 and exactly 2 expected
What do I need to do differently to add this auth to a resource route?
The is_admin() function from the tutorial:
const ADMIN_TYPE = 'admin';
const DEFAULT_TYPE = 'default';
public function isAdmin() {
return $this->type === self::ADMIN_TYPE;
}
And the middleware:
namespace App\Http\Middleware;
use Closure;
class IsAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(auth()->user()->isAdmin()) {
return $next($request);
}
return redirect('home');
}
}
You can't name your route "admin" with ->name('admin'); at the end of your resource route because it concerns all CRUD routes in one statement and Laravel build-in system has already named them.
You're on the good way, just delete the last line like so, it should works :
Route::resource('thingies', 'ThingyController')
->middleware('is_admin');
You cannot give a 'name' to a resource route. but you can give names to each method in the resource controller separately.
to do so name() function required 2 parameters.
method name
name for that method route.
,
Route::resource('thingies', 'ThingyController')
->middleware('is_admin')
->name('create', 'admin.create');

Laravel Storage::extend not working

I can't figure out where I'm going wrong, with this. I've followed the Laravel docs by installing spatie/flysystem-dropbox via composer copied the DropboxServiceProvider from the Laravel Docs, added the service provided to the config\app.php, ran composer dump autoload but yet I am still getting the following error message:
PHP error: Undefined index: driver in /***/vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemManager.php on line 112
Here is the service provider:
<?php
namespace App\Providers;
use Storage;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Illuminate\Support\ServiceProvider;
use Spatie\FlysystemDropbox\DropboxAdapter;
class DropboxServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*
* #return void
*/
public function boot()
{
Storage::extend('dropbox', function ($app, $config) {
$client = new DropboxClient(
$config['authorizationToken']
);
return new Filesystem(new DropboxAdapter($client));
});
}
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
//
}
}
And here's my config/app/php:
...
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
App\Providers\DropboxServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
...
Finally, here's my config/filesystems.php:
'dropbox'=>[
'authorizationToken'=>env('DROPBOX_ACCESS_TOKEN')
],
Turns out that I was missing the driver value in the config/filesystems/php so it should have been this:
'dropbox'=>[
'driver' => 'dropbox', <=== THIS WAS MISSING
'authorizationToken'=>env('DROPBOX_TOKEN')
],
One good Pacakge avilable for extend storage using dropbox:
detail documentation : https://github.com/GrahamCampbell/Laravel-Dropbox
steps for use this package :
1 : composer require graham-campbell/dropbox in your cmd window
2 : after this you have to register service provider for laravel dropbox,
go to config/app.php
and add 'GrahamCampbell\Dropbox\DropboxServiceProvider' this in provider array
and 'Dropbox' => 'GrahamCampbell\Dropbox\Facades\Dropbox' this to aliases array
3: now you have to publish pacakge so 'php artisan vendor:publish' run this in your cmd
- this will create dropbox.php file in your config in this file you have to add your credentials
4: here you have two option for connection you can use it according to your choice.
usage :
simple example :
use GrahamCampbell\Dropbox\Facades\Dropbox;
// you can alias this in config/app.php if you like
Dropbox::createFolder('Folder_Name');
// we're done here - how easy was that, it just works!
Dropbox::delete('Folder_Name');
// this example is simple, and there are far more methods available

Symfony route to file misunderstanding

I had an intention to dynamically generate a robots.txt file for different domain names.
I removed the file from /web/ directory.
I added
bits_cb.common:
resource: "#BitsClientoboxBundle/Controller/CommonController.php"
type: annotation
to routing.yml.
I added
/**
* #Route("/robots.txt", name="robots")
* #param Request $request
*/
public function indexAction(Request $request)
{
//
}
to CommonController.php.
The debug:router console command there is route:
robots ANY ANY ANY /robots.txt
But if I try to get from http://{{sitename}}/robots.txt it returns 404.
To be sure, if I change
* #Route("/robots.txt", name="robots")
to
* #Route("/robots", name="robots")
and get from http://{{sitename}}/robots it works okay.

Generate well formed routes from MenuBuilder class in Symfony2

I've this route defined in a controller:
/**
* #Secure(roles="IS_AUTHENTICATED_FULLY")
* #Route(
* "/proccess/{slug}",
* requirements={"slug": "^([a-zA-Z0-9]*-[a-zA-Z0-9]*)+$"},
* name="registerRPNI"
* )
*/
public function indexAction(Request $request)
{
......
}
And I need to set the right route in KNPMenuBundle MenuBuilder class. I'm doing as follow:
->addChild('Process RPNI', array(
'uri' => '/process/national-and-imported-products-registration',
))
And it works for dev environment since route shows the right page and execute the right code but if I move away from dev and goes live to prod then I got a 404 Not found, what I'm doing wrong in this case? What should be the right way to generate the routes inside the MenuBuilder class? Any advice around this?

Categories