Hi all, I was wondering how I would have a named route that I can put in a view file that would automatically set the "account_id" in the route. Example:Each url for a logged in user looks like (account_id = 234567);
domain.com/234567/user/edit/1 (named route 'user.edit')
domain.com/234567/dashboard
domain.com/234567/some/other/task
But I want in the blade file do something like
<a href="{{ url('user.edit', array('foo', 'bar'), true) }}">My Route</a>
BUT I would not like have to pass the current account_id each time I write it in the blade file.
Any ideas on how I can do this.
One option would be to create a new URL generating function for your account URLs. You could put it in your routes
file, or include it before your routes execute:
if (!function_exists('aurl'))
{
/**
* Generate an account url for the application.
*
* @param string $path
* @param mixed $parameters
* @param bool $secure
* @return string
*/
function aurl($path = null, $parameters = array(), $secure = null)
{
// Here you would include logic to find the $account_id, or even use it from outside
// the function's scope.
// I'm using this as an example:
$account_id = Auth::user()->account_id;
return app('url')->to($path, array_merge(array($account_id), $parameters), $secure);
}
}
Then, inside of your views, you could just use the new aurl
function when you want a to create an account URL without specifying the account ID every time.
There are probably better ways to accomplish this, but this would work if you needed something quickly.
I like that, but I wonder if there is a way to overwrite or extend the url helpers.
I'm not sure if there is a Laravel way to overwrite the URL helpers, since they are just defined in a helpers.php
file and auto-loaded with Composer.
There are ways to override functions that do not belong to an object in PHP, but I really think that is overkill, requires an extension and much more of a hassle than it is worth.
However, the above function is identical to the url
helper function. I suppose the return line could be written as:
return url($path, array_merge(array($account_id), $parameters), $secure);
But it is not much of a difference.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community