Laravel Routes::When no longer works. What would be the alternative? - laravel

Context, I'm bumping an old version of laravel into a newer version.
I have been able to fix several leaky holes, however, there is one, in particular, that is getting hard to find a solution for and that is this:
Route::when('admin/*', 'isAdmin');
It seems like the ::when thing no longer works.
Keep in mind I'm not a PHP developer, hell this is actually the first time I'm using PHP at all.
Here's the routing page (web.php)).
<?php
use Illuminate\Support\Facades\Route;
use App\Models\User;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::resource('admin/dashboard', 'App\Http\Controllers\DashboardController', array('only' => array('index')));
Route::resource('admin/companies', 'App\Http\Controllers\CompaniesController');
Route::resource('admin/users', 'App\Http\Controllers\UsersController');
Route::resource('admin/public_polls', 'App\Http\Controllers\PublicPollsController');
Route::resource('admin/public_polls.public_poll_options', 'App\Http\Controllers\PublicPollsOptionsController',array('except' => array('index')));
/** Define filter to all admin actions **/
Route::when('admin/*', 'isAdmin');
/** Login/Register Routes **/
Route::get('/', array(
'uses' => 'App\Http\Controllers\loginController#index',
'as' => 'home'
));
Route::post('/', array(
'uses' => 'App\Http\Controllers\loginController#login',
'as' => 'home'
));
Route::post('register', array(
'uses' => 'App\Http\Controllers\loginController#register',
'as' => 'register'
));
Route::get('register', array(
'uses' => 'App\Http\Controllers\loginController#index',
'as' => 'register'
));
/*Route::get('logout', array(
'uses' => 'loginController#logout',
'as' => 'logout'
))->before('auth');
*/
Route::get('welcome', function() {
if ( User::isAdmin(Auth::user()->id) ) {
return Redirect::to('admin/dashboard');
}
return View::make('welcome');
});
/*
Route::get('teste', function() {
return 'Ecrã de teste';
dd(User::isAdmin(Auth::user()->id));
});*/
/** Email Routes **/
Route::get('email', function() {
$data['name'] = 'Random_Name';
// Mail::pretend();
Mail::send('emails.auth.accountActivation', $data, function($message){
$message->to('random_email#email.com')->subject('Welcome');
});
return 'Email sent!';
});
/*
Event::Listen('laravel.query', function(){
var_dump($sql);
});*/

Nevermind fellows, found the solution, it was as easy as doing a Route::group() and moving the resources with /admin inside the group.
Route::group([
'prefix' => '/admin',
'as' => 'admin.',
], function () {
Route::resource('/dashboard', 'App\Http\Controllers\DashboardController', array('only' => array('index')));
Route::resource('/companies', 'App\Http\Controllers\CompaniesController');
Route::resource('/users', 'App\Http\Controllers\UsersController');
Route::resource('/public_polls', 'App\Http\Controllers\PublicPollsController');
Route::resource('/public_polls.public_poll_options', 'App\Http\Controllers\PublicPollsOptionsController',array('except' => array('index')));
});
/** Define filter to all admin actions **/
//Route::when('admin/*', 'isAdmin');
This way it also generates the stuff like admin.companies.create and admin.users.create

Related

Own RoleMiddleware doesn't get called properly

just some weeks ago I started with Laravel and I made some good progress in these weeks with my project.
3 days ago I decided to implement some roles for my users in the system.
I created a middleware via artisan and wrote the code for it.
The problem I have is to assign my middleware to a specific route.
First I added this line to the $routeMiddleware-array in the Kernel.php: 'role' => \App\Http\Middleware\RolesMiddleware::class,.
my routes/web.php-file looks like this on:
// Member area
Route::group(['prefix' => 'member', 'middleware' => ['auth', 'role']], function() {
Route::get('dashboard', ['as' => 'dashboard', 'uses' => function () {
return view('member.dashboard');
}]);
Route::group(['prefix' => 'user'], function() {
Route::get('showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers',
'roles' => 'manageUsers'
]);
});
});
First I had only the 'auth' middleware in the first group and I wanted to add my 'role' middleware as additional action directly on my get-route like middleware => 'role:manageUsers'. In this case my middleware was ignored totally and did not get called in any case.
After is put the middleware in the array like in the code above it got called at least.
Now I tried to add a custom action 'roles' with the value 'managerUsers' to my get-route. The middleware still gets called and if output the actions via var_dump(request->route()->getAction()); I see the actions 'uses' and 'as' but not my custom action 'roles'.
I have srsly no clue whats wrong. Does anyone know if it isn't possible to add custom actions or an additional middleware to a specific route?
Best regards.
EDIT 1 (17.07.2017)
My \app\Http\Middleware\RolesMiddleware.php looks like this:
namespace App\Http\Middleware;
use Closure;
class RolesMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param \string[] ...$roles
* #return mixed
*/
public function handle($request, Closure $next, string ...$roles)
{
var_dump($roles);
die('middleware reachted');
}
}
My \app\Http\Kernel.php looks like this:
...
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'role' => \App\Http\Middleware\RolesMiddleware::class,
];
...
And my \routes\web.php look like this:
...
Route::group(['prefix' => 'member', 'middleware' => ['auth', 'role']], function() {
...
Route::group(['prefix' => 'user'], function() {
Route::get('showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers'
]);
});
});
...
If I do assign my middleware as an array together with the "auth" middleware, my one will be called. The point is, that I want to define a role the user has to have with a specific route. (In this case with the Route::get(...))
If I do assign my middleware not together with the "auth" middleware (e.g. in the group with prefix "user"), it will be totally ignored. The same if I do assign my middleware with the get-route directly.
Route::group(['prefix'=>'user', 'middleware'=>'role:manageUsers'], function() {
Route::get('/showUsers',[
'uses' => 'UserController#showUsers',
'as' => 'manageUsers'
]);
});
Your RolesMiddleware.php:
class RolesMiddleware{
public function handle($request, Closure $next, ...$roles){
// sent arguments are stored in $roles array
print_r($roles); // Array ( [0] => manageUsers )
}
}
Have you registered your middleware in your kernel.php?
Best regards...
As usual the problem was in front of the PC.
I copied some more routes for later usage and forgot to change the value for 'as' in the action-array.
Because I'm using the value of the 'as' key for my template to find the correct page I got redirected by another route than expected. Sadly this one pointed to the same controller and action and I didn't noticed the wrong URL in my browsers adress bar.
My role-middleware worked as expected but I just accessed the wrong page.

Links to forum keeps being truncated

Please I need help with how my links to the chatter forum are truncated when I click on discussions or any other link on the forum homepage.
A quick solution would be very much appreciated.Kindly Check the URL
Here's an example:
instead of;
localhost/apps/school/forums/discussions
it shows as:
localhost/forums/discussions
Below is the Route/web.php
<?php
/**
* Helpers.
*/
// Route helper.
$route = function ($accessor, $default = '') {
return $this->app->config->get('chatter.routes.'.$accessor, $default);
};
// Middleware helper.
$middleware = function ($accessor, $default = []) {
return $this->app->config->get('chatter.middleware.'.$accessor, $default);
};
// Authentication middleware helper.
$authMiddleware = function ($accessor) use ($middleware) {
return array_unique(
array_merge((array) $middleware($accessor), ['auth'])
);
};
/*
* Chatter routes.
*/
Route::group([
'as' => 'chatter.',
'prefix' => $route('home'),
'middleware' => $middleware('global', 'web'),
'namespace' => 'DevDojo\Chatter\Controllers',
], function () use ($route, $middleware, $authMiddleware) {
// Home view.
Route::get('/', [
'as' => 'home',
'uses' => 'ChatterController#index',
'middleware' => $middleware('home'),
]);
// Single category view.
Route::get($route('category').'/{slug}', [
'as' => 'category.show',
'uses' => 'ChatterController#index',
'middleware' => $middleware('category.show'),
]);
/*
* Auth routes.
*/
// Login view.
Route::get('login', [
'as' => 'login',
'uses' => 'ChatterController#login',
]);
// Register view.
Route::get('register', [
'as' => 'register',
'uses' => 'ChatterController#register',
]);
/*
* Discussion routes.
*/
Route::group([
'as' => 'discussion.',
'prefix' => $route('discussion'),
], function () use ($middleware, $authMiddleware) {
// All discussions view.
Route::get('/', [
'as' => 'index',
'uses' => 'ChatterDiscussionController#index',
'middleware' => $middleware('discussion.index'),
]);
// Create discussion view.
Route::get('create', [
'as' => 'create',
'uses' => 'ChatterDiscussionController#create',
'middleware' => $authMiddleware('discussion.create'),
]);
// Store discussion action.
Route::post('/', [
'as' => 'store',
'uses' => 'ChatterDiscussionController#store',
'middleware' => $authMiddleware('discussion.store'),
]);
// Single discussion view.
Route::get('{category}/{slug}', [
'as' => 'showInCategory',
'uses' => 'ChatterDiscussionController#show',
'middleware' => $middleware('discussion.show'),
]);
// Add user notification to discussion
Route::post('{category}/{slug}/email', [
'as' => 'email',
'uses' => 'ChatterDiscussionController#toggleEmailNotification',
]);
/*
* Specific discussion routes.
*/
Route::group([
'prefix' => '{discussion}',
], function () use ($middleware, $authMiddleware) {
// Single discussion view.
Route::get('/', [
'as' => 'show',
'uses' => 'ChatterDiscussionController#show',
'middleware' => $middleware('discussion.show'),
]);
// Edit discussion view.
Route::get('edit', [
'as' => 'edit',
'uses' => 'ChatterDiscussionController#edit',
'middleware' => $authMiddleware('discussion.edit'),
]);
// Update discussion action.
Route::match(['PUT', 'PATCH'], '/', [
'as' => 'update',
'uses' => 'ChatterDiscussionController#update',
'middleware' => $authMiddleware('discussion.update'),
]);
// Destroy discussion action.
Route::delete('/', [
'as' => 'destroy',
'uses' => 'ChatterDiscussionController#destroy',
'middleware' => $authMiddleware('discussion.destroy'),
]);
});
});
/*
* Post routes.
*/
Route::group([
'as' => 'posts.',
'prefix' => $route('post', 'posts'),
], function () use ($middleware, $authMiddleware) {
// All posts view.
Route::get('/', [
'as' => 'index',
'uses' => 'ChatterPostController#index',
'middleware' => $middleware('post.index'),
]);
// Create post view.
Route::get('create', [
'as' => 'create',
'uses' => 'ChatterPostController#create',
'middleware' => $authMiddleware('post.create'),
]);
// Store post action.
Route::post('/', [
'as' => 'store',
'uses' => 'ChatterPostController#store',
'middleware' => $authMiddleware('post.store'),
]);
/*
* Specific post routes.
*/
Route::group([
'prefix' => '{post}',
], function () use ($middleware, $authMiddleware) {
// Single post view.
Route::get('/', [
'as' => 'show',
'uses' => 'ChatterPostController#show',
'middleware' => $middleware('post.show'),
]);
// Edit post view.
Route::get('edit', [
'as' => 'edit',
'uses' => 'ChatterPostController#edit',
'middleware' => $authMiddleware('post.edit'),
]);
// Update post action.
Route::match(['PUT', 'PATCH'], '/', [
'as' => 'update',
'uses' => 'ChatterPostController#update',
'middleware' => $authMiddleware('post.update'),
]);
// Destroy post action.
Route::delete('/', [
'as' => 'destroy',
'uses' => 'ChatterPostController#destroy',
'middleware' => $authMiddleware('post.destroy'),
]);
});
});
});
/*
* Atom routes
*/
Route::get($route('home').'.atom', [
'as' => 'chatter.atom',
'uses' => 'DevDojo\Chatter\Controllers\ChatterAtomController#index',
'middleware' => $middleware('home'),
]);
You need to set the root directory to point to the public folder in laravel for the url rewriting to work and this won't happen when you're using xampp/wamp and accessing the url like folder structure. Only the index page of laravel app would work and other pages would throw errors. Also the links generated would not be accurate since laravel uses the base app url.
You should run php artisan serve and access your app with http://localhost:8000. This solves your routing and url generating issues. The other option would be to modify the virtual hosts in your local installation which isn't as easy.

Sharing routes between multiple prefixes

I'm trying to cut down on the size of my routes file and re-use named routes. I have two separate areas that are authenticated and have their own specialized routes, however, both of them share a LOT of other routes in common.
Route::group(['middleware' => 'web'], function () {
/**
* Author routes.
*/
Route::group(['prefix' => 'author', 'middleware' => 'auth'], function () {
Route::get('/', ['as' => 'dashboard', 'uses' => 'Controller#showHome']);
// ...various routes unique to authors...
Route::any('posts/data', ['as' => 'posts.data'])->uses('PostsController#data');
Route::get('posts/{account?}', ['as' => 'posts.show'])->uses('PostsController#index');
Route::get('posts/{post}/delete', ['as' => 'posts.delete'])->uses('PostsController#destroy');
Route::resource('posts', 'PostsController', ['parameters' => 'singular']);
// ...lots more routes like the above shared with reviewers...
});
/**
* Reviewer routes.
*/
Route::group(['prefix' => 'reviewer', 'middleware' => 'auth'], function () {
Route::get('/', ['as' => 'dashboard', 'uses' => 'Controller#showHome']);
// ...various routes unique to reviewers...
Route::any('posts/data', ['as' => 'posts.data'])->uses('PostsController#data');
Route::get('posts/{account?}', ['as' => 'posts.show'])->uses('PostsController#index');
Route::get('posts/{post}/delete', ['as' => 'posts.delete'])->uses('PostsController#destroy');
Route::resource('posts', 'PostsController', ['parameters' => 'singular']);
// ...lots more routes like the above shared with authors...
});
});
I still need a reviewer to go to example.com/reviewer/posts to do all post related activities and authors to go to example.com/author/posts.
How can I make this a lot less verbose?
Create a separate route file e.g. post_routes.php and put all your shared Post route in there.
Include the route file
Route::group(['prefix' => 'author', 'middleware' => 'auth'], function () {
require app_path('Http/post_routes.php');
});
/**
* Reviewer routes.
*/
Route::group(['prefix' => 'reviewer', 'middleware' => 'auth'], function () {
require app_path('Http/post_routes.php');
});

How to add route group inside another route group.. Laravel 5

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::group(['middleware' => 'cors'], function(Router $router){
});
Route::group([
'prefix' => 'api/v1',
'namespace' => 'Api'
], function () {
Route::post('/auth/register', [
'as' => 'auth.register',
'uses' => 'AuthController#register'
]);
Route::post('/auth/login', [
'as' => 'auth.login',
'uses' => 'AuthController#login'
]);
});
I want to add the prefix group route inside the middleware route, how can i achieve that?
You can nest route groups inside of each other. Just wrap one in the closure of the other.
Route::group(['middleware' => 'cors'], function(Router $router){
Route::group(
[
'prefix' => 'api/v1',
'namespace' => 'Api'
], function () {
Route::post('/auth/register', [
'as' => 'auth.register',
'uses' => 'AuthController#register'
]);
Route::post('/auth/login', [
'as' => 'auth.login',
'uses' => 'AuthController#login'
]);
});
});
hey i solved this by,
Route::group([
'prefix' => 'api/v1',
'namespace' => 'Api',
'middleware' =>'cors'
],
function () {
Route::post('/auth/register', [
'as' => 'auth.register',
'uses' => 'AuthController#register'
]);
Route::post('/auth/login', [
'as' => 'auth.login',
'uses' => 'AuthController#login'
]);
});
but the problem here is i am getting this error
XMLHttpRequest cannot load http://localhost:8000/api/v1/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 500.
is there any problem with my chrome cause i heard there is plugin for cors in chrome.
Thanks :)

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