simulate route in laravel - laravel

I have this route defined
Route::get('test/something/{id?}', 'MyController#mymethod')->name('test.something');
So if go to domain_1.com/test/something/123 I get some page with data.
Now, I want to to show the exact same thing if the site if accessed form another domain with subdomain. I've defined this:
Route::group(['domain' => 'subdomain.domain_2.com'], function() {
Route::get('/', 'MyController#mymethod', ['id' => 123]);
});
but I got to subdomain.domain_2.com, I get Too few arguments error. How can I pass the id parameter to the method in the route?

You could use redirect like:
Route::get('test/something/{id?}', 'MyController#mymethod')->name('test.something');
Route::group(['domain' => 'subdomain.domain_2.com'], function() {
Route::get('/', function(){
return redirect('/test/something/123');
});
});
If you don't want to use redirect, you could check the current url from the method in the controller like:
public function mymethod($id=null){
$currentUrl = request()->url();
if (strpos($currentUrl, 'subdomain') !== false) {
$id = 123;
}
// your function
}

I've found this piece of code that gets the job done, but I'm not sure is the correct way to achieve what I want
Route::group(['domain' => 'subdomain.domain_2.com'], function()
{
Route::get('/', [ 'as' => 'some_alias', function()
{
return app()->make(App\Http\Controllers\MyController::class)->callAction('mymethod', $parameters = [ 'id' => 123 ]);
}]);
});

Related

how to pass different dynamic parameters at same position to access different view pages in laravel

These are my routes for which I am facing problem
Route to get the list of registered places in a particular city
Ex: http://localhost:8000/London, http://localhost:8000/London/Restaurants
Route::group(['namespace' => 'Page'], function() {
Route::group(['prefix' => '{city}', 'where' => ['city' => '[\w\d]+']], function() {
Route::get('/', 'CityPageController#showCityPage')->name('cityPage');
});
});
Route to get a particular user profile and its details such as reviews, photos etc.
Ex: http://localhost:8000/John, http://localhost:8000/John/reviews, http://localhost:8000/John/photos
Route::group(['namespace' => 'User'], function() {
Route::group(['middleware' => 'verified'], function() {
Route::group(['prefix' => '{username}', 'where' => ['username' => '[\w\d]+']], function() {
Route::get('/', 'ProfileController#showProfilePage')->name('profilePage');
Route::get('/reviews', 'ReviewController#showReviewPage')->name('reviewPage');
Route::get('/photos', 'ImageController#showPhotoPage')->name('photoPage');
});
});
});
The problem is that both of these routes are not working simultaneously.
The route the resides above the other takes precedence over the other route.
how to solve this problem of routing.
Edit
I know there is a way to achieve this functionality but I don't know how. Any help is appreciated.
Note: If you haven't, firstly I recommend to create a unique slug field on database first that will appear on url
Your route file
Route::get('{slug1}', 'PageController#singleSlug'); # slug 1 has to be unique i.e. username and cityname
Route::get('{slug1}/{slug2}', 'PageController#doubleSlug'); # combination of slug1 and slug2 has to be unique
The controller functions
public function singleSlug($slug1)
{
$user = User::where('name', $slug1)->first();
if ($user) {
return view('user')->compact('user');
}
$city = City::where('name', $slug1)->first();
if ($city) {
return view('city')->compact('city');
}
abort(404); # neither user nor city
}
public function doubleSlug($slug1, $slug2)
{
// check the slug2 as this value is always defined by the system
switch ($slug2) {
case 'Restaurants':
$city = City::with('restaurants')->where('name', $slug1)->first();
if ($city) {
$viewName = 'city_restos_listing';
$viewData = $city;
}
break;
case 'reviews':
$user = User::with('reviews')->where('name', $slug1)->first();
if ($user) {
$viewName = 'user_reviews_listing';
$viewData = $user;
}
break;
case 'photos':
$user = User::with('photos')->where('name', $slug1)->first();
if ($user) {
$viewName = 'user_photos_listing';
$viewData = $user;
}
break;
default:
abort(404); # the slug 2 is incorrect
break;
}
if(isset($viewName)) {
return view($viewName)->compact('viewData');
} else {
abort(404); # user or city not found
}
}
from Laravels point of view, both urls are the same:
{property}/
having different property names city and username doesn't make a differance because laravel will not understand that london is a city and say Prateek is a username.
A better approach I would suggest is to add an identefier of the model name before the prefix: EX. Route::group(['prefix' => 'users/{username}' ... instead of your approach and city before the city route.
have a look at this: https://laravel.com/docs/6.x/controllers#resource-controllers
add a prefix to distinguish these two kinds of route
Route::group(['prefix' => 'users/{username}'
and Route::group(['prefix' => 'cities/{city}'
An easy way to solve this issue :
Route::group(['namespace' => 'Page'], function() {
Route::group(['prefix' => 'city/{city}', 'where' => ['city' => '[\w\d]+']], function() {
Route::get('/', 'CityPageController#showCityPage')->name('cityPage');
});
});
Route::group(['namespace' => 'User'], function() {
Route::group(['middleware' => 'verified'], function() {
Route::group(['prefix' => 'profile/{username}', 'where' => ['username' => '[\w\d]+']], function() {
Route::get('/', 'ProfileController#showProfilePage')->name('profilePage');
Route::get('/reviews', 'ReviewController#showReviewPage')->name('reviewPage');
Route::get('/photos', 'ImageController#showPhotoPage')->name('photoPage');
});
});
});

Laravel group routing with parameter

I have this group in my route:
}
Route::group(['prefix' => 'v1/en'], function() {}
is it possible to change the 'en' segment uri in a parameter, so it can be changed depending on the request? Something like this:
Route::group(['prefix' => 'v1/{lang}'], function() {}
Yes you can, $lang will be available if you define your route group like this:
Route::group(['prefix' => 'v1/{lang}'], function() {
// ...
});
or with new syntax:
Route::prefix('v1/{lang}')->group(function() {
// ...
});
You can access it anywhere with:
request()->route()->parameter('lang');
You might want to checkout packages like this: Localization for Laravel
They basically do the same, and have nice middleware implementations to set locales etc.
How about to generate dynamically another route group with prefix $lang inside of group with v1 prefix?
$langs = ['en', 'de', 'it'];
Route::group(['prefix' => 'v1'], function() use ($langs) {
foreach($langs AS $lang) :
Route::group(['prefix' => $lang], function() {
Route::get('something', 'SomethingController#list');
});
endforeach;
});
or same logic (taken from here):
Route::group(['prefix' => 'v1'], function() use ($langs) {
Route::group(['prefix' => '{lang}'], function() {
Route::get('something', 'SomethingController#list');
});
});

Multi domain routing in Laravel 5.2

I have setup multi-domain routing in my laravel 5.2 app. What I want to achieve is if a user hits, membership.app, he should be served different homepage as compared to user who hits, erp.app domain.
Route::pattern('erp', 'erp.app|erp.domain.com');
Route::pattern('membership', 'membership.app|membership.domain.com');
Route::group(['middleware' => ['web', 'auth'], 'domain' => '{erp}'], function() {
Route::get('/', 'HomeController#getIndex');
Route::controller('members', 'MembersController');
Route::controller('users', 'UsersController');
Route::controller('settings', 'SettingsController');
});
Route::group(['middleware' => 'web', 'domain' => '{erp}'], function () {
Route::controller('auth', 'Auth\AuthController');
});
Route::group(['middleware' => 'web', 'domain' => '{membership}'], function () {
Route::controller('/', 'BecomeMemberController');
});
Route::group(['middleware' => 'web'], function () {
Route::controller('ajax', 'AjaxController');
});
I tried this setup, but it breaks the code with first param in each controller method being the url instead of intended value.
Suppose I have a method hello in members controller.
public function hello($param1, $param2)
{
....
}
If I access erp.app/members/hello/1/2 url and try to print out $param1 of controller method, it returns erp.app instead of intended 1 in this case.
Please help.
I don't know why aren't you seperating the routes to different controllers as you say the output will be quite different...
A quick example of to use that:
Route::group(['domain' => '{type}.myapp.com'], function () {
Route::get('members/hello/{id1}/{id2}', function ($type, $id1, $id2) {
// when you enter --> members.myapp.com/hello/12/45
var_dump($type); //memebers
var_dump($id1); //12
var_dump($id2); //45
});
});

Laravel Route basic: Get a route with old fashioned php params

I would like to be able to get a route like this:http://something.com/search?q=random_search
When I do this:
Route::get('search/{q}', function($q) {
return $q;
});
It will answer to http://something.com/search/random_search but it seems it doesn't work for what I expect.
Register your route without {q} and with a name.
Using closure:
Route::get('search', ['as' => 'search', function(){
$q = Input::get('q');
return $q;
}]);
Using controller:
Route::get('search', ['as' => 'search', 'uses' => 'SearchController#yourMethod']);
Then call the route by its name:
route('search', ['q' => 'search query']); // /search?q=search%20query
or
URL::route('search', ['q' => 'search query']);
If you are really keen on using URL GET:
Route::get('search', function() {
$q = Input::get('q');
return $q;
});

Laravel 4 : Route returning wrong information

I am setting up an API with Laravel so that I can connect with an AngularJS front-end.
I have 2 routes that go to the same controller method -> BallController#getSpecs
My routes are set up as follows:
Route::group(['prefix' => '/api/v1', 'before' => 'auth.basic'], function() {
Route::group(['prefix' => '/ball'], function() {
Route::get('/', 'BallController#getIndex');
Route::get('{id}', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
Route::get('{id}/specs', 'BallController#getSpecs');
});
});
Now I am having trouble with Route::get('specs', 'BallController#getSpecs'); route.
The getSpecs method is defined as follows:
public function getSpecs($id = null)
{
if(empty($id))
{
Ball::all()->each(function($ball) {
$json = [$ball->id => [
'name' => $ball->name,
'core' => $ball->core->toArray(),
'coverstock' => $ball->coverstock->toArray(),
'finish' => $ball->finish->toArray(),
'manufacturer' => $ball->manufacturer->toArray()
]];
});
return Response::json($json);
}
else
{
$ball = Ball::find($id);
if(empty($ball))
{
return Response::json('You\'ve got no ballss', 404);
}
else
{
return Response::json([$ball->id => [
'name' => $ball->name,
'core' => $ball->core->toArray(),
'coverstock' => $ball->coverstock->toArray(),
'finish' => $ball->finish->toArray(),
'manufacturer' => $ball->manufacturer->toArray()
]]);
}
}
}
When I call /api/v1/ball/1/specs specifying an id I get the correct information back, however when I call /api/v1/ball/specs my function returns my error message 'You've got no balls'
ID should be null in this cast putting me into the first part of my if statement but for some reason I am getting into my else and getting my error because obviously no ID was provided and the ball won't exist.
Any help/insight will be appreciated.
Edit: I think it may be sending it to the wrong method. I think that /api/v1/ball/specs is being sent to BallController#getIndex instead of BallController#getSpecs.
The problem is in this part of the routing:
Route::get('{id}', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
When it sees "/api/v1/ball/specs", it will actually call getIndex() with the "id" parameter set to "specs", because that's the first matching route. One way to fix it would be to define the "specs" route first before you define the "{id}" route. But a better solution would be to limit the accepted values of the "{id}" parmeter like this...
Route::get('{id}', 'BallController#getIndex')->where('id', '[0-9]+');
One other suggestion, there shouldn't be a leading "/" in your prefix values (apparently the code may be working anyway, but they aren't really supposed to be there. So the complete updated route might look like this...
Route::group(['prefix' => 'api/v1', 'before' => 'auth.basic'], function() {
Route::group(['prefix' => 'ball'], function() {
Route::get('/', 'BallController#getIndex');
Route::get('specs', 'BallController#getSpecs');
Route::get('{id}', 'BallController#getIndex')->where('id', '[0-9]+');
Route::get('{id}/specs', 'BallController#getSpecs')->where('id', '[0-9]+');
});
});

Resources