Error in SaaS routes - laravel

I am developing SaaS app and in routes i have following code
$subdomain = '';
$domain_parts = explode('.', Request::server('HTTP_HOST'));
if (count($domain_parts) == 3) {
$subdomain = $domain_parts[0];
if ($subdomain == 'www') {
$subdomain = '';
}
}
if (empty($subdomain)) {
Route::get('/', 'IndexController#showIntro');
} else {
Route::group(array('domain' => '{subdomain}.'.Config::get('app.domain'), 'before' => 'db.setup'), function() {
{
Route::get('/', array(
'as' => 'login',
'uses' => 'LoginController#showLoginForm'
));
Route::post('login', array(
'as' => 'performLogin',
'uses' => 'LoginController#performLogin'
));
Route::get('logout', array(
'as' => 'logout',
'uses' => 'LoginController#performLogout'
));
});
The problem is if subdomain is exists then it will not redirecting to login page. If i remove the content of the array in Route::group
then it will work but the array content is neccesarry, The error i am getting is NotFoundHttpExceptioni know there is a small mistake but not getting that, So any solution for this route error.
Thank you.

Your evaluation here is actually not necessary:
$subdomain = '';
$domain_parts = explode('.', Request::server('HTTP_HOST'));
if (count($domain_parts) == 3) {
$subdomain = $domain_parts[0];
if ($subdomain == 'www') {
$subdomain = '';
}
}
if (empty($subdomain)) {
Route::get('/', 'IndexController#showIntro');
} else {
You can get rid of this code, and then simply put
Route::get('/', 'IndexController#showIntro');
after the Route::group() for subdomain.
I do something like this:
Route::group(array('domain' => '{account}.' . Config::get('database.environment_url') .'') , function()
{
// Subdomain-only activity here.
}
// If there is no subdomain, Laravel will go straight to this route first.
Route::get('/' , 'IndexController#showIntro');
Hope this helps!
EDIT:: To add to this - as you know, WWW is considered a subdomain by laravel. If you want to do something special for the "www" subdomain, you can do it within the Subdomain group.

Related

simulate route in 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 ]);
}]);
});

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 | How to append parameter to URL when using Redirect::route and Redirect::back()?

My view provides links like http://finance.dev/home/customer/6#tab_1_3 so that user a can directly navigate to a tab in the page using the link.
In my routes I have :
Route::get('/home/customer/{id}',[
'as' => 'home.customer',
'uses' => 'CustomerController#show'
]);
Route::get('/home/customer/{id}/{navigate}/{tab}',[
'as' => 'home.customer.navigate',
'uses' => 'CustomerController#navigate'
]);
I am passing the required variables to route using:
window.location.href = '/home/customer/'+id+'/'+navigate+'/'+tab;
And my controller logic is :
public function navigate($id, $navigate, $tab)
{
$user = customer::find($id);
if($navigate == 'previous')
{
// get previous user id
$go = customer::where('id', '<', $user->id)->max('id');
}
elseif ($navigate == 'next') {
// get next user id
$go = customer::where('id', '>', $user->id)->min('id');
}
else{
return \Redirect::back();
}
return \Redirect::route('home.customer', array('id' => $go));
}
The above code successfully returns a URL like http://finance.dev/home/customer/6
Now I am trying to figure out how to define \Redirect::route and \Redirect::back() to return a URL like http://finance.dev/home/customer/6#tab_1_3
How can I go about this?
$url = URL::route('home.customer', ['id' => $go])."#tab_1_6";
return \Redirect::to($url);
Reference Link

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 login redirect doesn't work

I have made the login/tregistration form. Registration works well but login redirect doesn't work. I have the following function in my controller:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
and the routes.php
Route::resource('car', 'CarController');
Route::get('users', 'UserController#index');
Route::post('users/register', array('uses' => 'UserController#store'));
Route::post('users/signin', array('uses' => 'UserController#doLogin'));
Route::get('users/logout', array('uses' => 'UserController#doLogout'));
Route::get('/', 'CarController#index');
CarController
public function index() {
$cars = DB::select('select * from cars');
$result = DB::select('select c.*, i.sgs, i.tpl, i.kasko, i.inter_permis from cars as c left join insur_docs as i on i.car_id = c.id');
$date = Carbon::now();
$limit_date = Carbon::now()->addMonths(1);
return View::make('pages.index', array(
'cars' => $cars,
'result' => $result,
'date' => $date,
'limit_date' => $limit_date,
));
}
The problem is that it doesn't redirects to index page just refresh the page. If not correct credentials it shows "error" else if correct credentials it just refresh page and doesn't redirects. I f I replace redirect with success message it shows it. I have the same code localy and login with redirect is ok, but in google app engine (my project online) doesn't redirect.
The example you have used wouldn't actually redirect the user for two reasons.
The use of Redirect::route() excepts the parameter passed to be the name of a route, eg one defined like so
Route::get('/', ['as' => 'home', 'uses' => 'YourController#yourMethod']);
To redirect here you would use Redirect::route('home').
You aren't actually returning the redirect. Any response for a route, whether it be within a controller method or a closure, must be returned using the return keyword.
So to correct your code, it'd be like this:
public function doLogin() {
$credentials = [
'email' => Input::get('email'),
'password' => Input::get('password')
];
if (Auth::attempt($credentials)) {
return Redirect::to('/');
} else {
dd('error');
}
}
I moved the credentials to an array as it looks tidier and it makes it easier to read when displaying on this site, so you don't have to do that, but it may make things easier for you.

Categories

Resources