Serialization of 'Closure' is not allowed Laravel routing? - laravel

When I launch command: php artisan route:cache I get message:
Serialization of 'Closure' is not allowed
There is only one closure in routes:
Route::group(['middleware' => ['auth']], function () {
})
I use php 7.1

Move the closure in routes/api.php to controller or comment it
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
Then run
php artisan route:clear
php artisan route:cache
Laravel will try to cache routes by serializing to base64 encoded text in bootstrap/cache/routes.php, and closures can't be serialized

Related

Illegal string offset 'name' error calling component from blade

In my Laravel 8 app I created new component with command
php artisan make:component Admin/Auth/loggedUserHasPermissions
and I have error with sending parameter to it from blade file :
Illegal string offset 'name' (View: /mnt/_work_sdb8/wwwroot/lar/AdsBackend8/resources/views/test.blade.php)
On row in resources/views/test.blade.php :
<x-logged-user-has-permissions :logged-user="getLoggedUser()" />
getLoggedUser is funnction in helper file.
and in app/View/Components/Admin/Auth/loggedUserHasPermissions.php
<?php
namespace App\View\Components\Admin\Auth;
use Illuminate\View\Component;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class loggedUserHasPermissions extends Component
{
private $loggedUser;
private $hasAdminRole;
public function __construct($loggedUser)
{
$this->loggedUser = $loggedUser;
$this->hasAdminRole = false;
}
public function render()
{
I follow camelCase / kebab-case rules written here https://laravel.com/docs/8.x/blade#passing-data-to-components
running commands
php artisan config:cache
php artisan route:cache
php artisan cache:clear
php artisan view:clear
php artisan clear-compiled
composer dump-autoload
did not help
How it can be fixed?
Thanks!

Laravel Policy not working on route middleware

I have a NotificationPolicy with the following code:
<?php
namespace App\Policies;
use App\Notification;
use App\User;
use Illuminate\Auth\Access\HandlesAuthorization;
class NotificationPolicy
{
use HandlesAuthorization;
public function update(User $user, Notification $notification)
{
return $user->id === $notification->user_id;
}
}
I have registered this properly by adding this to the AuthServiceProvider:
protected $policies = [
Notification::class => NotificationPolicy::class,
];
I have this so that only the logged in user can update their notification by doing things such as setting the archived_at value or read_at value to the current timestamp. The policy does work if I use it in the controller, i.e.;
class ArchiveItemController extends Controller
{
public function __invoke(Notification $notification)
{
$this->authorize('update', $notification);
$notification->markAsArchived();
return redirect()->route('inbox.index')->with('success', 'Item has been archived');
}
}
However I don't want to use them in the controllers and would prefer to use them in my routes file. So I have removed this line $this->authorize('update', $notification); from the controller and I have tried the following but it doesn't work:
Route::prefix('inbox')->middleware(['auth', 'can:employee'])->group(function () {
Route::get('/notification/{notification}/archive', 'User\Account\Inbox\ArchiveItemController')
->name('inbox.item.archive')
->middleware('can:update', 'notification');
});
I've even ran the following but they don't make a difference:
php artisan optimize
php artisan cache:clear
php artisan route:cache
php artisan view:clear
php artisan config:cache
Your middleware declaration is not correct.
You will have to change 'can:update', 'notification' to 'can:update,notification' for it to work:
So in the end you would have the following:
Route::prefix('inbox')->middleware(['auth', 'can:employee'])->group(function () {
Route::get('/notification/{notification}/archive', 'User\Account\Inbox\ArchiveItemController')
->name('inbox.item.archive')
->middleware('can:update,notification');
});
If you have cached the routes, you will have to run php artisan route:clear for the changes to take effect.
From the docs:
Laravel includes a middleware that can authorize actions before the
incoming request even reaches your routes or controllers. By default,
the Illuminate\Auth\Middleware\Authorize middleware is assigned the
can key in your App\Http\Kernel class. Let's explore an example of
using the can middleware to authorize that a user can update a blog
post:
use App\Post;
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->middleware('can:update,post');
In this example, we're passing the can middleware two arguments. The
first is the name of the action we wish to authorize and the second is
the route parameter we wish to pass to the policy method. In this
case, since we are using implicit model binding, a Post model will be
passed to the policy method. If the user is not authorized to perform
the given action, a HTTP response with a 403 status code will be
generated by the middleware.

In Route.php line 817:Unable to prepare route [api/user] for serialization. Uses Closure

I cleared every instance of a closure from my web.php file but i'm still getting this error when I run php artisan route:cache.How do I fix this.
The format of the routes that I used are:
Route::get('/home',[
'uses'=>'HomeController#index',
])->name('home');
and the other format is
Route::get('/profile',[
'uses'=>'profileController#index',
]);
Edit: Formatted code
I figured a way around this error its due to Route present in the routes > api.php , just comment it out and files will be cached successfully.
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });

laravel Unable to prepare route ... for serialization. Uses Closure

When I clear caches in my Laravel 5.2 project, I see this error message:
[LogicException]
Unable to prepare route [panel] for serialization. Uses Closure.
I think that it's related with a route
Route::get('/article/{slug}', 'Front#slug');
associated with a particular method in my controller:
public function slug($slug) {
$article = Article::where('slug',$slug)->first();
$id = $article ->id_article ;
if ( ($article=== null) || (is_null($id)) ) return view('errors/Db');
else return view('detail')->with(array('article'=> $article, 'title'=>'My title - '.$article->title));
}`
In short, from a master view I pass $slug, that is a shortlink to the article, with $slug , which is unique in the database, I identify the record and then I pass it's contents to the detail view.
I didn't have any problem when I wrote the method, infact it worked like a charm, but after I cleaned caches, I get that error and the links in the master view don't show any shortcode.
Where am I doing wrong?
I think that it's related with a route
Route::get('/article/{slug}', 'Front#slug');
associated with a particular method in my controller:
No, thats not it. The error message is coming from the route:cache command, not sure why clearing the cache calls this automatically.
The problem is a route which uses a Closure instead of a controller, which looks something like this:
// Thats the Closure
// v
Route::get('/some/route', function() {
return 'Hello World';
});
Since Closures can not be serialized, you can not cache your routes when you have routes which use closures.
If none of your routes contain closures, but you are still getting this error, please check
routes/api.php
Laravel has a default auth api route in the above file.
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which can be commented or replaced with a call to controller method if required.
This is definitely a bug.Laravel offers predefined code in routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
which is unabled to be processed by:
php artisan route:cache
This definitely should be fixed by Laravel team.(check the link),
simply if you want to fix it you should replace routes\api.php code with some thing like :
Route::middleware('auth:api')->get('/user', 'UserController#AuthRouteAPI');
and in UserController put this method:
public function AuthRouteAPI(Request $request){
return $request->user();
}
The Actual solution of this problem is changing first line in web.php
Just replace Welcome route with following route
Route::view('/', 'welcome');
If still getting same error than you probab
the solustion when we use routes like this:
Route::get('/', function () {
return view('welcome');
});
laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize
Check your routes/web.php and routes/api.php
Laravel comes with default route closure in routes/web.php:
Route::get('/', function () {
return view('welcome');
});
and routes/api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
if you remove that then try again to clear route cache.
If you're coming to this problem because you've upgraded Laravel <5.8 project up to >=5.8, you've likely used the ./vendor/bin/carbon-upgrade method to upgrade the project as suggested by your terminal. In this case, you simply need to remove the following two blocks from the bottom of your composer.json file and composer install again:
"post-install-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postInstall",
"php artisan optimize"
],
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan optimize"
],
If someone is still looking for an answer, for me the problem was in routes/web.php file. Example:
Route::get('/', function () {
return view('welcome');
});
It is also Route, so yeah...Just remove it if not needed and you are good to go!
You should also follow answers provided from above.
In order to troubleshoot this (at least in laravel 6):
The action property inside Route.php has all the info needed. A better error message should be possible to provide by laravel.
What I did was to add a dd($this->action) just before the exception is thrown here:
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Routing/Route.php#L917
With that in place I could easily pinpoint the location, in my case api.php and lines 22-24:
array:6 [
"middleware" => "api"
"domain" => "local-api.mydomain.com"
"uses" => Closure()^ {#6497
class: "App\Providers\RouteServiceProvider"
this: App\Providers\RouteServiceProvider {#5743 …}
file: "./routes/api.php"
line: "22 to 24"
}
"namespace" => "App\Http\Controllers"
"prefix" => null
"where" => []
]
This is how I solved mine.
Navigate to routes directory
Then open api.php
comment code that looks like this:
Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); });
Then run
php artisan optimize
check that your web.php file has this extension
use Illuminate\Support\Facades\Route;
my problem gone fixed by this way.

Route:list laravel 5 not changed

It's my first time deploying laravel on shared host.
I have a problem when adding some function on controller that already listed on routes.php.
Everything is ok when I run it on local, but when it's on shared host, and I run php artisan route:list the list doesn't updated
Here's my controller :
public function getIndex(){
return view('content.login');
}
public function postIsLogin(Request $data){
...
}
public function getLogout(){
...
}
And this is my routes.php
Route::controller('/login','LoginController');
Route::controller('/driver','DriverController');
Route::controller('/pushnotif','PushNotificationController');
Route::controller('/','DashboardController');
I add getLogout() function, but when I run php artisan route:list there's no route for getLogout() function.
I appreciate any help. Thank you.
This usually caused by route cache, try to run php artisan route:clear

Resources