Laravel prefix and AJAX - laravel

PROBLEM: AJAX request not working with prefix
Website works great without language prefix. But I need it.. So before (no middleware) and ajax post to domain.com/entitlement worked great.
However, when posting with prefix (domain.com/en/entitlement) and having the pre-fix middleware on throws an error MethodNotAllowedHttpException in RouteCollection.php line 219:
The stackoverflow posts I have seen on prefix routing are focusing on GET related issues. Like Laravel 5 route prefix. I have a POST issue (the GET works fine)
Any ideas?
ROUTES
Route::group(['middleware' => ['web']], function () {
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ]
],
function()
{
Route::get('/', array(
'as' => 'home',
'uses' => 'HomeController#getHome'
));
Route::post('/entitlement', array(
'as' => 'entitlement-post',
'uses' => 'HomeController#postEntlitment'
));
}
}
AJAX REQUEST
$.ajax({
type: 'POST',
url: '/entitlement', --> Becomes domain.com/en/entitlement
data: data,
dataType:'json',
beforeSend: function() {
},
...
LocalizationSessionRedirect
<?php namespace Mcamara\LaravelLocalization\Middleware;
use Illuminate\Http\RedirectResponse;
use Closure;
class LocaleSessionRedirect {
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle( $request, Closure $next )
{
$params = explode('/', $request->path());
$locale = session('locale', false);
if ( count($params) > 0 && $locale = app('laravellocalization')->checkLocaleInSupportedLocales($params[ 0 ]) )
{
session([ 'locale' => $params[ 0 ] ]);
return $next($request);
}
if ( $locale && app('laravellocalization')->checkLocaleInSupportedLocales($locale) && !( app('laravellocalization')->getDefaultLocale() === $locale && app('laravellocalization')->hideDefaultLocaleInURL() ) )
{
app('session')->reflash();
$redirection = app('laravellocalization')->getLocalizedURL($locale);
return new RedirectResponse($redirection, 302, [ 'Vary' => 'Accept-Language' ]);
}
return $next($request);
}
}

Thanks to tptcat the answer is to take out middleware of Mcmara's redirect.
UPDATED ROUTE
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
// 'middleware' => [ 'localeSessionRedirect', 'localizationRedirect' ] --> Not included
],
function()
{

Related

How to route app with multiple subdomain using Laravel

I have developed an application using Laravvel-5.8.
I have developed the application for just a single company whereby each table have a company_id derived from the company table as shown below:
class Company extends Model
{
protected $table = 'companies';
protected $fillable = [
'id',
'company_name',
'subdomain',
];
}
class User extends Authenticatable
{
protected $fillable = [
'name',
'company_id',
'email',
];
}
and the route/web.php looks like this:
Route::get('/', ['as' => '/', 'uses' => 'IndexController#getLogin']);
Auth::routes();
Route::get('/dashboard', 'HomeController#index')->name('dashboard');
// Config Module
Route::group(['prefix' => 'config', 'as' => 'config.', 'namespace' => 'Config', 'middleware' => ['auth']], function () {
Route::resource('countries', 'ConfigCountriesController');
Route::resource('nationalities', 'ConfigNationalitiesController');
});
// HR Module
Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () {
Route::resource('designations', 'HrDesignationsController');
Route::resource('departments', 'HrDepartmentsController');
Route::resource('employee_categories', 'HrEmployeeCategoriesController');
});
The main route is :
Route::get('/', ['as' => '/', 'uses' => 'IndexController#getLogin']);
which gives localhost:8888/myapp
config/app.php:
'env' => env('APP_ENV', 'production'),
'url' => env('APP_URL', 'localhost:8888/myapp'),
'asset_url' => env('ASSET_URL', null),
I'm asked to add sub-domains where each will see the data based on the company_id in each table
localhost:8888/myapp
localhost:8888/company1.myapp
localhost:8888/company2.myapp
All will use:
Route::get('/', ['as' => '/', 'uses' => 'IndexController#getLogin']);
After successful login will redirect to:
Route::get('/dashboard', 'HomeController#index')->name('dashboard');
Also each will only see it's data based on company_id
companies table:
id | company_name | subdomain
1 | Main |
2 | Company1 | company1
3 | Company2 | company2
Main=> localhost:8888/myapp
Company1=>localhost:8888/company1.myapp
Company2=>localhost:8888/company2.myapp
How do I modify:
route/web.php
config/app.php
to achieve this?
Thanks
There are two methods by which It can be done.
By Middleware
As per your question, login page urls can be localhost:8888/myapp, localhost:8888/company1.myapp, or localhost:8888/company2.myapp
Using middleware, we will keep the company name in the session using middleware. You can use it from session.
php artisan make:middleware VerifyDomain
will create a domain
<?php
namespace App\Http\Middleware;
use Closure;
class VerifyDomain
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$domain == "myapp"; // your company app name
$path = $request->getPathInfo(); // should return /company1.myapp or /company2.myapp or /myapp
if (strpos($path, ".") !== false) { // if path has dot.
list($subdomain, $main) = explode('.', $path);
if(strcmp($domain, $main) !== 0){
abort(404); // if domain is not myapp then throw 404 page error
}
} else{
if(strcmp($domain, $path) !== 0){
abort(404); // if domain is not myapp then throw 404 page error
}
$subdomain = ""; // considering for main domain value is empty string.
}
$company = Company::where('company_name', $subdomain)->firstOrFail(); // if not found then will throw 404
$request->session()->put('company_name', $company); //store it in session
return $next($request);
}
}
Then add it to route middleware.
In your controller you can redirect to different dashboards as per the company names stored in session.
In route groups
Route::domain('localhost:8888/myapp')->group(function () {
Route::get('/', function ($id) {
//
});
});
Route::domain('localhost:8888/{company_name}.myapp')->group(function () {
Route::get('/', function ($company_name, $id) {
$company = Company::where('company_name', $company_name)->firstOrFail();
// send the value of $company to data to send different view data
});
});

Laravel Localization Routes in Jetstream & Fortify

I am using Laravel 8 with the Jetstream and Fortify authentication module. All the auth module works, on the other hand I was in the process of making the site in multi-languages, and I found myself with errors in authentication.
My problem today is the following, when the user finishes registering, he must check his email, or Laravel tells me the following error :
> Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameter for [Route: verification.verify] [URI: {locale}/email/verify/{id}/{hash}] [Missing parameter: locale].
But, for the others routes like /en/login, /en/register, /en/user/profile ..., they work fine ! The error is just for the email validation, please help, thanks. To have control over my authentication routes, I ignored the default JetStream & Fortify routes in the app/providers
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return redirect()->route('home-locale', app()->getLocale());
})->name('home');
Route::group([
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']], function(){
Route::get('/', 'HomeController#index')->name('home-locale');
Auth::routes();
});
Route::get('/index', 'HomeController#index');
Route::post('/map-agents','MapController#ajaxRequestMap')->name('*','map.agents');
Route::post('/map-agents/agents','MapController#ajaxRequestAgent');
Route::group([
'middleware' => ['auth:sanctum', 'verified'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
});
Route::group([
'middleware' => ['auth'],
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function (){
Route::resource('agents', AgentsController::class);
});
routes/fortify.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Fortify\Features;
use Laravel\Fortify\Http\Controllers\AuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\ConfirmablePasswordController;
use Laravel\Fortify\Http\Controllers\ConfirmedPasswordStatusController;
use Laravel\Fortify\Http\Controllers\EmailVerificationNotificationController;
use Laravel\Fortify\Http\Controllers\EmailVerificationPromptController;
use Laravel\Fortify\Http\Controllers\NewPasswordController;
use Laravel\Fortify\Http\Controllers\PasswordController;
use Laravel\Fortify\Http\Controllers\PasswordResetLinkController;
use Laravel\Fortify\Http\Controllers\ProfileInformationController;
use Laravel\Fortify\Http\Controllers\RecoveryCodeController;
use Laravel\Fortify\Http\Controllers\RegisteredUserController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticatedSessionController;
use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticationController;
use Laravel\Fortify\Http\Controllers\TwoFactorQrCodeController;
use Laravel\Fortify\Http\Controllers\VerifyEmailController;
Route::group([
'middleware' => config('fortify.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
$enableViews = config('fortify.views', true);
// Authentication...
if ($enableViews) {
Route::get('/login', [AuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('login');
}
$limiter = config('fortify.limiters.login');
$twoFactorLimiter = config('fortify.limiters.two-factor');
Route::post('/login', [AuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$limiter ? 'throttle:'.$limiter : null,
]));
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
// Password Reset...
if (Features::enabled(Features::resetPasswords())) {
if ($enableViews) {
Route::get('/forgot-password', [PasswordResetLinkController::class, 'create'])
->middleware(['guest'])
->name('password.request');
Route::get('/reset-password/{token}', [NewPasswordController::class, 'create'])
->middleware(['guest'])
->name('password.reset');
}
Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
->middleware(['guest'])
->name('password.email');
Route::post('/reset-password', [NewPasswordController::class, 'store'])
->middleware(['guest'])
->name('password.update');
}
// Registration...
if (Features::enabled(Features::registration())) {
if ($enableViews) {
Route::get('/register', [RegisteredUserController::class, 'create'])
->middleware(['guest'])
->name('register');
}
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware(['guest']);
}
// Email Verification...
if (Features::enabled(Features::emailVerification())) {
if ($enableViews) {
Route::get('/email/verify', [EmailVerificationPromptController::class, '__invoke'])
->middleware(['auth'])
->name('verification.notice');
}
Route::get('/email/verify/{id}/{hash}', [VerifyEmailController::class, '__invoke'])
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware(['auth', 'throttle:6,1'])
->name('verification.send');
}
// Profile Information...
if (Features::enabled(Features::updateProfileInformation())) {
Route::put('/user/profile-information', [ProfileInformationController::class, 'update'])
->middleware(['auth'])
->name('user-profile-information.update');
}
// Passwords...
if (Features::enabled(Features::updatePasswords())) {
Route::put('/user/password', [PasswordController::class, 'update'])
->middleware(['auth'])
->name('user-password.update');
}
// Password Confirmation...
if ($enableViews) {
Route::get('/user/confirm-password', [ConfirmablePasswordController::class, 'show'])
->middleware(['auth'])
->name('password.confirm');
Route::get('/user/confirmed-password-status', [ConfirmedPasswordStatusController::class, 'show'])
->middleware(['auth'])
->name('password.confirmation');
}
Route::post('/user/confirm-password', [ConfirmablePasswordController::class, 'store'])
->middleware(['auth']);
// Two Factor Authentication...
if (Features::enabled(Features::twoFactorAuthentication())) {
if ($enableViews) {
Route::get('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'create'])
->middleware(['guest'])
->name('two-factor.login');
}
Route::post('/two-factor-challenge', [TwoFactorAuthenticatedSessionController::class, 'store'])
->middleware(array_filter([
'guest',
$twoFactorLimiter ? 'throttle:'.$twoFactorLimiter : null,
]));
$twoFactorMiddleware = Features::optionEnabled(Features::twoFactorAuthentication(), 'confirmPassword')
? ['auth', 'password.confirm']
: ['auth'];
Route::post('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'store'])
->middleware($twoFactorMiddleware);
Route::delete('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'destroy'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-qr-code', [TwoFactorQrCodeController::class, 'show'])
->middleware($twoFactorMiddleware);
Route::get('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'index'])
->middleware($twoFactorMiddleware);
Route::post('/user/two-factor-recovery-codes', [RecoveryCodeController::class, 'store'])
->middleware($twoFactorMiddleware);
}
});
routes/jetstream.php
<?php
use Illuminate\Support\Facades\Route;
use Laravel\Jetstream\Http\Controllers\CurrentTeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\ApiTokenController;
use Laravel\Jetstream\Http\Controllers\Livewire\PrivacyPolicyController;
use Laravel\Jetstream\Http\Controllers\Livewire\TeamController;
use Laravel\Jetstream\Http\Controllers\Livewire\TermsOfServiceController;
use Laravel\Jetstream\Http\Controllers\Livewire\UserProfileController;
use Laravel\Jetstream\Http\Controllers\TeamInvitationController;
use Laravel\Jetstream\Jetstream;
Route::group(
[
'middleware' => config('jetstream.middleware', ['web']),
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}']],
function () {
if (Jetstream::hasTermsAndPrivacyPolicyFeature()) {
Route::get('/terms-of-service', [TermsOfServiceController::class, 'show'])->name('terms.show');
Route::get('/privacy-policy', [PrivacyPolicyController::class, 'show'])->name('policy.show');
}
Route::group(['middleware' => ['auth', 'verified']], function () {
// User & Profile...
Route::get('/user/profile', [UserProfileController::class, 'show'])
->name('profile.show');
// API...
if (Jetstream::hasApiFeatures()) {
Route::get('/user/api-tokens', [ApiTokenController::class, 'index'])->name('api-tokens.index');
}
// Teams...
if (Jetstream::hasTeamFeatures()) {
Route::get('/teams/create', [TeamController::class, 'create'])->name('teams.create');
Route::get('/teams/{team}', [TeamController::class, 'show'])->name('teams.show');
Route::put('/current-team', [CurrentTeamController::class, 'update'])->name('current-team.update');
Route::get('/team-invitations/{invitation}', [TeamInvitationController::class, 'accept'])
->middleware(['signed'])
->name('team-invitations.accept');
}
});
});
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SetLocale::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
app/Http/Middleware/setLocale.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class SetLocale
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, Closure $next)
{
$languages = array_keys(config('app.languages'));
$route = $request->route();
if (request('change_language')) {
session()->put('language', request('change_language'));
$language = request('change_language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language)
{
$route->parameters['locale'] = $language;
if (in_array($language, $languages)) {
app()->setLocale($language);
}
return redirect(route($route->getName(), $route->parameters));
}
} elseif (session('language')) {
$language = session('language');
if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language && in_array($route->parameters['locale'], $languages))
{
$language = $route->parameters['locale'];
session()->put('language', $language);
}
} elseif (config('app.locale')) {
$language = config('app.locale');
}
if (isset($language) && in_array($language, $languages)) {
app()->setLocale($language);
}
return $next($request);
}
}

Sentinel and Laravel 5.2

I cant make Sentinel work. I don't know what to do anymore, i tried everything, hopefully someone else have some advice.
Problem is in online middleware where check method is false...
EDIT: i found out problem is sessions are not working in middleware, still no solution tho
EDIT2: looks like its permisions, i am on ubuntu, i have run same code with xampp on win10 and everything works fine, still no solution for ubuntu
routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/', ['as' => 'index' , 'uses' => 'UserController#index']);
Route::post('login', ['as' => 'login' , 'uses' => 'UserController#login']);
Route::post('register', ['as' => 'register' , 'uses' => 'UserController#register']);
Route::get('logout', ['as' => 'logout' , 'uses' => 'UserController#logout']);
Route::group(['prefix' => 'viva' , 'middleware' => ['online']], function () {
Route::get('/', ['as' => 'dashboard' , 'uses' => 'VivaController#dashboard']);
});
});
login method
public function login(){
$data = Input::all();
$credentials = [
'email' => $data["username"],
'password' => $data["password"],
];
$user = Sentinel::authenticate($credentials);
if (!empty($user)){
Sentinel::login($user);
//dd(Sentinel::check()); //---> this gives logged user...
return Redirect::route('dashboard');
}
else{
return Redirect::back()->withErrors(['fail', 'Neuspjela prijava! Molimo pokuĆĄajte ponovo.']);
}
}
online.php Middleware
class online
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next )
{
dd(Sentinel::check()); //---> this is always false
if (Sentinel::check())
{
return Redirect::route('dashboard');
}
else
{
return Redirect::route('index')->withErrors(['fail', 'Nemate prava na pristup ovim stranicama!']);
}
return $next($request);
}
}
For session, I believe you might need these permissions.
Note: assumption that Laravel is installed at /var/www/laravel
cd /var/www/laravel
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

Laravel5 multilanguage domains

I have some issues with Laravel5.
I got multiple domains linked to single application, but each domain can have multiple languages. Locale string should not appear until different language is selected for domain.
Maybe some one has experience with this.
etc.:
domain.com/home
domain.net
domain.lt/pagrindinis
domain.lt/en/home
I finally found solution:
On app.php i made custom array for locations:
'domains' => [
'domain_1' => [
'locales' => ['en', 'lt'],
'locale' => 'lt' // default locale for this domain
],
'domain_2' => [
'locales' => ['ru', 'en']
'locale' => 'ru',
],
];
and in route service provider.
/**
* Handle app requests
*
* #param Router $router
* #param Request $request
* #return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function map(Router $router, Request $request)
{
$locale = $this->getLocaleByDomain($request);
$requestLocale = $request->segment(1);
$options = [
'namespace' => $this->namespace
];
if (in_array($requestLocale, Config::get('app.domains')[$request->getHost()]['locales'])) {
$locale = $requestLocale;
$options = array_merge(
$options,
[
'prefix' => $locale
]
);
}
app()->setLocale($locale);
$router->group($options, function ($router) {
require app_path('Http/routes.php');
});
}
/**
* Retrieve locale by domain
*
* #param $request
* #return mixed
*/
protected function getLocaleByDomain($request)
{
$locale = Config::get('app.fallback_locale');
if (array_key_exists($request->getHost(), Config::get('app.domains'))) {
$locale = Config::get('app.domains')[$request->getHost()]['locale'];
}
return $locale;
}
Routes.php file contains:
$router->get(trans('routes.contacts'),
[
'as' => 'contacts',
'uses' => 'PagesController#contacts'
]
);
So what i reached is multiple domains, with multiple languages and pretty nice SEO url's for every locale. Maybe anyone can make some other ideas?

Laravel route method call works for closure function but not for Conroller#method

what is the difference between:
Route::post('insert/{slug}/{page_number}/{person_type_id}/{user_id}', function($slug) {
return Response::json(
[
'success' => false,
'slug' => $slug
]);
});
and this:
Route::post(
'{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}',
'PersonsController#insertBen'
);
The first one works. The latter used to work but it's no longer working now. I tried stepping through the code and the latter ends up going to the UsersController#login rather than to PersonsConroller#insertBen. So odd. This was working about a month ago. I'm trying to see what I changed with my version control but it's so strange that it's not working all of a sudden.
My posts are working fine as I can login and the post call to UsersController#doLogin is being called.
I even tested with this call:
Route::post(
'{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}',
'UsersController#insertTest'
);
/controllers/UsersController.php
public function insertTest($slug)
{
if ( Request::ajax() ) {
return Response::json( [
'success' => false,
'slug' => $slug
] );
}
}
But the PersonsController#insertBen doesn't work. My PersonsController is working fine as I can update using this controller. So what could be the problem? Anyone encounter something similar? Why does the route.php call the post on some of Controller#method but not on others? Why does the closure function work but not the Controller#method?
UPDATE
Here's the entire file. I even tested by putting that line close to the top of the file too.
/** ------------------------------------------
* Route binding
* ------------------------------------------
*/
App::bind('Acme\Repositories\Interfaces\IPersonRepository', 'Acme\Repositories\Person\DbPersonRepository');
App::bind('Acme\Repositories\Interfaces\IUserRepository', 'Acme\Repositories\User\DbUserRepository');
App::bind('Acme\Repositories\Interfaces\IPage15Repository', 'Acme\Repositories\Pages\Page15Repository');
/** ------------------------------------------
* Route model binding
* ------------------------------------------
*/
Route::model('user', 'User');
Route::model('comment', 'Comment');
Route::model('post', 'Post');
Route::model('role', 'Role');
/** ------------------------------------------
* Route constraint patterns
* ------------------------------------------
*/
Route::pattern('comment', '[0-9]+');
Route::pattern('post', '[0-9]+');
Route::pattern('user', '[0-9]+');
Route::pattern('role', '[0-9]+');
Route::pattern('token', '[0-9a-z]+');
/** ------------------------------------------
* Admin Routes
* ------------------------------------------
*/
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
# User Management
Route::get('users/', ['as' => 'admin.users.get.index', 'uses' => 'AdminUsersController#getIndex']);
Route::get('users/index', ['as' => 'admin.users.get.index_page', 'uses' => 'AdminUsersController#getIndex']);
Route::get('users/data', ['as' => 'admin.users.get.data', 'uses' => 'AdminUsersController#getData']);
Route::get('users/{user}/edit_user_by_page/{page_number}', ['as' => 'admin.users.get.edit_user_by_page', 'uses' => 'AdminUsersController#getEditUserByPage']);
# Admin Dashboard
Route::get('/', 'AdminDashboardController#getIndex' );
});
// Confide routes
Route::get('users/create', ['as' => 'confide.users.get.create', 'uses' => 'UsersController#create']);
Route::post('users', ['as' => 'confide.users.post.store', 'uses' => 'UsersController#store']);
Route::get('users/login', ['as' => 'confide.users.get.login', 'uses' => 'UsersController#login']);
Route::post('users/login', ['as' => 'users.login', 'uses' => 'UsersController#doLogin']);
Route::get('users/confirm/{code}', ['as' => 'confide.users.get.confirm', 'uses' => 'UsersController#confirm']);
Route::get('users/forgot_password', [ 'as' => 'users.forgot_password', 'uses' => 'UsersController#forgotPassword' ]);
Route::post('users/forgot_password', ['as' => 'confide.users.post.forgot_password', 'uses' => 'UsersController#doForgotPassword']);
Route::get('users/reset_password/{token}', ['as' => 'confide.users.get.reset_password', 'uses' => 'UsersController#resetPassword']);
Route::post('users/reset_password', ['as' => 'confide.users.post.reset_password', 'uses' => 'UsersController#doResetPassword']);
Route::get('users/resendconfirmationemail', [ 'as' => 'users.resendconfirmationemail', 'uses' => 'UsersController#getResendConfirmationEmail' ]);
Route::post('users/resendconfirmationemail', ['as' => 'confide.users.post.resendconfirmationemail', 'uses' => 'UsersController#postResendConfirmationEmail']);
Route::get('users/logout', ['as' => 'confide.users.get.logout', 'uses' => 'UsersController#logout'])->after('invalidate-browser-cache');
/** ------------------------------------------
* Frontend Routes
* ------------------------------------------
*/
Route::get('{slug}/users/page', ['as' => 'users.page.path', 'uses' => 'UsersController#getPage'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get page_number
Route::get('{slug}/users/page/{page_number}', ['before' => 'auth', 'as' => 'users.page.page_number', 'uses' => 'PersonsController#index'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get edit
Route::get('{slug}/users/page/{page_number}/edit', ['before' => ['auth', 'slug' ], 'as' => 'users.page.page_number.edit', 'uses' => 'PersonsController#edit'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//post insert-ben
Route::post('{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}', ['before' => 'auth', 'as' => 'users.page.page_number.insert', 'uses' => 'PersonsController#insertBen'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//post delete-ben
Route::post('{slug}/users/page/{page_number}/delete-ben/{person_type_id}/user/{user_id}/person_id/{person_id}/address_id/{address_id}/ben_id/{ben_id}', ['before' => 'auth', 'as' => 'users.page.page_number.delete', 'uses' => 'PersonsController#deleteBen'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//put update
Route::put('{slug}/users/page/{page_number}/update', ['before' => 'auth', 'as' => 'users.page.page_number.update', 'uses' => 'PersonsController#update'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get upgrade page when user goes to a page like (page 17 or other pages like page 9 and 10 I think) reserved only for irrevocable registered plans. TODO: get the upgrade View model
Route::get('{slug}/users/upgrade/{_meta}', [ 'as' => 'users.ugprade', 'uses' => 'PersonsController#upgrade' ] )->where('slug', '^\b(irrevocable){1}\b$');
//Paypal post Paypal info to tables paypals, paypal_transactions, pricings and getPaypalBtn
Route::put('paypal_transactions/{slug}/{page_number}/returnpaypalbtn', ['before' => 'auth', 'as' => 'paypal_transactions.returnpaypalbtn', 'uses' => 'PaypalTransactionsController#returnPaypalBtn'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
/** ------------------------------------------
* Tests:
* ------------------------------------------
*/
Route::get('users/{username}/page', ['as' => 'users.page.test', 'uses' => 'UsersController#getPageTest']);
Route::get('{slug}/users/show_sql', ['as' => 'users.page.show_sql', 'uses' => 'PersonsController#showSql'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
# Index Page - Last route, no matches
Route::get('/', array('before' => 'detectLang', 'uses' => 'UsersController#login'));
Boy, this took a long time to figure out. Thank God! What happened was that I had this line in my Route::filter('csrf', function().
This filter is called before your other Route::[method] so if there are any Route calls in your filter like I had in mine then your defined Route::[method] won't be called. I think by default but not 100% sure:
/app/filters.php
$token = Request::ajax() ? ( Request::header('X-CSRF-Token') ) : Input::get('_token');
Which I ended up getting from http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
It was an ajax call but this Request::header('X-CSRF-Token') was always null.
So I changed that to something more readable and that works.
if ( Request::ajax() )
{
$sRequestHeaderCSRF = Request::header('X-CSRF-Token');
if ( Request::header('X-CSRF-Token') === null || Request::header('X-CSRF-Token') === '' )
{
$token = Input::get('_token');
} else
{
$token = Request::header('X-CSRF-Token');
}
} else
{
$token = Input::get('_token');
}
The other snag was this Input::get('_token') which was returning null too.
I had to pass and, explicitly, name the _token in the data. I was, previously,
passing a serialized array as the data in the jQuery $.ajax. But the calls to
get the _token key name from this data in public function input($key = null, $default = null)
(see below) was not retrieving it from the serialized array; hence, the explicit key being passed as
'_token': oSerializeArray._token.
var oSerializeArray['_token'] = $('input[name="_token"]').val();
$.ajax({
type: action,
cache: false,
dataType: 'json',
url: sUrl,
data: {
'oSerializeArray': oSerializeArray,
'_token': oSerializeArray._token
},
beforeSend: function() {
}
})
.done( function( data, text, jqxhr ) {
data.success;
//data.iPersonsPK;
window.location.replace(sUrlEdit);
})
.fail( function ( data, jqxhr ) {
data.success;
})
.always( function ( data ) {
data.success;
});
Just fyi, Input::get('_token') is called from:
/vendor/illuminate/support/Illuminate/Support/Facades/Input.php
in this function:
public static function get($key = null, $default = null)
{
return static::$app['request']->input($key, $default);
}
and here:
/vendor/laravel/framework/src/Illuminate/Http/Request.php:248
in this function:
public function input($key = null, $default = null)
{
$input = $this->getInputSource()->all() + $this->query->all();
return array_get($input, $key, $default);
}
I had to step through the code.
This is my updated Route::filter('csrf', function():
Route::filter('csrf', function()
{
if ( Request::ajax() )
{
$sRequestHeaderCSRF = Request::header('X-CSRF-Token');
if ( Request::header('X-CSRF-Token') === null || Request::header('X-CSRF-Token') === '' )
{
$token = Input::get('_token');
} else
{
$token = Request::header('X-CSRF-Token');
}
} else
{
$token = Input::get('_token');
}
$sSessionToken = Session::token();
//if the tokens do not match then send to the login page
if (Session::token() != $token) {
return Redirect::to( 'users/login' );
}
});
Also, more fyi, for problems with your routes.php one may look at these files:
/vendor/laravel/framework/src/Illuminate/Routing/Router.php
/vendor/laravel/framework/src/Illuminate/Routing/Route.php
and set break points while looking at your stack calls during debugging.
BTW, I read that one can use this to set the X-CSRF token in the headers of your ajax calls with this:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
}
});
The above is referenced from http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
I'm wondering if Taylor Otwell has some info on the architechtural design and explanations of the framework.
I was going to read about Symfony but not sure if will help me more thoroughly understand the underpinnings of Laravel.
I know there is the Laravel API docs which is helpful but something more like a study of the design. Any ideas?

Resources