Skip to content

Commit 9183807

Browse files
author
ahmadhuss
committed
refactor: Store uploaded photo in storage/app/public/photos directory
* Image saved in the database with the following path `photos/${imagePath}.jpg` * Symlink `storage/app/public/photos` directory to `/public/storage` * Publicly we can access photos with following URL `asset("storage/$product->photo")`
1 parent 3f01276 commit 9183807

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

app/Http/Controllers/ProductController.php

+29-1
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,40 @@ public function create()
3939
*/
4040
public function store(StoreProductRequest $request)
4141
{
42+
// Q: What does it mean?
43+
/**
44+
* We will got photo with random name `photo/34432g23h4j32hj4.png`
45+
* It was uploaded in `storage/app/photo` (We have a new storage called photo Laravel created!)
46+
* So After that, We can store the database filename with directory in the database.
47+
* Actual filename was in the `storage` folder.
48+
* These are the default settings and these files are not publicly accessible.
49+
* But you can access the image with URL something like this:
50+
* basic.test/photos/435345345.png
51+
* Error: It will not found.
52+
* Why?
53+
* The `config/filesystems.php` has default array "disks" 'local' &
54+
* 'public'. Inside the store('photos' , OnWhichDiskYourDirectoryCreated)
55+
* Now Second parameter is important and we enter "public".
56+
* Now our storage will be inside "storage/public/photos" directory.
57+
* ----------
58+
* But Here is the problem In Real world laravel only show assets from the root
59+
* "/public" directory and our storage means photos are located at the "/storage/public"
60+
* So we have to use symlink or shortcut strategy.
61+
* If you symlink storage/app/public, all containing folders will be served there
62+
* the only thing that changes is that the content itself is not actually within
63+
* public, it is just referenced there.
64+
* "php artisan storage:link"
65+
* It will create the symlink.
66+
*/
67+
$path = $request->file('photo')->store('photos', 'public');
68+
//dd($path); //dump&die
69+
4270
Product::create([
4371
'name' => $request->name,
4472
'price' => $request->price,
4573
'category_id' => $request->category_id,
4674
'description' => $request->description,
47-
'photo' => ''
75+
'photo' => $path
4876
]);
4977
return redirect()->route('products.index');
5078
}

0 commit comments

Comments
 (0)