ralphdns's avatar

cannot display image file to index page, using the edit/update method

when i pass data to my update method, every other input shows, except the image file...pls help me fix this... see the update PostsController


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Http\Requests\CreatePostRequest;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        $posts = Post::orderBy('created_at', 'desc')->paginate(12);
    
        return view('posts.index', compact('posts'));
        
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //renderd the URI(posts/create) for tis mtd
        return view('posts.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(CreatePostRequest $request)
    {
        //1. saving everytin frm the $request obj frm the form
        $input = $request->all();

        //2. storing the filename in the object, into $file variable, that is if the user actually choose a file
        if($file=$request->file('cover_image')){

            //3. storing the name of the file
            $filenameWithExt = $file->getClientOriginalName();

            //get just filename using php
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

             //get just extension
            $extension = $request->file('cover_image')->getClientOriginalExtension();

              //filename to store
            $fileNameToStore = $filename.'_'.time().'.'.$extension;

            //upload the image
            $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
            
           /*  //4. moving file frm xampp/tmp to image folder, whc wil b found under public
            $file->move('image', $fileNameToStore); */

            //5. equal the path column in db, to equal the filename
            $input['cover_image'] = $fileNameToStore;
        } else {
            $fileNameToStore = 'noimage.jpg';//if no image is deliberately selectd, use this deafault image
        }

        //now create evrytin to the db
        Post::create($input);
        return redirect('/posts');
        
        
        /* //files
        //the $request object a mtd called file, so it takes the name of the form 'file' frm the create view
        $file = $request->file('file');

        echo '<br>';

        echo $file->getClientOriginalName();//image name

        echo '<br>';

        echo $file->getClientSize();//image size */


        /* $this->validate($request, [
            'title' => 'required',
            'content' => 'required'  
        ]); */

        //tis returns evrytin to the post.index pg
       // return $request->all();

       //to get a specific inputs
        //return $request->get('title'); //or $request->title;

        //PERSISTING data to db, u can use any of the following groups
        //1. storing all the inputs into the create mtd. note dat this mtd requires u do put fillables in ur Post Model
       /*  Post::create($request->all());
        return redirect('/posts'); */

        //2. storing all inputs into a variable called input. tis useful whn files are invloved to be received
       /*  $input = $request->all();
        $input['title'] = $request->title;
        $input['content'] = $request->content;
        Post::create($request->all());   */
      
        //3. instantiating the class u want to create
        /* $post = new Post;
        $post->title =  $request->title;
        $post->content =  $request->content;
        $post->save(); */

        //at last we get redirected to the posts pg
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
        $post = Post::findOrFail($id);
        return view('posts.show', compact('post'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $post = Post::findOrFail($id);
        return view('posts.edit', compact('post'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        //1. saving everytin frm the $request obj frm the form
        $input = $request->all();

        //2. storing the filename in the object, into $file variable, that is if the user actually choose a file
        if($file=$request->file('cover_image')){

            //3. storing the name of the file
            $filenameWithExt = $file->getClientOriginalName();

            //get just filename using php
            $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);

             //get just extension
            $extension = $request->file('cover_image')->getClientOriginalExtension();

              //filename to store
            $fileNameToStore = $filename.'_'.time().'.'.$extension;

            //upload the image
            $path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
            
           /*  //4. moving file frm xampp/tmp to image folder, whc wil b found under public
            $file->move('image', $fileNameToStore); */

            //5. equal the path column in db, to equal the filename
           /*  $input['cover_image'] = $fileNameToStore; */

            
        } /* else {
            $fileNameToStore = 'noimage.jpg';//if no image is deliberately selectd, use this deafault image
        } */

        //find the post->id sent frm the edit form
        $post = Post::findOrFail($id);

        if($request->hasFile('cover_image')){
            $input['cover_image'] = $fileNameToStore;
        }

        //update the object, by passing all values into it
        $post->update($input);
    
        return redirect('/posts');

        
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
        //find the post->id sent frm the edit form
        $post = Post::findOrFail($id);

        
        if($post->cover_image !== 'noimage.jpg'){
            //Delete Image
            Storage::delete('public/cover_images/'.$post->cover_image);
        }

        //delete the object, with a particular id
        $post->delete($id);
        return redirect('/posts');
    }
}

see my index view:


@section('content')
    <h1>All Posts Page</h1>
    <ul>
        @foreach($posts as $post)
            <li class="list-group-item">
                <div class="img-style">
                    <img class="img-responsive" width="30%" src="/storage/cover_images/{{$post->cover_image}}" alt="">
                </div>
                <a href="{{route('posts.show', $post->id)}}">{{$post->title}}</a> <br>
                    {{$post->content}}
            </li><br><br>
        @endforeach
    </ul>
@endsection ```

see my route:
```<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

/*
|--------------------------------------------------------------------------
| UGOBLOG ROUTES
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/* to activate the $error msg truout our appln */
Route::group(['middleware'=>'web'], function(){
    Route::resource('/posts', 'PostsController');
});

0 likes
8 replies
shez1983's avatar

what does every other input shows, except the image file mean? what happens when you do a dd($request->all());

if the file isnt showing then there could be a problem with image/ uploading file etc

ralphdns's avatar

it means my upload file is not working

newbie360's avatar

did you put <form ........ enctype="multipart/form-data"> ?

jlrdw's avatar

Did you make sure the image was properly stored.

ralphdns's avatar

@newbie360, yeah. in the form i did 'file'=true, is not same thing as enctype="multipart/form-data">

newbie360's avatar

when you view the html source code in browser, all correct ?

<img class="img-responsive" width="30%" src="/storage/cover_images/the_image_name.jpg" alt="">

also type the url of the image in browser, see the image ? or you forgot make the symlink ?

Snapey's avatar

Does the execution pass through the file save lines?

Anything stored in the database for the image name?

You created a symlink to storage/public?

Does the file exist at the path you expected? A file was created in the storage public folder?

Does the file exist at the URL you expected?

Take it step by step through the controller and check your results at each step.

Please or to participate in this conversation.