Laravel Redirect to route with Parameters - laravel

This is my code:
return redirect()->route('edit.brand',$id)->with(array( 'brand' => $brand, 'errorName' => $errorName, 'errorCode' => $errorCode));
The result is that, in the FORM of route edit.brand.
It's filled by data with $id, (do the route first and ignore all parameters in 'with' )
How can I show $errorName if they exist

When You are redirecting to route, your parameters goes to flash session. So in edit.brand route You can access it with session helper like so:
session('errorName')

This is for flash data not request parameters That you are using .
Use this one
return Redirect::route('user', array('nick' => $username));

Related

How to use multiple method in single route in laravel

I want to use more than one method in a single route using laravel. I'm try this way but when i dd() it's show the plan string.
Route::get('/user',[
'uses' => 'AppController#user',
'as' => 'useraccess',
'roles'=> 'HomeController#useroles',
]);
When i dd() 'roles' option it's show the plan string like this.
"roles" => "HomeController#useroles"
my middleware check the role this way.
$actions=$request->route()->getAction();
$roles=isset($actions['roles'])? $actions['roles'] : null;
The simplest way to accept multiple HTTP methods in a single route is to use the match method, like so:
Route::match(['get', 'post'], '/user', [
'uses' => 'AppController#user',
'as' => 'useraccess',
'roles'=> 'HomeController#useroles',
]);
As for your middleware, to check the HTTP request type, a tidier way would be:
$method = request()->method();
And if you need to check for a specific method:
if (request()->isMethod('post')) {
// do stuff for post methods
}
Here's how you can do multiple methods on a single route:
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
/* Would be easier to use
* Route::put('/route/{route}', 'RouteController#update');
* Since Laravel gives you the Model of the primary key you've passed
* in to the route.
*/
Route::delete('/route', 'RouteController#destroy');
If you've written your own middleware, you can wrap the routes in a Route::group and apply your middleware to those routes, or individual routes respectively.
Route::middleware(['myMiddleware'])->group(function () {
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
});
Or
Route::group(['middleware' => 'myMiddleware'], function() {
Route::get('/route', 'RouteController#index');
Route::post('/route', 'RouteController#create');
Route::put('/route', 'RouteController#update');
});
Whichever is easier for you to read.
https://laravel.com/docs/5.6/routing#route-groups

Laravel reset password route not working

I am building custom views to reset passwords.
The routes looks like this:
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.reset');
Route::post('password/email', 'Auth\ForgotPasswordController#sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset.token');
Route::post('password/reset', 'Auth\ResetPasswordController#reset');
In ResetPasswordController.php I have added this:
//Show form to seller where they can reset password
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
The link sent to me looks like this:
https://myapp.dev/password/reset?451c70284a9d4b41123c4ec3efe83602b6cb955427ac48835200a45980bcf9f3
If I now enter that link I will go straight to the password/reset view and not the password/reset/{token}
However if I change the link in my broswer to
https://myapp.dev/password/reset/451c70284a9d4b41123c4ec3efe83602b6cb955427ac48835200a45980bcf9f3 (changing "?" to "/") I it works
So why doesnt the ? version of the URL work? I am using laravel 5.5
And since I dotn use the Auth:routes() is there any way to see what routes laravel generates when you use that?
There are two different things with parameters.
Route Parameters: These are included in the routes with '/' as in your example. You can get them by:
$request->parameter('parameter_name');
$request->parameters(); // for all parameters
Request Parameters: These are request parameters which attached in the URL after '?'. Parameters are sent this way in GET request. You can get them by:
$request->input('parameter_name');
$request->all(); // for all parameters
Laravel doc..
Probably you are confused with required parameters and optional parameters.
When you are defining the following route..
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset.token');
Laravel expects the token value as a required parameter in the third segment of the route.
But when you are accessing the route as
https://myapp.dev/password/reset?451c70284a9d4b41123c4ec3efe8360..
There is only two segment for the route. The token value is assigned as the get parameter or optional parameter.
As you already defined as follows..
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.reset');
your generated link points to the password/reset and ?451c70284a9d4b41123c4ec3efe83602b6cb955427ac48835200a45980bcf9f3 value is passed as the get parameter.
To trigger your reset the following route
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset.token');
you should use the following link format
https://myapp.dev/password/reset/451c70284a9d4b41123c4ec3efe83602b6cb955427ac48835200a45980bcf9f3
First of all, in your route
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.reset');
will take precedence over your url. since the route was declared on top and thus will goes into that showLinkRequestForm function first.
Meanwhile in your '/{token}' it will take slashes with the value that you sent thru the get route. Which currently you get.
Route::get('password/reset/{token}', 'Auth\ResetPasswordController#showResetForm')->name('password.reset.token');
Note that, position of route declaration is also affecting . Given example of 2 route with the same url but different name
//1st password/reset
Route::get('password/reset', 'Auth\ForgotPasswordController#showLinkRequestForm')->name('password.reset');
//2nd password/reset
Route::get('password/reset', 'Auth\ForgotPasswordController#showTokenForm')->name('password.reset.form');
In that case route naming will take the latest/last declaration which is 2nd password/reset and the first password/reset will be ignored or made into not available (tested).
So to answer your question which you asking Muhammad Nauman :
"How should I then change my code in order to get given route to work?"
Route::get('password/reset/{token}',
'Auth\ResetPasswordController#showResetForm')->name('password.reset.token');
In blade template you can adjust your routing value looks like this
Reset Form
Inside your new ResetPasswordController.php
public function showResetForm(Request $request)
{
$token = $request->route()->parameter('token');
return view('auth.passwords.reset')->with(
['token' => $token, 'email' => $request->email]
);
}
But if you are kinda like doing dirty way which pass the GET request token email
"?token="somevalue"&email="somevalue" you could do something like this
public function showResetForm()
{
return view('auth.passwords.reset')->with(
['token' => request('token'), 'email' => request('email')]
);
}
Then in the blade you add additional routing parameter of email too
Reset Form

Laravel sub-domain routing set global para for route() helper

I have setup sub-domain routing on my app (using Laravel 5.4) with the following web.php route:
Route::domain('{company}.myapp.localhost')->group(function () {
// Locations
Route::resource('/locations' , 'LocationController');
// Services
Route::resource('/services' , 'ServiceController');
});
However as my show and edit endpoints require an ID to be passed, using a normal route('services.show') helper results in an ErrorException stating Missing required parameters for [Route: services.create] [URI: services/create].
I appreciate this is necessary, but as the company is associated to the user on login (and is in the sub-domain) I don't want to be passing this for every view. I want to set this at a global level.
To avoid repeated queries, I thought about storing this in the session as so (in the :
protected function authenticated(Request $request, $user)
{
$current_company = $user->companies->first();
$company = [
'id' => $current_company->id,
'name' => $current_company->name,
'display_name' => $current_company->display_name
];
$request->session()->put('company', $company);
}
Which is fine, but I wonder if I can pass this to the route as a middleware or something. What's be best solution here?
Recommendation: remove the slash before the resource name.
The resource method will produce the following URIs:
/services/{service}
So, you should define your routes like this:
Route::domain('{company}.myapp.localhost')->group(function () {
// Locations
Route::resource('locations' , 'LocationController');
// Services
Route::resource('services' , 'ServiceController', ['only' => ['index', 'store']]);
Route::get('services');
});
I ran into this exact issue today, I poked around in the source and found a defaults method on the url generator that allows you to set global default route parameters like so:
app('url')->defaults(['yourGlobalRouteParameter' => $value]);
This will merge in whatever value(s) you specify into the global default parameters for the route url generator to use.

Redirect to current URL while changing a query parameter in Laravel

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');

Laravel, Routing Wildcards to filter and then controller

I am trying to capture a wildcard from URL and then first pass it to a filter then route to controller. I am not sure how to plot the question exactly but here is what I've tried so far.
Route::get('test/(:any?)', array('as' => 'testroute', 'uses' => 'test#result', 'before' => "test_filter:$1"));
Route::filter('test_filter', function($id = NULL)
{
if($id)
echo "This id is " . $id; // Prints "This id is $1"
});
and
Route::get('test/(:any?)', array('as' => 'testroute', function($id = NULL)
{
if($id)
echo "this id is " . $id; // Does not do anything
}, 'uses' => 'test#result'));
Basically, I want to check if there is an id appended to the URL and set a cookie if there is one. But regardless of the case, I want this route to be handled by a controller no matter if there is any id appended or not.
I have to do the same thing with so many routes so I'd prefer something like a filter rather than modifying the controller's codes.
I know that I can directly pass the wildcard element to a closure, or I can feed this as a parameter to any controller but in that case I'll have to modify the controller codes, which I can't at the moment.
Can I do it through filters ? or any other way in which i wont have to modify the controller codes ?
Try passing an anonymous right after the before
Route::get('test/(:any?)',
array(
'as' => 'testroute',
'uses' => 'test#result',
'before' => "test_filter",
function($my_cookie_value)
{
// Set cookie here
}
)
);
Taken from here
I'd use a middleware http://laravel.com/docs/5.1/middleware (or filter for older Laravel versions) and add the route/s into a group which has the middleware as you can see in here http://laravel.com/docs/5.1/routing#route-group-middleware.
The middleware will be executed before the route code, where you can add a logic to manage your cookie.

Resources