You are not logged in.

Important Note: This forum is being archived and will be completely locked down on the 7th of February. The new forum can be found at http://laravel.io.

Announcement

    Laravel 4 Advanced Architecture: Book Now On Sale

#1 2014-01-26 11:22:02

Ibland
Apprentice
Registered: 2014-01-26
Posts: 1

AngularJS and Laravel 4 routing conflict in HTML5 mode

I would like to remove the # hash from URLs using Angularjs' $locationProvider.html5Mode(true).

Example: The address bar displays http://localhost/shop instead of http://localhost/#/shop.

Everything works well untill I refresh a page. If i refresh, the following Laravel Route (defined in routes.php) is accesed

Route::resource('shop', 'ShoppingController')
not the AngularJS Route (defined in app.js)

$routeProvider.when('/shop', {
    templateUrl: 'templates/shop.html',
    controller: 'ShoppingController'
});

My Code:

routes.php (Laravel Routes)

Route::get('/', function() {
    return View::make('index');
});
Route::resource('shop', 'ShoppingController');
app.js (AngularJS Routes)

var app = angular.module('shoppingApp',['ngRoute','SharedServices']);

app.config(function($routeProvider, $locationProvider) {
    $routeProvider.when('/shop', {
        templateUrl: 'templates/shop.html',
        controller: 'ShoppingController'
    });
    $routeProvider.otherwise({ redirectTo: '/' });
    $locationProvider.html5Mode(true);
});

My directory structure:

Project
    /app
        /...
        /views
            -index.php (single page application file)
            -routes.php (Laravel routes)
    /public
        /...
        /js
            -angular.js
            -app.js
        -index.php (Laravel index file)

Tried Solutions:

Rewrite the htaccess file so that all requests are redirected to index.php (the single page application file, from where AngularJS would take over the routing). Problem: In this way the Laravel route (Route::resource('shop', 'ShoppingController'); - necessary for interaction with the database) becomes inaccessible to the AngularJS $http service:

app.js

app.controller("ShoppingController", function($scope, $http) {
    $http.get('/shop', { cache: true}).
        success(function(data, status) {
        $scope.items = data
    }).
    error(function(data, status) {
        console.log('Status: ' + status);
        });
});
Question: How can I solve the routing problem, so that the AngularJS route, not the Laravel Route gets accessed if I refresh localhost/shop?

Answer:
this excellent tutorial (scotch.io/tutorials/php/create-a-laravel-and-angular-single-page-comment-application) nicely explains how to separate laravel (backend) routing and angular js (frontend) routing.

Last edited by Ibland (2014-03-03 12:07:33)

Offline

Board footer

Powered by FluxBB

');