How to send to laravel request with api prefix? - laravel

location #laravelapi {
rewrite /api/(.*)?$ /api/index.php?$is_args$args last;
}
When we try access to api/routeexample, laravel gets only routeexample part, and throws 404 error. How we can send full url including 'api' part?

I m adding an example of how we define route for API request:
In routes/api.php
Route::group(['prefix' => 'v1'], function () {
Route::post('api_request', [App\Http\Controllers\YourController::class, 'targeted_function_name'])->name('api_request');
});

So I'm just added
include "api.php";
into my routes/web.php as hotfix, but i will search for better solution

Related

API routes return 404 in laravel

I have https://tenancyforlaravel.com/ installed in laravel to make multi-tenant and it works fine for the web routes.
My problem is that when I access my APIs then I get a 404 error in tenant domains.
tenancyforlaravel documentation: https://tenancyforlaravel.com/docs/v3/routes
It says that I must put all my APIs inside api.php file and wrap them in a Route group with this middleware so I put all my APIs inside api.php file and all my APIs as below:
Route::middleware('tenancy')->group(function () {
Route::name('api.')->namespace('Api')->group(function () {
Route::post('/login', 'AuthController#login')->name('login');
...
});
and when I access it using sub.local.test/api/login then I get 404 error.
Tested for tenancyforlaravel.com V3 and it works OK.
Route::middleware([
InitializeTenancyByDomain::class,
PreventAccessFromCentralDomains::class
])->prefix('api')->group(function () {
//
Route::name('api.')->namespace('App\Http\Controllers\Api')->group(function () {
Route::post('/login', 'AuthController#login')->name('login');
...
});
Put all your API routes inside api.php as below
use App\Http\Controllers\AuthController;
Route::group(['prefix' => '/{tenant}',
'middleware' => [InitializeTenancyByPath::class],],
function () {
Route::post('/login', [AuthController::class, 'login'])->name('login');
...
});
As you haven't mentioned your tenant identifier, I am using path as identifier, so using InitializeTenancyByPath middleware. Use whatever identifier middleware you want in place of that.
Access your API routes normally as you used to do, with your identifier. As this example uses path as identifier, the endpoint will look like:
sub.local.test/api/{tenant}/login

index "/" route not working when using with a prefix in Laravel

I have the following route declaration:
Route::name('test.')
->prefix('test')
->group(function() {
Route::get('/', function() {
dd('test');
})->name('index');
});
Trying to access /test will result in NotFoundException, although when calling route('test.index') it will resolve to /test.
Same exception when trying to access /test/ and when trying to change the line:
Route::get('/', function()...
to
Route::get('', function()...
As soon as I modify it to
Route::get('/test', function()...
it works when trying to access ´/test/test´ and it also resolved the uri correctly when calling route('test.index').
What am I missing to to get the route working using '/' ?

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

laravel_token is valid for first request but not subsequent requests

I have installed Laravel Passport and configured it according to the documentation. When calling axios.get from my VueJS file, the first call works as expected. the laravel_session Request Cookie is injected into the request, and the authentication passes, returning the resource.
My problem arises when I try to call the axios.get method again. My use case here is a search function. I'm making a call to /api/banking/accounts/search/{search-term} whenever the user types into a text field, using the code below:
remoteMethod(query) {
if (query !== '') {
this.loading = true;
axios.get(
`/api/banking/accounts/search/${escape(query)}`
).then(res => {
this.destinationAccountDirectory = res.data;
this.loading = false;
});
} else {
this.destinationAccountDirectory = [];
}
},
This code works fine without any auth:api middleware on the route, and for the first time with auth:api middleware. As can be seen from the screenshots below, the laravel_token value changes and is rejected on subsequent calls to the API.
**I've tried to removed the \Laravel\Passport\Http\Middleware\CreateFreshApiToken that was added to the web middleware group during passport installation, which seemed to have temporarily solved the issue, until I receive a 419 on a request shortly after. What could be causing the new laravel_tokens to be rejected? **
I solved this by removing the web middleware from my API route. Why it was there in the first place, I have no idea.
I changed my api.php from
Route::group([
'middleware' => [
'web',
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
to
Route::group([
'middleware' => [
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
Should the API routes be under the web group to benefit from the middleware, or is it purely for UI? Am I safe to do this?

Laravel 3 HTTP and HTTPS routes

I have the following code:
Route::get('/', function()
{
return 'non secure page';
});
Route::get('/', array('https' => true, function()
{
return 'secure page';
}));
What I expected to happen is that these two routes would be treated differently. The first is for http://example.com requests and the second for https://example.com. Respectively, these pages should show the text 'non secure page' and 'secure page'. What actually happens is that both show the text 'secure page'. This must mean that both routes are treated the same i.e. it doesn't matter if the request was over https or http - the same route is triggered.
I know I can resolve my issue by using if (Request::secure()){ //routes }; but that then leads me to the question what use are the HTTPS secure routes in laravel? What do they achieve and when should they be used?
I've looked at the docs, but it's not clear to me what is supposed to happen.
The documentation says:
When defining routes, you may use the "https" attribute to indicate that the HTTPS protocol should be used when generating a URL or Redirect to that route.
"https" and ::secure() are only used when generating URLs to routes, they're not used to provide https-only routes. You could write a filter to protect against non-HTTPS routes (example below). Or if you want to prevent any non-HTTPS access to your entire domain then you should reconfigure your server, rather than do this in PHP.
Route::filter('https', function() {
if (!Request::secure()) return Response::error(404);
});
Alternative filter response:
Route::filter('https', function() {
if (!Request::secure()) return Redirect::to_secure(URI::current());
});
References:
http://laravel.com/docs/routing#https-routes
http://laravel.com/docs/routing#filters
The problem is not related to HTTPS.
The documentation says,
Note: Routes are evaluated in the order that they are registered, so register any "catch-all" routes at the bottom of your routes.php file.
It means that your
Route::get('/', array('https' => true, function()
{
return 'secure page';
}));
is over-writing
Route::get('/', function()
{
return 'non secure page';
});
I was actually lead here by Spark from laravel.io and I thought I would clarify the doubt anyhow.
Regards

Resources