Is there any way I could pass an object through Redirect action method ?
For eg. return Redirect()->action('projectController#create_project',$project);
How to pass $project ?
Yes, you can. The second parameter of the action method will accept an array of parameters:
return redirect()->action('ProjectController#create_project', ['project' => $project]);
If you want to have this parameter only when redirecting, you can create the rote with an optional parameter:
Route::get('admin/{project?}', ['uses' => 'ProjectController#create_project']);
Then your method will look like this:
public function create_project( $project = null ) { }
When you don't have it in the route or if it's not passed from a redirect it'll be null otherwise you'll have your data in the variable.
Related
I have a route for example -
Route::get('/api/{user}/companies/{company}', [CompanyController::class, 'getCompanies'])
and a function in this controller
public function getCompanies(User $user, Company $company) {
$companies = $company->all();
return response()->json(['companies' => $companies]);
}
I am not using the $user instance in the function and I would like to not pass a User $user param in it, but I want that the route has user id as a param for clarity on the frontend.
I found a solution of using middleware with the forgetParameter() method but I don't want to add new middleware or declare it only for this route.
I can just leave that unused param in my function and everything will work just fine, but I am curious is there some elegant solution for this case.
public function getCompanies(Company $company, ?User $user = null)
{
return response()->json(['companies' => $company->all()]);
}
Pass $user to the last position and give it a default value
I think you can put a _ instead of passing a parameter, but I could be wrong.
I have RESTful API built on Laravel.
Now I'm passing parameter like
http://www.compute.com/api/GetAPI/1/1
but I want to pass parameter like
http://www.compute.com/api/GetAPI?id=1&page_no=1
Is there a way to change Laravel routes/functions to support this?
you can use link_to_route() and link_to_action() methods too.
(source)
link_to_route take three parameters (name, title and parameters). you can use it like following:
link_to_route('api.GetAPI', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
If you want to use an action, link_to_action() is very similar but it uses action name instead of route.
link_to_action('ApiController#getApi', 'get api', [
'page_no' => $page_no,
'id' => $id
]);
href text
with these methods anything after the expected number of parameters is exceeded, the remaining arguments will be added as a query string.
Or you can use traditional concatination like following:
create a route in routes.php
Route::get('api/GetAPI', [
'as' => 'get_api', 'uses' => 'ApiController#getApi'
]);
while using it append query string like this. you can use route method to get url for required method in controller. I prefer action method.
$url = action('ApiController#getApi'). '?id=1&page_no=1';
and in your controller access these variables by following methods.
public function getApi(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...your stuff
}
Or by Input Class
public function getApi() {
if(Input::get('page_no')){
$page = Input::get('page_no');
}
// ...your stuff
}
Yes you can use those parameters, then in your controllers you can get their values using the Request object.
public function index(Request $request) {
if($request->has('page_no')){
$page = $request->input('page_no');
}
// ...
}
I want user to get calculated result. I had to redirect localhost:8000/question/33 to localhost:8000/caclulate/some_payload
I have no idea how to do this.
class QuestionController extends Controller
public function index($id)
if(question->id == 33)
#Here I want to invoke calculate($payload)
return view('quiz.index', [
'payload' => $payload,
'question' => $question,
]);
}
public function calculate($payload)
{
return view('quiz.result', [
...
]);
}
I've tried $this->calculate($payload) and calculate().
If I understand right, you want call controller method from another controller method.
You could try it this way:
$request = Request::create('calculate/some_payload', 'GET', $params);
return Route::dispatch($request)->getContent();
For more info see Jason Lewis answer here: Consuming my own Laravel API
Are you expecting Request::json () to provide form input? Or, are you looking for Input::all() form input?
I've solved, my problem with:
return Redirect::action('QuestionController#calculate',
array('payload' => $payload));
But it generates address with parameter
http://localhost:8000/calculate?payload=%242y%2410%24V1OqC7rwp1w1rPXYQ42lRO9lJYQvmXB3nScw6D0EVeFR7VUz0QyCS
And I want to use$_POST instead of $_GET, so I need to invoke method with $_POST and catch $payload in method calculate. How can I do this?
I am sending an array from method 'filterResults' to method 'home' via redirect. The array does go through because the URI changes to www.site.com/country/area/city/category.
But when I print the array inside method 'home' it is not an array anymore but instead it is a string with only the first value (country) of the original array. Why is this the case? Where are the other values? and why is it now a string instead of an array?
Thanks for your help!
Route:
Route::any('home/{s1?}/{s2?}/{s3?}/{s4?}', array(
'as' => 'home',
'uses' => 'HomeController#home'
));
Controller Method 'filterResults':
public function filterResults() {
$filter = array('country' => $country, 'area' => $area, 'city' => $city, 'category' => $category);
return Redirect::route('home', $filter);
}
Controller Method 'Home':
public function home($filter = array()) {
print_r($filter); //result is a string with the value for country
}
That's not really how Laravel routing works. When you pass it an array, it is expecting an array of arguments.
So your home method will actually receive 4 arguments (the elements of the array).
It makes more sense to make the method something like:
public function home($country = null, $area = null, $city = null, $category = null) {
print_r($country);
print_r($area);
print_r($city);
print_r($category);
}
Keep in mind that when you're at /country/area/city/category, Laravel has absolutely no idea that you want those in an array. An alternative if you really have to have it in an array would be to remove the arguments from the home method altogether and use PHPs func_get_args which would give you the arguments in array form. They'd be 0-based indexed though. You could even then pass that through array_map to map 0 to country, 1 to area, 2 to city, and 3 to category, but that is probably a lot of excess work when you can just get at everything via parameters.
You need to define them to get the parameters for example
public function home($param1 = null, $param2 = null, $param3 = null, $param4 = null) {
}
It creates a url because Laravel is smart enough to do that according to the documentation. See array section in route parameters.
Is there a built-in way to do something like this?
Let's say I have a search-page that has a few parameters in the URL:
example.com/search?term=foo&type=user
A link on that page would redirect to an URL where type is link. I'm looking for a method to do this without manually constructing the URL.
Edit:
I could build the URL manually like so:
$qs = http_build_query(array(
'term' => Input::get('term'),
'type' => Input::get('type')
));
$url = URL::to('search?'.$qs);
However, what I wanted to know is if there is a nicer, built-in way of doing this in Laravel, because the code gets messier when I want to change one of those values.
Giving the URL generator a second argument ($parameters) adds them to the URL as segments, not in the query string.
You can use the URL Generator to accomplish this. Assuming that search is a named route:
$queryToAdd = array('type' => 'user');
$currentQuery = Input::query();
// Merge our new query parameters into the current query string
$query = array_merge($queryToAdd, $currentQuery);
// Redirect to our route with the new query string
return Redirect::route('search', $query);
Laravel will take the positional parameters out of the passed array (which doesn't seem to apply to this scenario), and append the rest as a query string to the generated URL.
See: URLGenerator::route(),
URLGenerator::replaceRouteParameters()
URLGenerator::getRouteQueryString()
I prefer native PHP array merging to override some parameters:
['type' => 'link'] + \Request::all()
To add or override the type parameter and remove another the term:
['type' => 'link'] + \Request::except('term')
Usage when generating routes:
route('movie::category.show', ['type' => 'link'] + \Request::all())
You can do it with Laravel's URLGenerator
URL::route('search', array(
'term' => Input::get('term'),
'link' => Input::get('type')
));
Edit: be sure to name the route in your routes.php file:
Route::get('search', array('as' => 'search'));
That will work even if you're using a Route::controller()
From Laravel documentation:
if your route has parameters, you may pass them as the second argument
to the route method.
In this case, for return an URI like example.com/search?term=foo&type=user, you can use redirect function like this:
return redirect()->route('search', ['term' => 'foo', 'type' => 'user']);
Yes, there is a built in way. You can do your manipulation in Middleware.
The $request passed to the handle method of all middleware has a query property. As an InputBag, it comes with a few methods; Namely, for your intentions: ->set().
Pretty self explanatory, but here's an example:
public function handle(Request $request, Closure $next)
{
$request->query->set('term','new-value');
// now you pass the request (with the manipulated query) down the pipeline.
return $next($request);
}
The Input component should also contain query parameters.
i.e Input::get('foo');