In one of my website in laravel, when I tried to integrate angularjs4 everything works fine. But I am facing a conflict issue with api routes and route defined in web
The code in my web.php is as follows
Route::get('/{path?}', function () {
return view('site');
})->where('path', '.*')
->name('siteapp');
Since the above code route everything to the view "site", I cannot able to add api request routes in api.php, example is given below
The link www.mysite.com/api/user routes to the route in "web.php" which should be from api.php
Route in my api.php
Route::get('user', function (Request $request) {
return ['name' => 'demo'];
})->middleware('jwt.auth');
Is there any regular expression to skip the path begin with www.mysite.com/api/something
I.e. from web.php. Is there any rule to skip path? begin with api in this line "where('path', '.*')"?
As a brief is it possible to skip path begin with api in the rule where('path', '[api]! [---allow all other string-]')
Please adivice
You can use a regEx for that like this :
Route::get('/{path?}', function () {
return view('site');
})->where('path', '^(?!api).*$')
->name('siteapp');
Related
I have a problem removing the route which does not exist in web.php but when I checked at PHP artisan route:list, its still appears on the list.
I'm trying to remove the route to access the default laravel breeze + react register. to replace with my own route.
Route::get('/', function () {
return Inertia::render('Welcome', [
'canLogin' => Route::has('login'),
]);
});
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::group(['middleware' => ['role:Admin']], function () {
Route::get('/new_register',
[\App\Http\Controllers\Auth\RegisteredUserController::class, 'create'])-
>middleware(['auth','verified'])->name('regis'); <-- my own route
});
this is the route list
as you can see , the route is not registered at web.php but still appear in route list
I want to build an Inventory app, everything was smooth until i want to make a page with URL pattern like
http://localhost:8000/product/edit/1
So i have this route in my React Router
<Route path='/product/edit/:product_id' component={MyComponent} />
Im using Redux to handle the state and Axios to get the data.
The problem is when i call the API , it's calling an URL of http://localhost:8000/product/edit/api/get-product-by-id. Of course im not getting any data returned.
The question is how to setup the Laravel Route for this problem?
Here is my web.php file
Route::get('/{path?}', function () {
return view('index');
})->where('path', '^((?!api).)*?');
What's wrong with using this approach?
I hope this solves your problem.
Route::get('/product/edit/{id}', function () {
return view('index');
});
I have two separate folders for my project, one has Laravel for backend part named as 'backend' and another has angularjs for frontend part named as frontend. My question is how to routing from laravel to angularjs?
I tried to do
Route::get('/', function () {
return view('index.html'); // 'index.html' is located at /project/frontend
});
Route::group(array('prefix' => 'api'), function() {
Route::resource('todos', 'TodoController');
});
in
/project/backend/routes/web.php
and I also changed paths in
/project/backend/config/view.php
to
'paths' => array(__DIR__.'/../frontend'),
This gives me
InvalidArgumentException View [index.html] not found
I think it is because I was not able to locate the right index.html file. I am new to Laravel and AngularJS, please help me!
I am working on a project based on ionic and angular js. I am loading JSON file which contains some JSON data in key-value pair. What I want to achieve is I have to call $urlRouterProvider.otherwise() method after json file is loaded completely. Following is the code which I have tried but it does not work for me. I have tried putting console in 'defaultRoute' function it is getting executed but '$urlRouterProvider.otherwise('/tab/myjobs')' this line doesn't work.The following code is present in app.config function. Any help will be appreciated.
$.getJSON('js/constants/'+lang+'.json')
.then(function(response) {
$translateProvider.translations(window.localStorage['deviceLanguage'],response);
defaultRoute($urlRouterProvider);
}, function(response) {
//$translate.use('en');
});
function defaultRoute($urlRouterProvider){
if(window.localStorage['userData']) {
var access_token = JSON.parse(window.localStorage['userData']).access_token;
if(access_token){
$urlRouterProvider.otherwise('/tab/myjobs');
}else{
$urlRouterProvider.otherwise('/login');
}
}else{
console.log("in line 282");
$urlRouterProvider.otherwise('/login');
}
}
The problem is that you are running an async method in the config phase.
AngularJS lifecycle is splitted in 2 phases, config (where you can use providers, but not services because these are not yet registered), and run (where you cannot use providers, but you can use services and in general is equivalent to the main function).
The run phase starts when config phase has finished, and config phase do not wait for any async process, so what is happening is that when your JSON get promise is solved your config phase has already finished (so any provider config you try to do in your promise success callback do not really config anything).
So in short, you cannot use $urlRouterProvider.otherwise() passing the result of an async call, like your getJson method.
A couple alternatives to what you are trying to do (redirect user depending on auth) are:
angular ui-router login authentication and angularjs redirect to login page if not authenticated with exceptions.
Consider using $state.go('someState')
You would want your code to look like this:
if(access_token){
$state.go('myJobs'); // where myJobs is the state correlated with your url 'tabs/jobs'
}else{
$state.go('login'); // or whatever the state name is that you have for 'login'
}
}else{
console.log("in line 282");
$state.go('login');
}
If you are trying to send the user to different routes conditionally, use $state.go('route.path') instead of updating the .otherwise() configuration. For example:
var app = angular.module('myapp',['ionic']);
app.controller('$scope', '$state','$http', [function($scope, $state, $http){
$http.get('my/api/path')
.then(function(response){
if(response.authenticated){
$state.go('secret.route');
} else {
$state.go('public.route');
}
});
}]);
I have a sample MVC6 single page app with one view in which I want to load 2 Angular partials using ngRoute. You can have a look at it at GitHub
There are 3 URLs in the app:
localhost - Index.cshtml
localhost/games - Index.cshtml with Angular's gamelist.html partial
localhost/games/2 - Index.cshtml with Angular's game.html partial
The routes config is the following:
MVC:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}");
routes.MapRoute("gamelist", "games", new { controller = "Home", action = "Index"});
routes.MapRoute("gameWithId", "games/2", new { controller = "Home", action = "Index" });
});
Angular:
myApp.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
$routeProvider
.when('/games', {
templateUrl: 'partials/gameslist.html',
controller: 'GameController',
controllerAs: 'ctrl'
})
.when('/games/:gameId', {
templateUrl: 'partials/game.html',
controller: 'GameController',
controllerAs: 'ctrl'
});
$locationProvider.html5Mode(true);
}]);
It all works perfectly fine as long as I start the app from the home page '/' and then navigate to the partials using the links on the page. The problem is that the URL #3 (localhost/games/2) does not work if I start the app from it, by typing it in the address bar. The URL #2 (/games/) does work.
The reason why #3 does not work is that MVC removes '/games' part from the URL and what Angular gets is just '/2'. If you run the sample app, you will see that '$location.path = /2'. Of course Angular cannot map using that path and no partial is rendered. So my question is - how to make MVC return the full path to the client so that Angular can map it?
You can get it to work with HTML5 mode, you just need to ensure that every request maps back to your Index.cshtml view. At that point the AngularJS framework loads, client-side routing kicks in and evaluates the request URI and loads the appropriate controller and view.
We've done this with multiple Angular apps inside MVC with different .cshtml pages, though we use attribute routing with the wildcard character, e.g.
[Route("{*anything}")]
public ActionResult Index()
{
return View("Index");
}
The wildcard operator (*) tells the routing engine that the rest of the URI should be matched to the anything parameter.
I haven't had chance to get to grips with MVC6 yet but I think you can do something like this with the "new" version of attribute routing?
[HttpGet("{*anything:regex(^(.*)?$)}"]
public ActionResult Index()
{
return View("Index");
}
To make link #3 work from the browser's address bar, I turned off "html5Mode" in Angular and made links #-based.
kudos to this blog
I think it is a better solution.
His solution is rewriting the request that doesn't fit to any route and doesn't have any extension to the landing page of angular.
Here is the code.
public class Startup
{
public void Configure(IApplicationBuilder app, IApplicationEnvironment environment)
{
// Route all unknown requests to app root
app.Use(async (context, next) =>
{
await next();
// If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
// Rewrite request to use app root
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/app/index.html"; // Put your Angular root page here
await next();
}
});
// Serve wwwroot as root
app.UseFileServer();
// Serve /node_modules as a separate root (for packages that use other npm modules client side)
app.UseFileServer(new FileServerOptions()
{
// Set root of file server
FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")),
// Only react to requests that match this path
RequestPath = "/node_modules",
// Don't expose file system
EnableDirectoryBrowsing = false
});
}
}