Save Url of image to database and get image - php

Hi I am New to Laravel I have done Upload a Image to path
img/banner/{{image upload here}}
My doubt is here is to save the image path in database with which
user uploaded
And while retrieving data how to give my URL path here.
I have created a database name uploads
id user_id group_id filename extension filesize location created_at updated_at
Blade File
<div class="panel panel-primary">
<div class="panel-heading"><h2>Slide Image Upload</h2></div>
<div class="panel-body">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/img/banner/{{ Session::get('image') }}">
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{ route('image.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="image" class="form-control">
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
Controller:
public function imageUploadPost()
{
request()->validate([
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.request()->image->getClientOriginalExtension();
request()->image->move(public_path('img/banner'), $imageName);
return back()
->with('success','You have successfully upload image.')
->with('image',$imageName);
}
Routes:
Route::post('/imageupload', 'Admin\ImageController#imageUploadPost')->name('image.upload.post');
Any Help will be appreciated.

I am expecting that you have included namespace, if not
use DB;
$full_path = public_path('img/banner');
$ext = request()->image->getClientOriginalExtension();
$size = request()->image->getSize();
DB::table('uploads')->insert(
['group_id' => '1', user_id' => '1', 'filename' => $imageName,'filesize'=>$size ,'extension'=> $ext,'location' => $full_path,'created_at'=> date('Y-m-d H:m:s')]
);
You can get by this your database values, $imagename is the name you used to upload the image, not sure about your group_id so set to 1.
latest Edit
this is how you can get imageName:
$imageName = time().'.'.request()->image->getClientOriginalExtension();
froom your code only

Related

Laravel 7: User Profile causing bug when uploading img and bio description

In a laravel 7 app I'm working on a feature where a user can upload their image profile and bio description. A problem that I'm facing is that there are certain cases when a user sets their profile image, the bio description would be gone. For example: If a user set their profile img and puts a description, but if the user sets another img then the description would be gone. Not quite sure what's the bugs that's causing it. (I'm using bootstrap modal for the user to edit their profile.)
controller.php
public function modalEditPost(Request $request)
{
$user = Auth::user();
$avatarName = "";
$userBio = "";
$request->validate([
'bio' => 'nullable|string|max:255',
'image' => 'mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->has('bio')) {
$userBio = $request->bio;
$user->bio = $userBio;
}
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$extension = $request->image->extension();
$avatarName = $user->id.'_avatar'.time().'.'.$extension;
$request->image->move(public_path('/uploads/avatars'), $avatarName);
$user->avatar = $avatarName;
}
}
$user->save();
return back()
->with('success','You have successfully edited your bio.')
->with('bio', $userBio)
->with('image', $avatarName);
}
index.blade.php
#include('partials.popup')
<div class="col-md-4">
<div class="card card-user">
<div class="card-body">
<p class="card-text">
<div class="author">
<div class="block block-one"></div>
<div class="block block-two"></div>
<div class="block block-three"></div>
<div class="block block-four"></div>
<img class = "avatar" src="/uploads/avatars/{{ Auth::user()->avatar}}" alt="">
<h4 class="title">{{ auth()->user()->first_name }} {{ auth()->user()->last_name }}</h5>
</div>
<div class="card-description">
{{ Auth::user()->bio }}
</div>
<br>
<div class="text-center">
<button class="btn btn-success"
style="cursor: pointer"
data-toggle="modal"
data-target="#popupModal">{{ __('Edit Profile') }}
</button>
</div>
</div>
</div>
popup.blade.php
<div class="modal-body">
<!-- (Image upload) Start -->
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- (Image upload) Start -->
<form action="{{ route('modal.upload.post') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-6">
<input type="file" name="image" class="form-control-file">
</div>
</div>
<br>
<div class="row">
<div class="col">
<p>Change Bio</p>
</div>
</div>
<div class="row">
<div class="col">
<input type="text" style="color:black" name="bio" class="form-control">
</div>
</div>
<br>
<div class="col-md-6">
<button type="submit" class="btn btn-success">Update</button>
</div>
</form>
<!-- (Image upload) End -->
</div>

Laravel : Update form keeping current image without input a new image isn't working

I have a form with image field, inserting all the field with image works fine
but when editing the form->to update a new image I used unlink function to remove the previous image and update with new one. The problem is if I don't upload a new image and submit the form it isn't working.
But I want to keep the current image remain if new image is not uploaded. I have tried many ways even not using unlink function but couldn't reach any solution. please help me, I really need this solution. Thanks in advance
here is my update function in controller
public function Update(Request $request, $id){
$PreviousPic = $request->Prev_pic;
$data = array();
$data['student_name'] = $request->student_name;
$data['matric_no'] = $request->matric_no;
$data['programme_name'] = $request->programme_name;
$data['faculty_name'] = $request->faculty_name;
$data['admission_year'] = $request->admission_year;
$data['contact_no'] = $request->contact_no;
$image = $request->file('pro_pic');
if ($image){
unlink($PreviousPic);
$image_name = date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$imageFullName = $image_name.'.'.$ext;
$uploadPath = 'media/';
$imageURL = $uploadPath.$imageFullName;
$success = $image->move($uploadPath,$imageFullName);
$data['pro_pic'] = $imageURL;
$Stdata = DB::table('students')->where('id', $id)->update($data);
return redirect()->route('student.index')
->with('success','Updated! The Student Data Updated Successfully');
}
}
here is my edit form image field
<div class="form-group">
<label class="col-md-4 control-label" >Image</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-picture"></i></span>
<div class="upload-btn-wrapper">
<button class="btn">Upload a New Image</button>
<input type="file" name="pro_pic" />
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Current Image </label>
<div class="col-md-5 inputGroupContainer">
<img src="{{ URL::to($StudentData->pro_pic)}}" height="150px" width="190px">
<input type="hidden" name="Prev_pic" value="{{$StudentData->pro_pic}}">
</div>
</div>
Using this I can upload new image removing the old picture. But If I keep the Upload a New Image field empty and submit the form, the form isn't submitted.
So, I want if I upload new image it works as now and if I don't upload a new image, the current image will remain & submit the form.
# I am using Laravel 7
I have found the answer as expected
public function Update(Request $request, $id){
$PreviousPic = $request->Prev_pic;
$data = array();
$data['student_name'] = $request->student_name;
$data['matric_no'] = $request->matric_no;
$data['programme_name'] = $request->programme_name;
$data['faculty_name'] = $request->faculty_name;
$data['admission_year'] = $request->admission_year;
$data['contact_no'] = $request->contact_no;
$image = $request->file('pro_pic');
if ($image != null){
unlink($PreviousPic);
$image_name = date('dmy_H_s_i');
$ext = strtolower($image->getClientOriginalExtension());
$imageFullName = $image_name.'.'.$ext;
$uploadPath = 'media/';
$imageURL = $uploadPath.$imageFullName;
$success = $image->move($uploadPath,$imageFullName);
$data['pro_pic'] = $imageURL;
$Stdata = DB::table('students')->where('id', $id)->update($data);
return redirect()->route('student.index')
->with('success','Updated! The Student Data Updated Successfully');
}else{
$Stdata = DB::table('students')->where('id', $id)->update($data);
return redirect()->route('student.index')
->with('success','Updated! The Student Data Updated Successfully');
}
}
Just use if else statement to find the solution and it's working great.
You need to pass the exact path of the old image from database.
You can try it with concatenation,
By making two separate columns for image_name and image_path
This is my edit image code
<div id="image" class="row" style="display: none;">
<div class="col-md-12">
<label for="text">Project Image</label>
<div class="form-group">
<input type="file" class="form-control" name="project_image"
value="{{ old('project_image',$currentProject->project_image) }}">
#if ($errors->has('project_image'))
<div class="text-danger">{{ $errors->first('project_image') }}</div>
#endif
</div>
</div>
</div>
This is the div to view the previous and new image
<div class="box box-primary">
<div class="box-body">
<div class="box-header text-center">
<h3 class="box-title">Project Cover Image</h3>
</div>
<div class="row">
<div class="col-md-12 text-center">
<img class="img-responsive" src="{{ URL::asset($currentProject->project_cover_image_path.'/'.$currentProject->project_cover_image_name)}}" alt="Photo">
<br>
<a class="btn btn-primary" data-toggle="modal" data-target="#modal-project-cover">
Change Cover Image
</a>
</div>
</div>
</div>
</div>
This is the modal that actually edits the image
{{-- Modal dialogue to edit Project Cover Image --}}
<div class="modal fade" id="modal-project-cover">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header text-center">
<form method="POST" action="{{url('updateprojectcover', $currentProject->project_id)}}" enctype="multipart/form-data">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
#if (session('error'))
<div class="alert alert-danger">{{ session('error') }}</div>
#endif
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×
</span>
</button>
<div class="row">
<div class="col-md-12">
<h4 for="text">Project Cover Image</h4>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group text-center">
<input type="file" class="form-control" name="project_cover_image">
#if ($errors->has('project_cover_image'))
<div class="text-danger">{{ $errors->first('project_cover_image') }}
</div>
#endif
</div>
</div>
</div>
<div class="modal-footer text-center">
<button type="submit" class="btn btn-primary text-center">Yes</button>
</div>
</form>
</div>
</div>
</div>
</div>
This is my controller to edit image
try
{
$cover_name = $request->file('project_cover_image');
if (isset($cover_name))
{
$project_cover_image_name = $cover_name->getClientOriginalName();
$project_cover_image_name = str_replace(" ", "_", time() . $project_cover_image_name);
$cover_name->move(ImageUrlController::$project_cover_image_path, $project_cover_image_name);
}
Project::where('project_id', $project_id)
->update([
'project_cover_image_path' => ImageUrlController::$project_cover_image_path,
'project_cover_image_name' => $project_cover_image_name,
'updated_at' => Carbon::now('PKT'),
]);
return redirect()->back()->withInput();
}
catch (\Exception $exception)
{
return back()->withError($exception->getMessage())->withInput();
}

Image is not shwing in the user profile in Laravel

I am having a little problem here. I am trying to put an image in my User Profile. The image is saved in the database and no errors are shown up, but I never see the default image that I gave to it. It says that it's there but The place for the pic stays empty.
This is what I've got for now:
UserController.php
<?php
namespace app\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
// namespace App\Http\Controllers\Controller;
// use App\Http\Requests\Request;
// use Illuminate\Http\Request;
class UserController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile',compact('user',$user));
}
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user = Auth::user();
$avatarName = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
/** Return view to upload file */
public function uploadFile(){
return view('uploadfile');
}
/** Example of File Upload */
public function uploadFilePost(Request $request){
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
$request->fileToUpload->store('logos');
return back()
->with('success','You have successfully upload image.');
}
}
profile.blade.pbp
<hidden='Illuminate\Support\Facades\Auth'>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="row justify-content-center">
<div class="profile-header-container">
<div class="profile-header-img">
<img class="rounded-circle" width="150" height="150" src="/storage/avatars/{{ $user->avatar }}" />
<!-- badge -->
<div class="rank-label-container">
<span class="label label-default rank-label">{{$user->name}}</span>
</div>
</div>
</div>
</div>
<div class="row justify-content-center">
<form action="/profile" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="avatar" id="avatarFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'public'),
How can I make the default avatar visible?
Also, do you have any suggestions on how to put a watermark on the photos that will appear each time someone uploads photos?
Thanks in advance!
You can try this. First execute this command
php artisan storage:link
Then
<img class="rounded-circle" width="150" height="150" src="{{url('')}}/storage/avatars/{{ $user->avatar }}"/>

Method [vlidate] does not exist error in laravel 5.3 while trying to upload image

I am developing a project in laravel 5.3 where I have to create a 1 feild form to change logo of website my form look like this.
I do not need to save path in database. I just need to upload file in \public\images\ with name logo and only png files are allowed. so it will be \public\images\logo.png
following is the form code.
<div class="col-md-8 col-md-offset-2">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/images/{{ Session::get('path') }}">
#endif
<div class="box box-info">
<div class="box-header with-border text-center">
<h3 class="box-title">Basic Info</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form class="form-horizontal" action="{{ url('/') }}/admin/change-site-logo" enctype="multipart/form-data" method="POST">
<div class="box-body">
{{ csrf_field() }}
<div class="form-group">
<label for="logo" class="col-sm-3 control-label">Logo</label>
<div class="col-sm-9">
<input type="file" class="form-control" id="logo" name="logo" placeholder="Logo Image">
</div>
</div>
<div class="form-group">
<label for="logo" class="col-sm-3 control-label"></label>
<div class="col-sm-9">
<img style="width: 200px; height: 50px;" src="https://www.google.com.pk/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png">
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right">Save</button>
</div>
<!-- /.box-footer -->
</form>
</div>
<br /><br />
</div>
this is Route Route::post('/admin/change-site-logo', 'adminController#logo_change');
and controller is as following
class adminController extends Controller
{
public function logo_change(Request $request)
{
$this->vlidate($request, [
'logo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = 'logo.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
return back()
->with('success', 'Image Uploaded Successfully.')
->with('in path', $imageName);
}
I am writing first time this kind of code so dont know what to fix. I just know that the error is Method [vlidate] does not exist.

How do i save the file name/image through my database?

Im currently doing the file upload. I searched through the internet regarding the file upload. The website that I saw is only saving through the images folder, i tried to put the Administrator::create(['image' => $request->image]);
It saved to the database but its not the name of the image that i upload.. The name of the image after i-upload C:\xampp\tmp\php306A.tmp
My Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Administrator;
class ImageController extends Controller
{
/**
* Create view file
*
* #return void
*/
public function imageUpload()
{
return view('image-upload');
}
/**
* Manage Post Request
*
* #return void
*/
public function imageUploadPost(Request $request)
{
$file = $request->file('image');
$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);
// Administrator::create($request->all());
Administrator::create([
'image' => $request->image
]);
return back()
->with('success','Image Uploaded successfully.')
->with('path',$imageName);
}
}
?>
My View
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.3 Image Upload with Validation example</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="panel panel-primary">
<div class="panel-heading"><h2>Laravel 5.3 Image Upload with Validation example</h2></div>
<div class="panel-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<img src="/images/{{ Session::get('path') }}">
#endif
<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-md-12">
<input type="file" name="image" />
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Routes
Route::get('image-upload','ImageController#imageUpload');
Route::post('image-upload','ImageController#imageUploadPost');
My model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Administrator extends Model
{
protected $table = 'accounts';
protected $fillable = array(
'first_name',
'middle_name',
'last_name',
'email',
'image',
''
);
}
To get the uploaded image, you could change these lines:
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
to
$imageName = "";
if($request->hasFile('images')) {
$image = $request->file('images');
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $imageName);
}
And your create part:
Administrator::create([
'image' => $imageName
]);
view part
{!! Form::open(array('url'=>'insertfile','method'=>'POST' ,'class'=>'form-horizontal','files'=>true)) !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Upload:</label>
<div class="col-sm-4">
<input type="file" name="filenam" class="filename">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
{!! Form::close() !!}
controller
public function insertFile(){
$file= Input::file('filenam');
$rules = array('file' => 'required|max:10000|mimes:jpeg,png,jpg,gif,svg,csv,xls,xlsx,doc,docx,pdf');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'up_file';
$filename = $file->getClientOriginalName();
$data=array(
'file_name' => $filename,
);
var_dump($data);
yourmodelname::insert($data);
$upload_success = $file->move($destinationPath, $filename);
}
}
in route:
Route::get('/uploadfile','UploadController#getView');
Route::post('/insertfile','UploadController#insertFile');
file will be upload in yourproject/public/up_file directory

Categories