简体   繁体   中英

Laravel cannot find file in directory?

http://angulairapi.rohanchhabra.in/airports

This is a very simple route I have created in Laravel. It just takes a json file in the public directory, decodes it into an array and return the same json in response.

If you go the route (mentioned above), the error say "No such file or directory" but it exists in fact. It is working fine on my local machine. But when I pushed the same thing on my server, it is giving me this error.

http://gitlab.learningtechasia.com:8901/rohan0793/angulairapi.git

I have made the repository public so that everyone can have a look.

I have tested on my machine asset() is working for me and the path(public/airports.json) you have written reflect same error for me.

Laravel`s Helper function asset("file_name") generate a URL for an asset.

please check laravel`s helper function documentation for more detail

put this code in your routes.php and try again

<?php

Route::get('/airports', function(){
    $airports = json_decode(file_get_contents(asset("airports.json")));
    return Response::json($airports);
});

Route::get('/flights', function(){
    $airports = json_decode(file_get_contents(asset("flights.json")));
    return Response::json($airports);
});

EDIT

When you are working on local machine your url having word public ie localhost/project-name/public/airports.json.

but when you deploy project on server it seems it remove public word from url, so what happing here, server finding airports.json at location http://angulairapi.rohanchhabra.in/public/airports.json but its not actually there its at location http://angulairapi.rohanchhabra.in/airports.json , so it is recommended to use laravel function(in this case asset()) to generate url/assets link.

An alternative to asset() and Anands answer is the helper function public_path() . It returns an absolute file path from the system point of view and not a URL.

$airports = json_decode(file_get_contents(public_path().DIRECTORY_SEPARATOR."airports.json")));

asset() should be used for URLs to files. URLs that you send to the client. You should work with public_path() for internal things, such as getting the content of a file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM