degeta10's avatar

How to upload image to my database?

I'm trying to upload an image to database. Below is my code. When i upload my image it is stored as blob. So what should i do next? And how can i display the image ?

public function store(Request $request)
{
   
    if(Auth::check()){
        if (Stock::where('tag_no','=',$request->input('tag_no'))->exists()) { 
            return back()->withInput()->with('errors', 'Tag number already used!');                
            }            

            $stock = Stock::create([
                'tag_no' => $request->input('tag_no'),                    
                'image' => $request->input('image'),                           
                'user_id' => Auth::user()->id
            ]);               

            if($stock){
                return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
                ->with('success' , 'Stock created successfully');
            }                
    }        
    return back()->withInput()->with('errors', 'Error creating new Stock');        
}
0 likes
3 replies
m7vm7v's avatar

You do not 'store the image in the database'. There are 2 steps - store the image on the disk - some folder & then save THE PATH to the image into the database.

Then its as simple as Stock::where('id', 1)->first()->image to get the image path and display it.

1 like
degeta10's avatar
degeta10
OP
Best Answer
Level 1

ohk i changed my code to this... And now i can store the image to public/images folder. How can i display now?

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

                $imageName = time().'.'.$request->image->getClientOriginalExtension();
                $request->image->move(public_path('images'), $imageName);               

                $stock = Stock::create([
                    'tag_no' => $request->input('tag_no'),                   
                    'image' => $imageName,              
                    'user_id' => Auth::user()->id
                ]);               

                if($stock){
                    return redirect()->route('stocks.index', ['stocks'=> $stock->tag_no])
                    ->with('success' , 'Stock created successfully');
                }                
        }        
        return back()->withInput()->with('errors', 'Error creating new Stock');        
    }
degeta10's avatar

Hey i figured it out.. Thanks for helping me :)

<div>
         <img src="/images/{{$stock->image}}" height="100" width="100"> 
</div>

Please or to participate in this conversation.