I send some data by POST.
For example: http://.../?tag[]=1&tag[]=2
I cant receive tag varible in controller, I tried to do something like this:
$this->get('request')->get('tag');
But I receive null.
Whats wrong?
If you are sending data as you mentioned via URL, it is a GET request.
public function exampleAction(Request $request)
{
$tagPost=$request->request->get('tag'); //from $_POST[]
$tagGet=$request->query->get('tag'); //from $_GET[]
var_dump($tagPost,$tagGet);
}
try:
$this->get('request')->request->get('tag');
instead of:
$this->get('request')->get('tag');
EDIT: IF you http method is GET (instead of POST), you can try with:
$this->get('request')->query->get('tag');
Check here for further detail
hope this help
Related
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.
I don't really have an idea how to use PUT method of web api passing the parameter from angular.
I understand how GET method executed but the PUT, POST and DELETE are really hard for me.
I read many articles but it i still dont get an idea
I have a code like this in controller in my web api:
static readonly IProfile profileRepository = new ProfileRepository();
[Route("api/profile/")]
[HttpGet]
[System.Web.Http.AcceptVerbs("GET")]
public IEnumerable<Profile> getProfiles()
{
return profileRepository.getProfiles();
}
[Route("api/profile/")]
[HttpPut]
[System.Web.Http.AcceptVerbs("PUT")]
public IEnumerable<Profile> putProfile(Profile profile)
{
profileRepository.putProfile(profile);
return getProfiles();
}
I also have like this in service in my angularJS
var _putProfile = function (name,address,contacts) {
return $http.put(serviceURL + 'api/profile/Name=' + name + '&Address=' + address + '&Contact=' + contacts).then(function (results) {
return results;
});
};
When i use Postman application the web api execute well when i use x-www-form-urlencoded and it passes data from postman to web api but how to pass data from angularJS to web api.
Is there anyone can give me a best answer here.. Please give me an idea how to do it and please advice me what is the best practice..
Im only new in angularJS and Web Api please guide me.. Thanks you so much
AngularJS send json data and not x-www-form-urlencoded format data. Web API has capability of reading both.
When it comes to HTTP PUT verb, data should be passed in body not query string.
For your $http.put call you should do something like this.
$http.put(serviceURL + 'api/profile', { Name:name, Address:address, Contact:contacts});
Please read $http documentation.
I need to add a FlashBag code $session->getFlashBag()->add('foo', $bar); to every controller, along with the code required to get $bar. I am wondering if there is a better way then copying+pasting the code into every controller? Would there be some sort of master controller?
I'd recommend you to create a listener that will run before every controller that you indicate. Following this guide will show everything you need to set it up:
http://symfony.com/doc/2.0/cookbook/event_dispatcher/before_after_filters.html
http://symfony2.ylly.fr/symfony2-simulate-preexecute-postexecute-filters-actions-jordscream/
You should try implementing a service and registering it for onCoreController, then do $event->getController()->preAction() (or whatever function name you want...) , then you can implement those methods in the controllers that you need functionality in
something like
src/My/Bundle/RequestListener.php:
public function onCoreController(FilterControllerEvent $event) {
$evntController = $event->getController();
if (method_exists($evntController[0], 'beforeFilter')) {
$evntController[0]->beforeFilter();
}
}
Look here for more info
http://symfony.com/doc/2.0/book/internals.html#the-event-dispatcher
http://symfony.com/doc/2.0/book/internals.html
http://symfony.com/doc/current/cookbook/service_container/event_listener.html
I've been experiencing an issue with my SF2 application today.
I want the user to be automatically authenticated after submiting a valid subscription form.
So basically in my controller here's what I do:
if ($form->isValid()) {
$customer = $form->getData();
try {
$customer = $this->get('my.service.manager.customer')->customerSubscribe($customer);
} catch (APIClientException $e) {
$error = $e->getErrors();
...
}
if ($customer && !isset($error)) {
// connect customer
$token = new UsernamePasswordToken($customer, null, 'api_auth', array('ROLE_USER'));
$this->get('security.context')->setToken($token);
...
}
return new RedirectResponse($this->generateUrl('MyBundle_index'));
}
The two lines below the 'connect customer' comment actually seem to authenticate the user fine.
The problem being when I redirect to another page with RedirectResponse, then the authentication is lost.
I've tried a call to
$this->container->get('security.context')->isGranted('ROLE_USER')
which returns true just before the call to RedirectResponse, and false in my other controller where the response is being redirected.
At this point I'm a bit confused about what I'm doing wrong. Any ideas appreciated.
Btw, I'm using Symfony2.1
I've noticed this happens when you redirect more than once at a time. Does the controller for the MyBundle_index route return another redirect? If so, I think that's your answer.
Otherwise, maybe try using forwards? Instead of:
return new RedirectResponse($this->generateUrl('MyBundle_index'));
...just forward to whatever controller/action is defined for that route:
return $this->forward("SomeBundle:Default:index");
The URL that the user ends up with in their address bar might not be what you're expecting (it won't change from the one they requested originally), but you can probably fiddle with that to get it to your liking.
Ok I solved it like so:
$token = new UsernamePasswordToken($customer->getEmail(), null, 'api_auth', array('ROLE_USER'));
Apparently I needed to pass the customer id (in that case the email) as the first argument of UsernamePasswordToken, instead of the entire customer object. I'm not sure why since my entity Customer has a _toString method implemented, but at least it works fine like that.
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