show image file in browser after uploading in laravel database

5.3k views Asked by At

I have a create form with some field like;name, price,category,... and a input field for image file.

it's my create.blade.php :

@extends('layouts.app')
@section('content')
    <div class="container">

        <div class="card mt-5">
            <div class="card-body">
                <div class="card-title">
                    create product
                </div>
            </div>
        </div>
        <form method="post" action="{{route('books.store')}}" enctype="multipart/form-data">
            {{csrf_field()}}
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text" class="form-control" name="name" id="name" aria-describedby="emailHelp" value="{{old('name')}}" placeholder="Enter name">

            </div>
            <div class="form-group">
                <label for="pages">pages</label>
                <input type="text" class="form-control" id="pages" name="pages" value="{{old('pages')}}" placeholder="pages">
            </div>



            <div class="form-group">
                <label for="ISBN">ISBN</label>
                <input type="text" class="form-control" id="ISBN" name="ISBN" value="{{old('ISBN')}}" placeholder="ISBN">
            </div>


            <div class="form-group">
                <label for="price">price</label>
                <input type="text" class="form-control" id="price" name="price" value="{{old('price')}}" placeholder="price">
            </div>

            <div class="form-group">
                <label for="published_at">published_at</label>
                <input type="date" class="form-control" id="published_at" name="published_at" value="{{old('published_at')}}" placeholder="published_at">
            </div>

            <div class="form-group">
                <label for="published_at">انتخاب تصویر</label>
                <input type="file" name="file" id="file">
            </div>

            <div class="form-group">
                <label for="category_id">CATEGORY ID</label>
                <select name="category_id[]" class="form-control" multiple>
                    @foreach($categories as $category)
                        <option value="{{$category->id}}">
                            {{$category->name}}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="form-group">
                <label for="author_id"> Author</label>
                <select name="author_id[]" class="form-control" multiple>
                    @foreach($authors as $author)
                        <option value="{{$author->id}}">
                            {{$author->name}}
                        </option>
                    @endforeach
                </select>
            </div>

            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <button type="submit" class="btn btn-success">Submit</button>
        </form>
    </div>

@endsection

and it's my Controller:

<?php

namespace App\Http\Controllers;

use App\author;
use App\book;
use App\category;
use App\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Storage;

class BookController extends Controller
{
    public $book;
    public $file;
    /**
    public function __construct()
    {
        $this->middleware('auth')->only('create');
    }
*/
    public function index()
    {
        $books = Book::with(['user'])->get();
        return view('books.index', compact('books'));

    }


    public function show($id)
    {
        $book = Book::with('categories','authors')->find($id);
        return view('books.show', compact('book'));
    }


    public function create()
    {
        $categories = Category::all();
        $authors = Author::all();
        $files= File::all();
        return view('books.create', compact('categories','authors','files'));
    }
    public function store(Request $request)
    {
        $this->validate($request,
            [
                'name'=>'required|string|max:256',
                'pages'=>'required|integer|numeric',
                'ISBN'=>'required|string|numeric',
                'price'=>'required|integer|numeric',
                'published_at'=>'required|date|date',
                'file'=>'required',

            ]
        );


        if ($request->hasFile('file')) {
            $filename = $request->file('file')->getClientOriginalName();
            $request->file->storeAs('public', $filename);
            $file = new File;
            $file->name = $filename;

            $file->save();

        }

        $book =  Auth::User()->books()->create($request->except('_token'));
        $book->categories()->attach($request->get('category_id'));
        $book->authors()->attach($request->get('author_id'));
        $book->files()->attach($request->get('book_id'));
        return redirect('/books');
    }

}


its web.php:

<!-- begin snippet: js hide: false console: true babel: false -->

and it's index.blade.php where we can see fields in browser:

@extends('layouts.app')
@section('content')


    <div class="container">
        <table class="table">
            <tr>
                <th>
                    Book Name
                </th>

                <th>
                    Creator
                </th>
            </tr>

            @foreach($books as $book)
                <tr>
                    <td><a href={{"/books/".$book->id}}>{{$book->name}}</a></td>
                    <td>{{$book->user->name}}</td>
                    @can('update',$book)
                        <td><a href="{{Route('books.edit',['id'=>$book->id])}}" class="btn btn-primary">edit</a></td>

                        <!-- Button trigger modal -->
                 <td>      <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal">
                           delete
                        </button>
                 </td>

                  
                    @else
                        <td>

                        </td>
                    @endcan

                    <td>

                    </td>

                </tr>

            @endforeach
        </table>

        <div class="mt-3"></div>
        <a href="{{'/books/create'}}" class="btn btn-success btn-block">Create</a>

    </div>


@endsection

all of my code run right but my question is that how can I do to display image file to browser? I mean ;how can use img tag in index.blade.php to that image displays in browser? (I didn't write all of my code because it would be too long and I just want a short code in img tag,something like this:

'<img  src="public/' . $file->getClientOriginalName() .'"  />';

but you know it dosen't work in blade.What can I do?

1

There are 1 answers

9
Bhavdip Pambhar On

You can get image path using assets() or url() functions of Laravel.

The asset() function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):

<img  src="{{ asset('img/photo.jpg') }}">

Example with asset()

The url() function generates a fully qualified URL to the given path:

<img  src="{{ url('img/photo.jpg') }}">

Example with url()

If your file directly located in public folder than your code should be,

<img  src="{{ asset( $file->getClientOriginalName() ) }}"  >

Your problem solution with asset()