Trouble printing out image from public folder laravel

风格不统一 提交于 2019-12-25 11:54:40

问题


I want to show the image that I had just uploaded and only show it to those who have uploaded it. For example, user table contain jack, Emily and John, so if jack were to upload a file the image will show directly under him, but I don't know how to do it?

This is how it look like now:

Controller: (how I store the image)

public function store1(Request $request){

   $this->validate($request, [
        'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

   if ($request->hasFile('file')) {
        $image = $request->file('file');
        $name = $image->getClientOriginalName();
        $size = $image->getClientSize();
        $destinationPath = public_path('/images');
        $image->move($destinationPath, $name);

        $userImage = new UserImage;
        $userImage->name = $name;
        $userImage->size = $size;
        //dd($userImage);
        $userImage->save();
}

view.blade.php

 @foreach ($data as $object)
    <b>Name: </b>{{ $object->name }}<br><br>
@endforeach

I saw people using this inside their blade.php, but I don't know what the $model is:

    <img src="{{ asset('public/images/' . $model->image) }}"> 

Upload.blade.php (this is my upload page where user will upload their image)

                        {{  csrf_field()  }}


<div class="form-group">
    <label for="imageInput" class="control-label col-sm-3">Upload Image</label>
            <div class="col-sm-9">
                <input type="file" name="file">

        </div>
    </div>

 <div class="form-group">
            <div class="col-md-6-offset-2">
              <input type="submit" class="btn btn-primary" value="Save">
            </div>
          </div>
          </form>


回答1:


There are many ways to do it.

You could either use Eloquent or using query builder of Laravel.

In your controller you should get all the images that the user uploaded.

Query builder approach :

//don't forget the namespace
`use DB;`

//in your function write this.
$images = DB::table('user_images')
        ->join('users', 'users.id', '=', 'user_images.user_id')
        ->where('users.id', '=', $id) 
        ->get();

//use dd($images) to verify that the variable $images has data

//send $images in your view

in your view write a foreach loop like so:

@foreach($images as $image)
    <img src="{{ asset('public/images/' . $image->name ) }}"> 
@endforeach


来源:https://stackoverflow.com/questions/46922713/trouble-printing-out-image-from-public-folder-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!