Laravel Redirect::route with an array parameter - php

Purpose: to redirect a specific route with an array value. I am not able to use View::make in my situation, which causes problem.
$value = 'Sarah';
$array_param = array(
'1' => 'a',
'2' => 'b'
);
return Redirect::route('myroute', array(
'name' => $value
));
Above is cool. But i cannot use $array_param with redirect route, which expects a string parameter, but i'm sending an array variable. Alternative way?
return Redirect::route('myroute', array(
'name' => $value,
'parameter' => $array_param
));
--update--
Route::post('myroute/{name}/{array_param}', array(
'as' => 'myroute',
'uses' => 'mycontroller#mymethod'
));

What the version of Laravel do you have?
The code below works for me correctly on laravel 5.1. Maybe it'll help you.
public function store(Request $request)
{
$item = Item::find(1); // an example
return redirect()->route('item.show', ['id' => $item->id]);
}
and yes, the redirect to the post route looks very incorrect. Please try to use the redirect only to the GET routes.

Related

There is nothing happening when store data for Laravel API

I making laravel API where i can store a new data where the value in body raw json. but when i try to send request using post, i got nothing but the status is 200 OK. when i chek my mysql there is no data inputed.
So, what should i do?
mysql data
Laravel Controller, and API,
// function in controller
use App\Models\ChartAge;
class ChartController extends Controller
{
public function saveChart(Request $request)
{
$data = $request->validate([
'entity' => 'required|string|max:10',
'code' => 'required|string|max:10',
'year' => 'required|int|max:10',
'under_age_15' => 'required|string|max:50',
'age_15_64' => 'required|string|max:50',
'age_65_over' => 'required|string|max:50',
]);
$values = ChartAge::create($request);
return response()->json(
[
'status' => true,
'message' => "the videos has been favorites",
'data' => $values,
],
201
);
}
}
//in api.php
Route::post("charts", [ChartController::class, 'saveChart']);
and here is when i tried to send request using postman.
because there is no error, i don't know what's wrong??
First double check your ChartAge model, does it have $fillable or not?
and Edit your code:
From
$values = ChartAge::create($request);
To:
$values = ChartAge::create($request->all());
Hope this will be useful.
With validation:
$data = \Validator::make($request->all(),[
'entity' => 'required|string|max:10',
'code' => 'required|string|max:10',
'year' => 'required|int|max:10',
'under_age_15' => 'required|string|max:50',
'age_15_64' => 'required|string|max:50',
'age_65_over' => 'required|string|max:50',
]);
if($data-> fails()){
return back()->withErrors($data)->withInput();
}
$values = ChartAge::create($request->all());
Do you set fillable fields in your 'ChartAge' model?
protected $fillable = ['entity','code','year'...];
Do you try to test code with disabling validation?
Please try to put dd($request) in the first row of the controller code.
Method create expects a plain PHP array, not a Request object.

CakePHP 3 Custom Route in Pagination

in my routes file i define a route for my controller method
$routes->connect('/category/:cat', ['controller' => 'Categories', 'action' => 'category']);
My controller method is this
public function category(){
$this->paginate = [
'limit' => 2
];
$this->viewBuilder()->layout('newLayout');
$cat = $this->request->params['cat'];
$id = $this->Categories->findBySlug($cat)->select(['id'])->hydrate(false)->toArray();
$cid = $id[0]['id'];
$category = $this->ProductCategories
->find("all")
->select(['id', 'category_id'])
->where(["category_id" => $cid])
->contain(['Products' => function($q){
return $q->select(['id', 'sku', 'product', 'description', 'slug', 'price', 'off', 'stock', 'product_category_id'])
->where(['status' => 1])
->contain(['ProductImages' => function($q){
return $q->select(['product_id','url']);
}]);
}])->hydrate(false);
$categories = $this->paginate($category);
$this->set(compact('categories'));
$this->set('_serialize', ['categories']);
}
And my url look like this:
http://localhost/mizzoli.com/category/Designer-Saree
Now when i click on cake pagination url change to this
http://localhost/mizzoli.com/categories/category?page=2
But actual url i want is like this
http://localhost/mizzoli.com/category/Designer-Saree?page=2
And also i need to pass some extra parameter with pagination url like color, occasion etc. Please help me to get this. I did not find any solution.
I had a similar issue and resolved it by passing the param I needed inside the third parameter of the route definition. Like this:
$routes->connect('/category/:cat', ['controller' => 'Categories', 'action' => 'category'], ['pass' => ['cat']]);
I have #littleylv from the #cakephp IRC channel on Freenode to thank for this solution.
You can read more about passing parameters to actions via routes here: https://book.cakephp.org/3.0/en/development/routing.html#passing-parameters-to-action

Phalcon PhP - how to use named routes inside a controller

I'm having trouble finding how to get the Urls from named routes inside a Phalcon PhP controller. This is my route:
$router->add(
'/admin/application/{formUrl:[A-Za-z0-9\-]+}/{id:[A-Za-z0-9\-]+}/detail',
[
'controller' => 'AdminApplication',
'action' => 'detail'
]
)->setName("application-details");
I want to get just the Url, example: domain.com/admin/application/form-test/10/detail . With the code below I can get the html to create a link, the same result of the link_to.
$url = $this->tag->linkTo(
array(
array(
'for' => 'application-details',
'formUrl' => $form->url,
'id' => $id
),
'Show'
)
);
The result I want is just the Url. I'm inside a controller action. I know it must be really simple, I just can't find an example. Can you help me?
Thanks for any help!
You should use the URL helper. Example:
$url = $this->url->get(
[
'for' => 'application-details',
'formUrl' => $form->url,
'id' => $id,
],
[
'q' => 'test1',
'qq' => 'test2',
]
);
You can pass second array for query string params if needed.
According to your route definition, the above should output something like:
/admin/application/form-url/25/detail?q=test1&qq=test2
More info of Generating URIs in the docs.

CakePHP: "GET" form does not auto-populate form fields after submission

I'm using Cake 2.3.0. If I submit my form using POST, the selected form fields carry over however if I submit my form using GET, all of the form fields return to their default values.
Is there a way to make the GET submission to work like that of the POST?
Here's my contorller:
class ListingsController extends AppController {
public function results() {
$conditions = array(
'Listing.Beds >=' => $this->request->query['beds'],
'Listing.ListingStatus >=' => $this->request->query['status'],
);
$this->paginate = array(
'conditions' => $conditions,
);
$this->set('listings', $this->paginate());
}
}
Here's what my view looks like.
echo $this->Form->create(null, array(
'controller' => 'listings',
'action' => 'results',
'type' => 'get'
));
echo $this->Form->input('name');
$beds = array('1' => '1+', '2' => '2+', '3' => '3+', '4' => '4+', '5' => '5+');
echo $this->Form->input('beds', array('options' => $beds));
$status = array('Active' => 'Active', 'Pending' => 'Pending', 'ActivePending' => 'Active and Pending');
echo $this->Form->input('status', array('options' => $status));
echo $this->Form->end('Update');
So basically if I change 'type' => 'get' to 'type' => 'post' it works just fine. But I need to be able to do this via GET.
Thanks
I agree that this is annoying (IMO CakePHP should be smart enough to automatically determin 'where' to get its data from, based on the 'type').
You'll have to copy the 'query' of the request to the 'data' of the request;
$this->request->data = $this->request->query;
Not behind my computer to test it (as usual, lol), but should probably work.
Try adding this to your controller:
$this->request->data = $this->params['url'];
My solution:
$this->params->data = array('Tablefilter' => $this->params->query);
where "Tablefilter" depends on form definition (usually the model name)
$this->Form->create('Tablefilter', array('type' => 'get'))
Use PRG. Checkout this plugin.
What I ended up doing was looping through the $this->request->query array and pass those values to the matching $this->request->data.
So I added this:
foreach($this->request->query as $k => $v){
$this->request->data['Listing'][$k] = $this->request->query[$k];
}
Which ultimately gave me this:
class ListingsController extends AppController {
public function results() {
foreach($this->request->query as $k => $v){
$this->request->data['Listing'][$k] = $this->request->query[$k];
}
$conditions = array(
'Listing.Beds >=' => $this->request->query['beds'],
'Listing.ListingStatus >=' => $this->request->query['status'],
);
$this->paginate = array(
'conditions' => $conditions,
);
$this->set('listings', $this->paginate());
}
}
I'm not going to accept this as the answer though as I don't know if this is the optimal or suggested way to do it. But it works for me for now.
This works for me :
$this->request->data['Cluster'] = $this->params->query ; //controller side
Form definition:
$this->Form->create('Cluster',array('type'=>'get'));

ZF2: How to pass parameters to forward plugin which I can then get in the method I forward them to?

I have an Action method in Foo Controller which requires parameters:
public function fooAction($one, $two) {
$a = one;
$b = $two;
}
And I need to forward to that method from the other method of some Boo Controller. And one of those parameters has to be by reference parameter. The only example that the manual has is this:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array('action' => 'boo'));
No any additional parameters. But they write:
$params is an optional array of parameters with which to see a
RouteMatch object for purposes of this specific request.
So, I tried:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'one' => &$one,
'two' => $two,
));
But it doesn't work.
Is there any way to pass additional parameters to forward controller?
UPD:
These do not work too:
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'params' => array(
'one' => &$one,
'two' => $two,
)));
$result = $this->forward()->dispatch('Boo\Controller\Boo', array(
'action' => 'boo',
'options' => array(
'one' => &$one,
'two' => $two,
)));
UPD 2:
I still can't get the functionality I want (to pass parameters with the forward plugin) but I found other solutions. Before calling the forward plugin I set the variables to the Request object and after the forward I get them from the Request in my boo Action of my Boo\Controller\BooController:
// in Foo::fooAction
$this->getRequest()->one = &$one;
$this->getRequest()->two = $two;
$result = $this->forward()->dispatch('Boo\Controller\Boo', array('action' => 'boo'));
// in Boo::booAction
$a = $this->getRequest()->one;
$b = $this->getRequest()->two;
Stupid solution, it will not work with Ajax requests. Still interested how to pass parameters with the forward plugin. OR MAYBE how to get them in the booAction. Because there in no anything in the Request if I pass them with the forward.
UPD 3 and Final:
I finally found where they've decided to hide parameters I pass with the forward plugin. They put them in the RouteMatch object.
- Tryyyy to guess where we've hidden your params... Oh yeeah, they are in the RouteMatch, of course they are there, didn't you think smth else?
And NO ANY info in the forward plugin section of the manual!
To get params, I have to do this in my BooController::booAction:
$param = $this->getEvent()->getRouteMatch()->getParam('nameOfParam');
Why not to use the params plugin?
This works for me:
public function indexAction() {
$object = new SomeObject();
return $this->forward()->dispatch('Application\Controller\Index', [
'action' => 'show',
'myObject' => $object,
]);
}
public function showAction() {
$object = $this->params('myObject');
var_dump($object);
return [];
}
You can create a container class and use it in both controllers
in module.conf
public function getServiceConfig()
{
return array(
'invokables' => array(
'my_handy_container' => 'path\container_class_name',
)
);
}
Create a getter in both controllers:
public function getMyHandyContainer()
{
if (!$this->myHandyContainer) {
$this->myHandyContainer = $this->getServiceLocator()->get('my_handy_container');
}
return $this->myHandyContainer;
}
And call it using:
$myContainer = $this->getMyHandyContainer()->myHandyContainer;
$myContainer->foo = 5; // set something
ZF2 way to pass vars using forward
In the passing method do:
return $this->forward()->dispatch('controller_name', [
'action' => 'whatever',
'varname' => $value,
'varname2' => $value2
]);
In the invoked controller method, do:
$param2 = $this->params()->fromRoute('varname2',false);
Thought I would add another option that works for me.
You can simply pass the params straight through the forward function and use the routeMatch function to access them at the other end.
return $this->forward()
->dispatch('Module\Controller\Foo', array(
'action' => 'bas',
'id' => 6)
);
Passes to Foo Controller, basAction in this method you can then use the following code to access the id param
$myParam = (int) $this->getEvent()->getRouteMatch()->getParam('id');
Not sure if this meets your requirements - but works for me.
Thanks for the question, helped me a lot. Found an easy way for getting all params passed to forward()->dispatch(...). In the controller's action method:
$params = $this->params()->fromRoute();
returns array $data as passed as $data into forward()->dispatch($controllerName, $data).
Here in the official ZF2 documentation is written exactly how it works:
$params is an optional array of parameters with which to seed a RouteMatch object for purposes of this specific request. Meaning the parameters will be matched by their key to the routing identifiers in the config (otherwise non-matching keys are ignored).
So pass like this:
$params = array(
'foo' => 'foo',
'bar' => 'bar'
);
$this->forward()->dispatch('My\Controller', $params)
And then you can get your route match params in your My\Controller like normally:
$foo = $this->params()->fromRoute('foo');
$bar = $this->params()->fromRoute('bar');
For people struggling with accessing parameters within their controller here a nice overview from this CheatSheet.
$this->params()->fromPost('foo'); //POST
$this->params()->fromQuery('foo'); //GET
$this->params()->fromRoute('foo'); //RouteMatch
$this->params()->fromHeader('foo');//Header
$this->params()->fromFiles('foo'); //Uploaded file

Categories