Laravel 5: route optional parameter issue - laravel-routing

I want to have second param as optional one.
Routes:
Route::get('/offers/preview/{id}/{string?}', 'OfferController#preview');
Controller:
public function preview($id, $string)
{
// some code
}
Calling "offers/preview/101/test" looks ok.
Error by calling "offers/preview/101"
ErrorException in OfferController.php line 53:
Missing argument 2 for App\Http\Controllers\OfferController::preview()
Thank you in advance.

You need to add default value for the optional paramaters
public function preview($id, $string = '')
{
// some code
}
see Laravel Routing

Related

Lumen 8 - Using Faker in tests makes InvalidArgumentException: Unknown format "name"

I'm using Lumen default Tests only added this line to the test :
$users = \App\Models\User::factory()->count(5)->create();
But i get this error when running the test :
InvalidArgumentException: Unknown format "name"
I did't touch the UserFactory Class i include it below , whats wrong with my code?
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
];
}
Should anybody else end up here looking for a similar issue in Laravel, make sure you include
parent::setUp();
in your setup method (if you have one). For example,
class ManageDocumentTest extends TestCase
{
public $user;
public function setUp():void
{
parent::setUp();
$this->user = User::factory()->create();
...
Uncommented these lines in app.php and its working now :
$app->withFacades();
$app->withEloquent();
You have to extend use Tests\TestCase instead of PHPUnit\Framework\TestCase.
At least, it helped me.
If you are using Tests\TestCase, calling parent::setUp(); and it still doesn't work, make sure not to call $faker before the actual test - ie. in a #dataProvider it won't work

Laravel middleware with parameter

I write middleare to decide permission. But giving error.
Route page
Route::middleware([Permission::class])->group(function($id){
});
middleware
public function handle(Request $request, Closure $next,$id)
{
$id = $request->id; //$id is returning null
}
Giving this eror
Too few arguments to function App\Http\Middleware\Permission::handle(), 2 passed in /home/saide/Desktop/saide-backoffice/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 167 and exactly 3 expected
I think when you called Middleware you used a square bracket, you have used an array for submitting the parameter to the middleware, use the below code
Route::middleware([Permission::class])->group(function($id){
});
For submitting multiple parameters through middleware use this code:
Route::get('/', function () {
//
})->middleware(['first', 'second']);
For passing single middleware use this:
Route::get('/profile', function () {
//
})->middleware('auth');
Information Source: https://laravel.com/docs/8.x/middleware
The issue is that the middleware is expecting a parameter and you aren't supplying it.
If you want your middleware to have an additional parameter $id, then route should be like this:
Route::middleware([Permission::class.':id_value_goes_here'])->group(function () {
});
If you need the ID to be a dynamic parameter based on a route parameter (e.g. Route::get('/posts/$id', ...)) or something passed to the request, then you should omit the extra parameter from the middleware handle()'s method signature:
public function handle(Request $request, Closure $next)
{
$id = $request->id; // $id will now get correctly set
}

Too few arguments to function Livewire\LivewireManager::mount(), 0 passed in

Thanks in advance for helpful advice. I am using Laravel Livewire for creating components and Jetstrap for authentication for those routes that require it.
At the moment I only have one route set up for testing authentication, yet after I have logged in to view that route, I get the following error:
Too few arguments to function Livewire\LivewireManager::mount(), 0 passed in /var/www/mvp/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 261 and at least 1 expected
This seems to be originating from the LivewireManager class, inside the getInstance() function:
public function getInstance($component, $id)
{
$componentClass = $this->getClass($component);
throw_unless(class_exists($componentClass), new ComponentNotFoundException(
"Component [{$component}] class not found: [{$componentClass}]"
));
return new $componentClass($id);
}
It seems to be expecting a component argument from the Facade class in /vendor/laravel/framework/src/Illuminate/Support/Facades/, but isn't getting the component it needs. I checked the page code, and there is definitely a component there.
The Facade function creating the error:
/**
* Handle dynamic, static calls to the object.
*
* #param string $method
* #param array $args
* #return mixed
*
* #throws \RuntimeException
*/
public static function __callStatic($method, $args)
{
$instance = static::getFacadeRoot();
if (! $instance) {
throw new RuntimeException('A facade root has not been set.');
}
return $instance->$method(...$args);
}
And the page that's supposed to be loading its component:
#extends('layouts.app')
#section('content')
#livewire('component')
#stop
Is there a simple way to fix the problem? Or am I missing something?
I got same error like what you get when i try to passing parameter and then i'm solving the problem by following the documentation with changing the way to render livewire component from using blade directive #livewire() into <livewire: >

Phalcon router sends the wrong parameters

I have a problem with my router in Phalcon.
I have an action in my controller which ether takes a date parameter or not.
So when I access an URL: http://example.com/sl/slots/index/2017-06-27
everything works ok.
But when I go to: http://example.com/sl/slots/index
I get the following error:
DateTime::__construct(): Failed to parse time string (sl) at position
0 (s): The timezone could not be found in the database.
So the router actually takes the "sl" in the beginning as a parameter.
My router for this kind of url is set like this:
$router->add(
"/{language:[a-z]{2}}/:controller/:action",
array(
"controller" => 2,
"action" => 3
)
);
Btw it does the same withut the index: http://example.com/sl/slots
Oh and my slots index action looks like this:
public function indexAction($currentDate = false){ //code }
So the $currentDate is set to "sl" when I call the action without a parameter
Thank you for the help
Well you need to add language in first argument of action too. Then it should work.
In addition to #Juri's answer.. I prefer to keep my Actions empty or as slim as possible. Imagine if you have 3-4 parameters in the Route, you will end up with something like:
public function indexAction($param1 = false, $param2 = false, $param3 = false....)
Here is how I prefer to handle Route parameters:
public function indexAction()
{
// All parameters
print_r($this->dispatcher->getParams());
// Accessing specific Named parameters
$this->dispatcher->getParam('id');
$this->dispatcher->getParam('language');
// Accessing specific Non-named parameters
$this->dispatcher->getParam(0);
$this->dispatcher->getParam(1);
...
}

Defaults in Symfony2 routing not being passed properly

I am currently trying to configure a routing option in Symfony2 so /cms will route to /cms/role/view. However, the passing of defaults doesn't seem to work properly.
/src/MyProject/CMSBundle/Resources/config/routing.yml
MyProjectCMS_specific:
pattern: /cms/{page}/{option}
defaults: { _controller: MyProjectCMSBundle:Main:index, page: role, option: view }
requirements:
_method: GET
/src/MyProject/CMSBundle/Controller/MainController.php
<?php
namespace MyProject\CMSBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class MainController extends Controller
{
public function indexAction($page, $option)
{
$response = null;
/* Switch statement that determines the page to be loaded. */
return $response;
}
}
?>
The problem is that when I try to go to `localhost/app_dev.php/cms', it gives me the following error:
Controller "MyProject\CMSBundle\Controller\MainController::indexAction()" requires that you provide a value for the "$page" argument (because there is no default value or because there is a non optional argument after this one).
500 Internal Server Error - RuntimeException
However, if I try to visit localhost/app_dev.php/cms/role or localhost/app_dev.php/cms/role/view, it gives me the correct page. I've tried adding a default route to /cms, but it still gives me the same error. How is this possible and how can I fix this?
Thanks in advance.
I don't know what is the difference between what you wrote and
public function indexAction($page = "role", $option = "view")
but maybe you could try it and tell us.