How to pass query string with routes in laravel 5.4 - query-string

I am using Laravel 5.4. I want to use query string like below:
tempsite.com/lessons?id=23
For getting this how routes are to be modified. It is possible to give route in the following way.
Route::get('lessons/id={id}', ['as' => 'lessons.index', 'uses' => 'Lessons\LessonController#index']);
But adding '?' is not getting for me. Please help us to provide a solution as early as possible.

If you are using resourceful controllers, your routes are all handled for you so you would simply put
Route::resource('lessons', 'Lessons\LessonController');
You can then use route model binding to bind the model instance which matches that particular ID.
Route::model('lesson', Lesson::class);
This would be done in your RouteServiceProvider.
I would also suggest having a good read of the following documentation on the laravel website https://laravel.com/docs/5.4/routing. It provides really good insight in to how routes work and how they should be structured.

Instead of tempsite.com/lessons?id=23
Pass it like this tempsite.com/lessons/23
and in the route
Route::get('lessons/{id}', ['as' => 'lessons.index', 'uses' => 'Lessons\LessonController#index']);
to get the id in your controller, write your function like this
public function index($id)
{
//do anything with $id from here
}

There is no need to define query string parameters in your routes. You can return query string parameters in your controller like so:
URL example: tempsite.com/lessons?id=23
public function lessons(Request $request)
{
$request->get('id'); // Using injection
Request::get('id'); // Using the request facade
request()->get('id'); // Using the helper function
}
You could even validate the parameter:
public function lessons(Request $request)
{
$this->validate($request, ['id' => 'required|integer']);
}
Note: If you want to make the URL not accessible if the ID is omitted, see #DarkseidNG answer.

I was able to inform laravel to accept query stringed requests on my route by affixing the url with a forward slash, like so
// web.php
Route::get('/path/', "Controller#action");
With the above, mysite/path?foo=bar&name=john does not throw 404 errors.

Related

Get request not sending parameter via url to the api controller

I have this simple API controller in a NetCore 2.2 web game that is supposed to return a list of monsters based on the dungeonID(Guid).
So I use the URL, passing in the guid of the dungeonID, to that controller like this:
https://localhost:44361/MonsterList/GetMonsters/2f14c8gf-2e7e-466a-bcbg-f4440e92b3dg
But when I step through the code, I just see all zeroes for the dungeonID:
public async Task<JsonResult> GetMonsters(Guid dungeonID)
{
var monsters = await _context.MonsterList.Where(c => c.DungeonID == (dungeonID)).ToListAsync();
return Json(monsters);
}
This returns nothing because, for reasons I don't know, dungeonID is always all zeroes.
But this does work if I hard-code in the dungeonID:
https://localhost:44361/MonsterList/GetMonsters
public async Task<JsonResult> GetMonsters()
{
var monsters = await _context.MonsterList.Where(c => c.DungeonID == Guid.Parse("2f14c8gf-2e7e-466a-bcbg-f4440e92b3dg")).ToListAsync();
return Json(monsters);
}
I've seen lots of posts similiar to mine, like these:
asp.net webapi 2 post parameter is always null
Post parameter is always null
But nothing seems to work.
How do I add the ability to pass in a Guid parameter?
Thanks!
One point is 2f14c8gf-2e7e-466a-bcbg-f4440e92b3dg is not a GUID/UUID . Just try with a correct GUID :
https://localhost:44384/api/values/GetMonsters/2e6ae748-10c2-4e23-84c3-9d3db7c09631

ZendFramework 3 PUT method parameters access

I make REST API service based on Zend Framework 3. I stuck on a moment where I should process PUT request. Let it be like this:
PUT /document/14
Request parameters are: {
token: '.. some string here ..',
name: '....',
}
The thing is, that I can't even get "token", because neither $this->getRequest()->getQuery() nor $this->getPost() don't contain any parameters at all.
I've seen few recommendations like registering Zend_Controller_Plugin_PutHandler, but I didn't find such class in Zend Framework 3.
You need to get JSON data, and there is no params helper for that, so fast hack would be:
// In your Controller action
$content = $this->getRequest()->getContent();
$data = json_decode($content, true);
var_dump($data); // here you will have your json as array
This works but a better way is to use AbstractRestfulController.
Extend it and you will have automatically $id and $data injected in the method update($id, $data). Also you will have all other methods for RESTful API.
You should check implementation of that class for more info, especially method jsonDecode

How do you retrieve a route pattern from the route name in Silex?

Suppose I defined a route and named it new as shown below. How can I use the name to retrieve the route's pattern path /new?
class AppControllerProvider implements ControllerProviderInterface {
public function connect(Application $app) {
$controllers = $app['controllers_factory'];
//some code here...
$controllers->get('/new', function (Request $req) use ($app) {
return $app['twig']->render('content/new.twig', ['params' => $params, 'errors' => []]);
})->bind('new');
//some code here...
$app['url_generator']->generate('new') can be used to return the path for the route. Is there an analogous sort of method? I inquire because I'd like to be able to conveniently access the pattern in case it's modified, and keep the route names the same.
The following seems to work, as it finds the controller matching the route name, then finds the route, and finally outputs the corresponding pattern:
$app['controllers_factory']->get('new')->getRoute()->getPattern()
Unsure whether or not there's a simpler way.

How to get previous page route in Symfony?

I am looking for way to do this in 'right' symfony way.
There's a way to get the referer page from the $request variable. For example, if I was in myaction/mypage and click to myaction2/mypage2 by this getReferer() method I get 'http://myweb/myaction/mypage'.
If you are in an action method this can be done by
public function executeMyaction(sfWebRequest $request)
{
$previousUrl = $request->getReferer();
...
}
if you are somewhere else you can get the request by getting the conext
$previousUrl = $this->getContext()->getRequest()->getReferer();
For for sfWebRequest methods check the sfWebRequest API.
Note: this value could be inaccesible using proxy's

mvccontrib test helper and verifying http post routes and parameters

In my Asp.net MVC app, I have two methods on a controller, one for when the user first arrives on the view and then one when they submit the form on said view.
public ActionResult Foo() {}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Foo(string id, Account accountToFoo) {}
In the second action, there's a custom model binder that's assembling the account object that I'm acting on, though that's really not important. This all works fine in testing locally on a server.
We try to be pretty good about writing unit tests to test all our different views are properly getting routed to, including those that are HTTP POST. To do so, we've been using mvccontrib's test helper.
Testing gets have been super simple
"~/account/foo/myusername".
Route().
ShouldMapTo<AccountController>(c => c.Foo("myusername"));
My question is in testing POST routes, how do I write the lambda that I would use to verify the post is receiving accurate values, similar to the GET test above?
For a POST, it looks something like:
"~/account/foo".
WithMethod(HttpVerbs.Post).
ShouldMapTo<AccountController>(a => something_something);
It's the something_something portion of my lambda that I'm having trouble with. Using arbitrary values doesn't work ("a => a.Foo(0, new Account()"). How would I specify the expected values as part of the test?
EDIT I was hoping there was something akin to the way Moq has lambdas for statements such as foo.Setup(s => s.Foo(It.IsAny(), It.Is(i => i > 32)) and so on. Even I have to explicitly supply the values, that's workable--I just can't seem to grok the desired structure to pass those explicit values.
Here's an example. Assuming you have the following action:
public AccountController : Controller
{
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Foo(string id)
{
return View();
}
}
And the following route registered:
RouteTable.Routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "home", action = "index", id = "" }
);
You could test it like this:
var routeData = "~/account/foo".WithMethod(HttpVerbs.Post);
routeData.Values["id"] = "123";
routeData.ShouldMapTo<AccountController>(c => c.Foo("123"));
Some tweaking might be necessary to include the second Account argument you have.
Using the mvccontrib helper syntax:
"~/account/foo".WithMethod(HttpVerbs.Post).ShouldMapTo<AccountController>(a => a.foo(null));
You pass null as the Foo(string id, Account accountToFoo) method is never executed as part of the routing test.

Resources