{"id":9527,"date":"2020-01-25T06:49:33","date_gmt":"2020-01-25T06:49:33","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=9527"},"modified":"2021-11-13T06:18:13","modified_gmt":"2021-11-13T06:18:13","slug":"how-to-store-and-retrieve-image-from-the-database-in-laravel","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/how-to-store-and-retrieve-image-from-the-database-in-laravel\/","title":{"rendered":"How to store and retrieve image from the database in Laravel."},"content":{"rendered":"\n<p><strong># Creating Migration For Uploading Image<\/strong><\/p>\n\n\n\n<p>We need to add three lines in our migration file which makes column in our Database .<br>After adding, run Migration .<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/pradeeprjth\/52256cdd922c4bac6e19b3edc6dd3a56.js\"><\/script>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"CSS\" data-shcb-language-slug=\"css\"><span><code class=\"hljs language-css\"><span class=\"hljs-selector-tag\">php<\/span> <span class=\"hljs-selector-tag\">artisan<\/span> <span class=\"hljs-selector-tag\">migrate<\/span><span class=\"hljs-selector-pseudo\">:reset<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">CSS<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">css<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><strong># Blade Form<\/strong><\/p>\n\n\n\n<p>Now we need to make a form for uploading Image into Database. <br>Let us add new user&nbsp;<strong>input of file type<\/strong>&nbsp;in the&nbsp;<code>insert.blade.php<\/code>. Also, for file uploading, we need to add an&nbsp;<code>enctype<\/code>&nbsp;attribute in the&nbsp;<code>form<\/code>&nbsp;tag: <\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/pradeeprjth\/52256cdd922c4bac6e19b3edc6dd3a56.js\"><\/script>\n\n\n\n<p><strong># Initial Test<\/strong><\/p>\n\n\n\n<p>Now test your changes by serving the  Development Server in command line.(gitbash).<br>During development, It is always a good habit to check the output after minor changes so you can resolve errors quickly. Run the application in the browser and check if the&nbsp;<strong>create form now has a file input field<\/strong>.<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">php artisan serve<\/code><\/span><\/pre>\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"520\" height=\"448\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2020\/01\/formsite-file-upload-sample.jpg\" alt=\"\" class=\"wp-image-9529\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2020\/01\/formsite-file-upload-sample.jpg 520w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2020\/01\/formsite-file-upload-sample-300x258.jpg 300w\" sizes=\"auto, (max-width: 520px) 100vw, 520px\" \/><\/figure>\n\n\n\n<p>When you upload images, it needs to be stored by the application in local disk . Thus it required some file system configuration to save the file at the right place so that it can be retrieve latter .<\/p>\n\n\n\n<p><strong># Storing Images via Controller<\/strong><\/p>\n\n\n\n<p>We will need to store image details in the database. Replace the store method with following:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"PHP\" data-shcb-language-slug=\"php\"><span><code class=\"hljs language-php\"><span class=\"hljs-comment\"># app\/Http\/Controllers\/BookController.php<\/span>\n\n...\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Support<\/span>\\<span class=\"hljs-title\">Facades<\/span>\\<span class=\"hljs-title\">Storage<\/span>;\n<span class=\"hljs-keyword\">use<\/span> <span class=\"hljs-title\">Illuminate<\/span>\\<span class=\"hljs-title\">Support<\/span>\\<span class=\"hljs-title\">Facades<\/span>\\<span class=\"hljs-title\">File<\/span>;\n...\n<span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">store<\/span><span class=\"hljs-params\">(Request $request)<\/span>\n<\/span>{\n    request()-&gt;validate(&#91;\n        <span class=\"hljs-string\">'name'<\/span> =&gt; <span class=\"hljs-string\">'required'<\/span>,\n        <span class=\"hljs-string\">'author'<\/span> =&gt; <span class=\"hljs-string\">'required'<\/span>,\n    ]);\n    $cover = $request-&gt;file(<span class=\"hljs-string\">'bookcover'<\/span>);\n    $extension = $cover-&gt;getClientOriginalExtension();\n    Storage::disk(<span class=\"hljs-string\">'public'<\/span>)-&gt;put($cover-&gt;getFilename().<span class=\"hljs-string\">'.'<\/span>.$extension,  File::get($cover));\n\n    $book = <span class=\"hljs-keyword\">new<\/span> Book();\n    $book-&gt;name = $request-&gt;name;\n    $book-&gt;author = $request-&gt;author;\n    $book-&gt;mime = $cover-&gt;getClientMimeType();\n    $book-&gt;original_filename = $cover-&gt;getClientOriginalName();\n    $book-&gt;filename = $cover-&gt;getFilename().<span class=\"hljs-string\">'.'<\/span>.$extension;\n    $book-&gt;save();\n\n    <span class=\"hljs-keyword\">return<\/span> redirect()-&gt;route(<span class=\"hljs-string\">'books.index'<\/span>)\n        -&gt;with(<span class=\"hljs-string\">'success'<\/span>,<span class=\"hljs-string\">'Book added successfully...'<\/span>);\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">PHP<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">php<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Since Storage  facade&nbsp;renames the Files, We are storing new Filename, original filename and the mime type in the database for future usage.<\/p>\n\n\n\n<p>Now test your Application weather the image is uploading or not . You can find your images in your local folder to just go to root folder of you application then <strong>storage\/public\/app\/<\/strong>  your folder name. If The images are available in your local folder then you are going in the right direction .<\/p>\n\n\n\n<p><strong># Retrieve Images in Laravel<\/strong><\/p>\n\n\n\n<p>The final stem is to Retrieve Image from the storage folder. Go to your blade.php file where you want to show you image.<\/p>\n\n\n\n<script src=\"https:\/\/gist.github.com\/pradeeprjth\/52256cdd922c4bac6e19b3edc6dd3a56.js\"><\/script>\n\n\n\n<p>A url() function automatically generates URL for the public directory. Since We store book covers within <strong><em>\/public\/upload<\/em><\/strong>, we have mentioned the same path in image tag&#8217;s src attribute.<\/p>\n\n\n\n<p><strong>#Final Testing<\/strong><\/p>\n\n\n\n<p>Lets us now test our application. Run the application in the browser and insert an image. Then check your blade view weather the image is showing or not .<\/p>\n\n\n\n<p><strong># Chances of expected errors   <\/strong><\/p>\n\n\n\n<p>There is a broken image thumbnail instead of you image <\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"210\" height=\"230\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2020\/01\/stsmall215x235-pad210x230f8f8f8.jpg\" alt=\"\" class=\"wp-image-9532\"\/><\/figure>\n\n\n\n<p><strong># Solution<\/strong><\/p>\n\n\n\n<p> Try checking your pages source. check weather your image url is correct or not. Give full path <strong>src=&#8221;{{url(&#8216;storage\/app\/public\/uploads\/&#8217;.$book->filename)}}<\/strong><br><br>Or you can try <br><code><strong>Storage::url(\"\/storage\/app\/{$images->filename}\")<\/strong><\/code><\/p>\n\n\n<div class=\"epyt-gallery\" data-currpage=\"1\" id=\"epyt_gallery_77877\"><figure class=\"wp-block-embed wp-block-embed-youtube is-type-video is-provider-youtube epyt-figure\"><div class=\"wp-block-embed__wrapper\"><iframe loading=\"lazy\"  id=\"_ytid_33841\"  width=\"760\" height=\"427\"  data-origwidth=\"760\" data-origheight=\"427\" src=\"https:\/\/www.youtube.com\/embed\/?enablejsapi=1&#038;autoplay=0&#038;cc_load_policy=0&#038;cc_lang_pref=&#038;iv_load_policy=1&#038;loop=0&#038;rel=1&#038;fs=1&#038;playsinline=0&#038;autohide=2&#038;theme=dark&#038;color=red&#038;controls=1&#038;disablekb=0&#038;\" class=\"__youtube_prefs__  no-lazyload\" title=\"YouTube player\"  data-epytgalleryid=\"epyt_gallery_77877\"  allow=\"fullscreen; accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen data-no-lazy=\"1\" data-skipgform_ajax_framebjll=\"\"><\/iframe><\/div><\/figure><div class=\"epyt-gallery-list\"><div>Sorry, there was a YouTube error.<\/div><\/div><\/div>\n\n\n<p><\/p>\n\n\n\n<p><br><\/p>\n","protected":false},"excerpt":{"rendered":"<p># Creating Migration For Uploading Image We need to add three lines in our migration file which makes column in our Database .After adding, run Migration . # Blade Form Now we need to make a form for uploading Image into Database. Let us add new user&nbsp;input of file type&nbsp;in the&nbsp;insert.blade.php. Also, for file uploading,&#8230;<\/p>\n","protected":false},"author":14,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_kad_post_classname":"","_joinchat":[],"footnotes":""},"categories":[5201,5150],"tags":[5831,5834,5832,5091,5203,5833],"class_list":["post-9527","post","type-post","status-publish","format-standard","hentry","category-laravel","category-php","tag-broken_image","tag-fatch_from_database","tag-file_upload","tag-image","tag-laravel","tag-retrieve"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/9527","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=9527"}],"version-history":[{"count":4,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/9527\/revisions"}],"predecessor-version":[{"id":24998,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/9527\/revisions\/24998"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=9527"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=9527"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=9527"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}