3

I am having trouble with paths in the development and production environments in a laravel/vue.js project.

In CSS files:

Development environment npm run hot only accepts absolute paths in urls like /public/images/image.png while the production environment npm run prod + php artisan serve only accepts relative paths like ../images/image.png.

When I try to use a relative path in vue the images are not shown in the browser and the console shows:

GET http://localhost:63342/images/image.png?ffda917d2a7141d8413f313bccf119c5 404 (Not Found)

In vue templates:

In order to being able to use inline images in production I had to wrap the path inside require().default:

<img :src="require('../images/image.png').default" class="emailIcon" alt="">

require() does not seem to work in the development environment though. When I npm run hot the images are not shown.

Browser console shows:

GET http://localhost:63342/images/image.png?ffda917d2a7141d8413f313bccf119c5 404 (Not Found)

specs:

Windows 10
Laravel: 8.55.0
Vue.js: 4.5.13

Edit:

From @Chandan's comment I found that <img src="images/image.png"> works for both environments IF the images folder is inside public.

Unfortunately this doesn't work for url("images/image.png") if you want to put an image as background. Any insight there?

Edit2:

In the end there was no good solution for my problem. So I stopped using npm run hot and instead linked npm run watch to php artisan serve. Now I'm only using production server with hot reload. You can see here how to set it up.

Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132

1 Answers1

2

In the image controller you can upload your image like this or save it in the storage folder:

$extension = $request->image->extension();
$request->image->storeAs("location","name of image".".".$extension);
$imageName = Storage::url("location//name of image").".".$extension);

Post::create([ // Or image or which model your using to store your images
    'image_path' => $imageName,
]);

and then create a symbolic link by run

php artisan storage:link

Then u can make a route like this:

Route::get('image/{slug}/',[App\Http\Controllers\ImageController::class, 'show'])->name('image.show');

And controller like this:

class ImageController extends Controller
{
    public function show($slug)
    {
        // U can even make checks here if u want!
        $pathToFile = storage_path("location\\".$slug);
        return response()->file($pathToFile);
    }
}

And finally in PHP

<img src="{{url($image_path)}}"/>

or in JS

const src = window.location.origin + image_path;

And if the paths are correctly set the controller should return the image!

But this is if u want to implement a private foldor and want to make sure that user has to be logged in before accessing a image! but if ur folder is public you should just be able to do

    <div
            :style="{ backgroundImage: 'url(' + data.image + ')' }"
    />
HashtagForgotName
  • 651
  • 1
  • 7
  • 23