SOLVED Laravel website returns "Error 404" for GET requests - laravel

So I got a template of a Flutter app that retrieves all its data from a website using HTTP get requests.
I have the following method that gets the list of resturaunts:
Future<Stream<Restaurant>> getNearRestaurants(LocationData myLocation, LocationData areaLocation) async {
String _nearParams = '';
String _orderLimitParam = '';
if (myLocation != null && areaLocation != null) {
_orderLimitParam = 'orderBy=area&limit=5';
_nearParams = '&myLon=${myLocation.longitude}&myLat=${myLocation.latitude}&areaLon=${areaLocation.longitude}&areaLat=${areaLocation.latitude}';
}
final String url = '${GlobalConfiguration().getString('api_base_url')}restaurants?$_nearParams&$_orderLimitParam';
final client = new http.Client();
final streamedRest = await client.send(http.Request('get', Uri.parse(url)));
return streamedRest.stream.transform(utf8.decoder).transform(json.decoder).map((data) => Helper.getData(data)).expand((data) => (data as List)).map((data) {
return Restaurant.fromJSON(data);
});
}
However when I swap the template's url variable for my own website, the app gets stuck and streamRest returns with an error 404 page.
Tried Solutions:
I surrounded it with a try/catch block and it gave me no exceptions.
I also installed postman and checked my website with the GET statement for the same list of restaurants I try to retrieve in the flutter code posted above and see this: Postman GET screenshot
Its as if my website cannot route to the specific pages in my API folder. But they are all defined in api.php.
Update 1:
My web.php looks like this https://pastebin.com/QRG300uL. It seems to be similar to what was suggested below
Update 2:
I ran php artisan route::list and it showed that all the routes seem to be there:
| | POST | api/restaurant_reviews | restaurant_reviews.store | App\Http\Controllers\API\RestaurantReviewAPIController#store | api |
| | GET|HEAD | api/restaurant_reviews | restaurant_reviews.index | App\Http\Controllers\API\RestaurantReviewAPIController#index | api |
| | GET|HEAD | api/restaurant_reviews/create | restaurant_reviews.create | App\Http\Controllers\API\RestaurantReviewAPIController#create | api |
| | DELETE | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.destroy | App\Http\Controllers\API\RestaurantReviewAPIController#destroy | api |
| | GET|HEAD | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.show | App\Http\Controllers\API\RestaurantReviewAPIController#show | api |
| | PUT|PATCH | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.update | App\Http\Controllers\API\RestaurantReviewAPIController#update | api |
| | GET|HEAD | api/restaurant_reviews/{restaurant_review}/edit | restaurant_reviews.edit | App\Http\Controllers\API\RestaurantReviewAPIController#edit | api |
| | GET|HEAD | api/restaurants | restaurants.index | App\Http\Controllers\API\RestaurantAPIController#index | api |
| | POST | api/restaurants | restaurants.store | App\Http\Controllers\API\RestaurantAPIController#store | api |
| | GET|HEAD | api/restaurants/create | restaurants.create | App\Http\Controllers\API\RestaurantAPIController#create | api |
| | GET|HEAD | api/restaurants/{restaurant} | restaurants.show | App\Http\Controllers\API\RestaurantAPIController#show | api |
| | DELETE | api/restaurants/{restaurant} | restaurants.destroy | App\Http\Controllers\API\RestaurantAPIController#destroy | api |
| | PUT|PATCH | api/restaurants/{restaurant} | restaurants.update | App\Http\Controllers\API\RestaurantAPIController#update | api |
| | GET|HEAD | api/restaurants/{restaurant}/edit | restaurants.edit | App\Http\Controllers\API\RestaurantAPIController#edit | api |
| | POST | api/send_reset_link_email | | App\Http\Controllers\API\UserAPIController#sendResetLinkEmail | api |
| | GET|HEAD | api/settings | | App\Http\Controllers\API\UserAPIController#settings | api |
Solution:
This worked for me after changing alot of things, I changed my GET request url from "www.domain.com/api/resturants" to "www.domain.com/public/api/resturants"

Well i don't know about your flutter code for i use different methods in retrieving data from api but about the routes i suggest you do like me
in web.php the route file
//Api routes
Route::get('/company/api/fetch', 'ApiController#fetch_companies');
my api controller
public function fetch_companies()
{
$companies = Companies::all();
return response()->json($companies);
}
this way you will get the data passed to the route /company/api/fetch (you can modify that as you want) and when a get request enter this page it will return json
and for the request handling in flutter side i suggest you make your functions and classes as it is in the documentations
Note: that the flutter solution that i suggested may not work with your case for you are using Stream which is different than this type of requests because this type runs only ones while the Stream runs many times and gets data every time it gets new data from the server

Related

Getting same page on every URL/Route in Laravel8

I'm using default laravel auth , I have multiple routes with prefix group but when I use other routes/urls but giving the same page on every route which is View page the product
you can see my route
Auth::routes();
Route::prefix('products')->group(function () {
Route::get('/', [ProductsController::class, 'index']);
Route::get('/{code}', [ProductsController::class,'view_product'])->name('products.view_product');
});
On this below route giving the product_view page which I can't understand why is giving
Route::get('/test_route', , function () {
return 'Hello World';
});
+--------+----------+--------------------------+-----------------------------+--------------------------------------------------------
----+------------------------------------------+
| Domain | Method | URI | Name | Action
| Middleware |
+--------+----------+--------------------------+-----------------------------+--------------------------------------------------------
----+------------------------------------------+
| | GET|HEAD | api/user | generated::suiIeX6oHZWSnSP1 | Closure
| api |
| | | | |
| App\Http\Middleware\Authenticate:sanctum |
| | GET|HEAD | sanctum/csrf-cookie | generated::WKOquUKjM8nfHvKl | Laravel\Sanctum\Http\Controllers\CsrfCookieController#s
how | web |
| | GET|HEAD | products | generated::IucNuoXqqYtZPi70 | App\Http\Controllers\ProductsController#index
| web | |
| | GET|HEAD | {code} | products.view_product | App\Http\Controllers\ProductsController#view_product
| web |
+--------+----------+--------------------------+-----------------------------+--------------------------------------------------------
----+------------------------------------------+

Laravel Route not defined error on FP_route

I'm having a problem with a POST, when I try to run the page and data is loaded in the database table I'm trying to read I always get a Route [MAILFP_Tree] not defined error.
The code is triggered by a call for the route in the blade file that will visualize the page
<form action="{{route('MAILFP_Tree')}}" method="post">
the routes are the following
Route::get('FP_Tree', 'HomeController#toFP_Tree')->middleware('auth');
Route::post('FP_Tree', 'MailController#toFP_Tree')->middleware('auth')->name('MAILFP_Tree');
This is the controller created for the post method (it's the one called mailController)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \Illuminate\Support\Facades\Mail;
use App\Mail\emailFP_TreeRow;
use DB;
use Auth;
use App\AssociationHistorical;
class MailController extends Controller
{
public function toFP_Tree(Request $request)
{
$order_number = $request->input('order_number');
$customer_name = $request->input('customer_name');
$date_order_placed = $request->input('date_order_placed');
$item_number = $request->input('item_number');
$quantity = $request->input('quantity');
$item_description = $request->input('item_description');
$passed = array($order_number, $customer_name, $date_order_placed, $item_number, $quantity, $item_description);
Mail::to(Auth::user()->email)->send(new emailFP_TreeRow($passed));
//passes data to blade
$rows = AssociationHistorical::all();
return view('FP_Tree',[
'rows'=>$rows
]);
}
}
this is the content of the homecontroller
public function toFP_Tree()
{
//passes data to blade
$rows = AssociationHistorical::all();
return view('FP_Tree',[
'rows'=>$rows
]);
}
This is my migration table
Schema::create('association_historical', function (Blueprint $table) {
$table->id();
$table->string('order_number');
$table->string('item_number');
$table->string('item_description');
$table->date('date_order_placed');
$table->string('customer_name')->nullable();
$table->string('sales_rep_email');
});
The thing is that the problem happens when there is data in the association_historical table, most likely It is related to the fact that if there is no data in the database it won't run the post method, but i thought that it would make sense to show the database table...
the strange thing is that on someone else computer this works without any problem.
This is the result from PHP artisan route:list
+--------+----------+--------------------+-----------------------------+----------------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+--------------------+-----------------------------+----------------------------------------------------------+------------+
| | GET|HEAD | / | generated::UYk0LlF0PlICNJsK | App\Http\Controllers\LoginPageController#showLogin | web |
| | POST | / | login | App\Http\Controllers\LoginPageController#doLogin | web |
| | GET|HEAD | FP_Tree | generated::98bieUMU1hfvx1TH | App\Http\Controllers\HomeController#toFP_Tree | web |
| | | | | | auth |
| | GET|HEAD | Prediction | generated::4HdessOBvQL3KmpT | App\Http\Controllers\HomeController#toPrediction | web |
| | | | | | auth |
| | GET|HEAD | PredictionsLanding | generated::Xtf7I1MCKtlOSX3Y | App\Http\Controllers\HomeController#toPredictionsLanding | web |
| | | | | | auth |
| | GET|HEAD | UserManagement | generated::aOYFVG9JOLTfGjB5 | App\Http\Controllers\HomeController#toUserManagement | web |
| | | | | | auth |
| | GET|HEAD | api/user | generated::3SA9mFdg4RMncH1a | Closure | api |
| | | | | | auth:api |
| | GET|HEAD | logout | generated::YeCPB1fIxlH8JqDe | App\Http\Controllers\HomeController#doLogout | web |
| | | | | | auth |
+--------+----------+--------------------+-----------------------------+----------------------------------------------------------+------------+
it was so simple, thanks DigitalDrifter, just had to do a php artisan route:clear

Route returning Error 404 but the route exists

I have a blade template where I call a route to the show method:
<div class="user"><div><img src="{{asset('images/user.svg')}}" alt=""></div></div>
That route is controlled by a resource controller and the routes are set like this:
Route::resource('profile', 'App\Http\Controllers\ProfileController')->middleware('auth');
All the routes of that controller are defined as you can see from the output of my php artisan route:list:
| | GET|HEAD | profile | profile.index | App\Http\Controllers\ProfileController#index | web |
| | | | | | auth |
| | POST | profile | profile.store | App\Http\Controllers\ProfileController#store | web |
| | | | | | auth |
| | GET|HEAD | profile/create | profile.create | App\Http\Controllers\ProfileController#create | web |
| | | | | | auth |
| | GET|HEAD | profile/{profile} | profile.show | App\Http\Controllers\ProfileController#show | web |
| | | | | | auth |
| | DELETE | profile/{profile} | profile.destroy | App\Http\Controllers\ProfileController#destroy | web |
| | | | | | auth |
| | PUT|PATCH | profile/{profile} | profile.update | App\Http\Controllers\ProfileController#update | web |
| | | | | | auth |
| | GET|HEAD | profile/{profile}/edit | profile.edit | App\Http\Controllers\ProfileController#edit | web |
| | | | | | auth |
So far the controller only has a dd function since I haven't started writing it yet and the show method is the only one with anything written yet:
public function show($id)
{ dd($id);}
But for some reason, whenever I try acessing that route, it returns a 404 Not Found error. I tried accessing the index method and it works, but the show method always returns the 404 Not Found error. I also tried php artisan route:clear but it didn't solve the problem. What could I be doing wrong here?
Try out it , list all of router
php artisan route:list
Or you can as such that
Route::resource('profile', 'ProfileController', [
'names' => [
'index' => 'show.show'
'store' => 'profile.new',
]
]);
And if you try this ?
<div class="user"><div><img src="{{asset('images/user.svg')}}" alt=""></div></div>

Index Route missing in Resource Routes Laravel

I am unable to get the index route of my resource when using some prefix,
when my route is this:
Route::resource('subjects', 'SubjectController')->middleware('auth:admin');
i got this route listing:
| subjects | subjects.index
| subjects | subjects.store
| subjects/create | subjects.create
| subjects/{subject} | subjects.update
| subjects/{subject} | subjects.destroy
| subjects/{subject} | subjects.show
| subjects/{subject}/edit | subjects.edit
But when i add a prefix like this:
Route::prefix('admin')->group(function () {
Route::resource('subjects', 'SubjectController')->middleware('auth:admin');
});
The index route disappears, and routes list become this:
| admin/subjects | subjects.store
| admin/subjects/create | subjects.create
| admin/subjects/{subject} | subjects.update
| admin/subjects/{subject} | subjects.destroy
| admin/subjects/{subject} | subjects.show
| admin/subjects/{subject}/edit | subjects.edit
Got the solution. actually there was another route ('subjects') in my web.php. I needed to remove this, since they both were colliding.

Laravel - Routes GET|HEAD

When I do php artisan routes, the GET request of my app has a |HEAD. What is the purpose of having |HEAD?
Routes.php
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
| Domain | URI | Name | Action | Before Filters | After Filters |
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
| | GET|HEAD / | home | HomeController#home | | |
| | GET|HEAD user/{username} | profile-user | ProfileController#user | | |
| | GET|HEAD account/change-password | account-change-password | AccountController#getChangePassword | auth | |
| | GET|HEAD asset/encode-file/{id} | encode-file | EncodeController#getEncode | auth | |
| | GET|HEAD asset/edit-file/{id} | edit-file | AssetController#getEdit | auth | |
| | GET|HEAD asset/delete-file/{id} | delete-file | AssetController#deleteDestroy | auth | |
| | GET|HEAD asset/upload-file-form | upload-file-form | AssetController#getUploadCreate | auth | |
| | GET|HEAD asset/library | asset-library | AssetController#getAssetLib | auth | |
| | GET|HEAD account/sign-out | account-sign-out | AccountController#getSignOut | auth | |
| | GET|HEAD account/activate/{code} | account-activate | AccountController#getActivate | guest | |
| | GET|HEAD account/forgot-password | account-forgot-password | AccountController#getForgotPassword | guest | |
| | GET|HEAD account/recover/{code} | account-recover | AccountController#getRecover | guest | |
| | GET|HEAD account/sign-in | account-sign-in | AccountController#getSignIn | guest | |
| | GET|HEAD account/create | account-create | AccountController#getCreate | guest | |
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
The HEAD request is almost identical to a GET request, they only differ by a single fundamental aspect: the HEAD response should not include a payload (the actual data).
This makes the HEAD HTTP verb fundamental for managing the validity of your current cached data.
The value for a header field in the response of your HEAD request will warn you if your data is not up-to-date. After that you can make a proper GET request retrieving the updated data.
This can be achieved observing the Content-Length field or the Last-Modified field for example.
When working with large payloads, caching your data and making HEAD requests before the actual GET to check the validity of you current data can save you big money on data consumption.
You will know precisely when to retrieve the full payload.
The big question is: why is Laravel combining HEAD and GET HTTP verbs when you use Route::get()?
You can use Route::match('HEAD') to register your HEAD request, but I find it weird that we don't have Route::head().
From the HTTP RFC:
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
Following function is taken from the Laravel's Illuminate\Routing\Router.php class, when you use Route::get() method to add a route for your site/application, Laravel adds both methods for the url, it means that, these urls registered using getmethod could be accessed using both GET and HEAD HTTP method, and HEAD is just another HTTP verb/method, used for making a HEAD request.
/**
* Register a new GET route with the router.
*
* #param string $uri
* #param \Closure|array|string $action
* #return \Illuminate\Routing\Route
*/
public function get($uri, $action)
{
return $this->addRoute(array('GET', 'HEAD'), $uri, $action);
}

Resources