How to upload image in laravel 5.2 - php

This is my form
#extends('layout.template')
#section('content')
<h1>Add Student</h1>
{!! Form::open(array('action' => 'studentController#save', 'files'=>true)) !!}
<div class="form-group">
{!! Form::label('Profile-Picture', 'Profile Picture:') !!}
{!! Form::file('image',null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Save', ['class' => 'btn btn-primary form-control']) !!}
</div>
{!! Form::close() !!}
#stop
This is my controller method
public function save()
{
$students=Request::all();
students::create($students);
Session::flash('flash_message', 'Record successfully added!');
return redirect('students');
}
when i upload image and submit image than in the database column field save this image address "/tmp/phpFFuMwC";

That' s because you are saving the temporarily generated file url.
For files you need to manually save it to the desired location
( make sure it passes validations ):
$request->file('photo')->move($destinationPath);
// With a custom filename
$request->file('photo')->move($destinationPath, $fileName);
and then store the new filename ( with or without the path ) in the database something like this:
$students = new Students;
$students->image = $fileName;
...
$students->save();
Docs: https://laravel.com/docs/5.2/requests#files

On your controlller make these changes
public function save(Request $request)
{
$destination = 'uploads/photos/'; // your upload folder
$image = $request->file('image');
$filename = $image->getClientOriginalName(); // get the filename
$image->move($destination, $filename); // move file to destination
// create a record
Student::create([
'image' => $destination . $filename
]);
return back()->withSuccess('Success.');
}
Don't forget to use
use Illuminate\Http\Request;

Related

Upload videos in Laravel project

I am having trouble when I try to upload video/movie to my site. It doesn't save the video in the database, but it makes a folder 'movie' in my files with that video in it like it's supposed to. Also I edited my php.ini file for size requirements and session that I made says that it uploaded. Here is my code
View:
<div class="col-md-6">
{!! Form::open(['method'=>'POST', 'action'=> 'MovieController#store', 'files' => true]) !!}
<div class="form-group">
{!! Form::label('movie_name', 'Enter Movie Name:') !!} <br>
{!! Form::text('movie_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('uploaded_path', 'Select Movie:') !!} <br>
{!! Form::file('uploaded_path', null, ['class'=>'form-control'])!!}
</div>
</div>
<div class="form-group">
{!! Form::label('actor_id', 'Actors:') !!}
{!! Form::select('actor_id[]', $actors, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id[]', $categories, null, ['class'=>'form-control js-example-basic-multiple', 'multiple' => 'multiple']) !!}
</div>
MovieRequest:
public function rules()
{
return [
'movie_name' => 'required|max:255',
'uploaded_path' => 'mimetypes:video/avi,video/mpeg,video/mp4|required'
];
}
Controller:
public function store(MovieRequest $request)
{
DB::beginTransaction();
try {
if ($request->hasFile('uploaded_path')) {
$filenameWithExt = $request->file('uploaded_path')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $request->file('uploaded_path')->getClientOriginalExtension();
$fileNameToStore = $filename. '_'.time().'.'.$extension;
$path = $request->file('uploaded_path')->storeAs('public/movies/', $fileNameToStore);
} else {
$fileNameToStore = 'novideo.mp4';
}
$movie = new Movie;
$movie->movie_name = $request->input('movie_name');
$movie->uploaded_path = $fileNameToStore;
$movie->actors()->attach($request->input('actor_id'));
$movie->categories()->attach($request->input('category_id'));
$movie->save();
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
}
Session::flash('success', 'A movie was successfully UPLOADED in the database!');
return redirect()->route('movies.index');
}
Don’t forget to add:
enctype="multipart/form-data"
to movie field.

Preloading image in edit form

I have edit form which is populated from database when I go to update page. Everything works fine except the image part. If I don't submit new image it deletes old one too.
This is my controller
public function update( ItemRequest $request){
$item = Item::find( $request['id'] );
$filename=null;
$image = $request->file('image');
if($request->hasFile('image'))
{
if($image->isValid()){
$extension = $image->getClientOriginalExtension();
$uploadPath = public_path(). '/uploads';
$filename = rand(111,999). '.'. $extension;
$image->move($uploadPath, $filename);
}
}
$item->title = $request['title'];
$item->category_id = $request['category_id'];
$item->price = $request['price'];
$item->description = $request['description'];
$item->image = $filename? $filename: $item->image;
$item->image = $filename;
if($item->save()){
if(!is_null($filename)){
$item_image = new Item_Images;
$item_image->image = $filename;
$item_image->item_id = $item->id;
$item_image->published = 1;
$item_image->save();
}
$request->session()->flash('alert-success','Item updated successfully.');
} else
$request->session()->flash('alert-error','Can not update item now. Plese tyr again!!.');
return redirect()->route('products');
}
And the corresponded fields for image on the form
#if( $item['image'] )
<div class="form-group">
{!! Form::label('inputImage', 'Existing Image', array('class'=> 'col-sm-2 control-label')) !!}
<div class="col-sm-10">
<img src="{!!asset('/uploads/'. $item['image'] )!!}" />
</div>
</div>
#endif
<div class="form-group">
{!! Form::label('inputImage', 'Image', array('class'=> 'col-sm-2 control-label')) !!}
<div class="col-sm-10">
{!! Form::file('image', ['class'=>'form-control', 'id'=>'inputImage']) !!}
</div>
</div>
First I check if there is image in database and if there is it is shown on the page. There there is the file field.
So is it possible to load as a value the current image in file field of form? Or this must be done in controller logic somehow?
Remove this line to fix the problem:
$item->image = $filename;
By doing this, you'll set image as null if no image was uploaded.

How to save uploaded file name in table using Laravel 5.1

I need help in saving uploaded file name in database table using laravel 5.1.
My Controller code for saving Image details
public function store(Request $request)
{
if($request->hasFile('img_filename'))
{
$destinationPath="offerimages";
$file = $request->file('img_filename');
$filename=$file->getClientOriginalName();
$request->file('img_filename')->move($destinationPath,$filename);
}
$input=$request->all();
Offer_image::create($input);
return redirect('offerimage');
}
My view code for accepting image
{!! Form::open(array('route'=>'offerimage.store','role'=>'form','files'=>true)) !!}
<div class="box-body">
<div class="form-group">
{!! Form::label('img_name','Name') !!}
{!! Form::text('img_name', $value = null, $attributes = array('class'=>'form-control','id'=>'img_name','required')) !!}
</div>
<div class="form-group">
{!! Form::label('img_description','Description') !!}
{!! Form::textarea('img_description', $value = null, $attributes = array('class'=>'form-control','id'=>'img_description','required')) !!}
</div>
<div class="form-group">
{!! Form::label('img_filename','Upload Image') !!}
{!! Form::file('img_filename') !!}
</div>
{!! Form::hidden('status',$value='active') !!}
</div><!-- /.box-body -->
<div class="box-footer">
{!! Form::submit('Submit',$attributes=array('class'=>'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
This controller code to store image working properly, but where i am trying to save image file name to table , this code is storing filepath to database table.
As I am using direct create() method to store the request object in table, I don't know how do I store file name instead of path.
Check this Image for table data
The Problem is that your Request Data hasn't changed while you uploaded the picture. So img_filename still contains tmpdata.
You can try this:
$input = $request->all();
$input['img_filename'] = $filename;
Code that works for me :
$updir = 'images/';
$img_name = 'image.jpeg';
Request::file('img_filename')->move($updir, $img_name);
$file = $request->file('img_filename');
$filename=$file->hashName();
Above is the hash name Laravel uses to save your files

Laravel File Uploads: Accessing the file from server

I have successfully uploaded the image files to the server using Laravel 5.0. Here is my form:
<html>
<head>
<title>Uploads</title>
</head>
<body>
{!! Form::open(array('url' => 'uploadProcessing' , 'enctype' => 'multipart/form-data')) !!}
{!! Form::label('image','Upload Image') !!}
{!! Form::file('image') !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
</body>
</html>
Here is my Controller:
public function uploadProcessing() {
$image = Input::file('image');
$imageName = rand(1111, 9999) . '.' . Input::file('image')->getClientOriginalExtension();
Input::file('image')->move(base_path() . '/public/uploads/', $imageName);
}
Along with that, I am saving the $imageName as a refrence in database table.
Now I have to display that image in a view with that reference. I am trying to access it in this way:
#foreach($result as $r)
{!! HTML::image('uploads/$r->reference') !!}
#endforeach
But it is not working, any help?
I got it, It was simple, I tried this:
<img src="..\uploads\{!! $r->reference !!}" />
And it worked

Laravel 4: moving files once uploaded

Im having problems trying to upload photos and any kind of file on my app, because the do upload but as .tmp files and they dont display properly on my view
1.-My form,Im trying to upload a member with name, group, email, description and a photo
{{Form::open(array('action' => 'AdminController#addMember','files'=>true)) }}
{{ Form::label('file','Agregar Imagen',array('id'=>'','class'=>'')) }}
{{ Form::file('file','',array('id'=>'','class'=>'')) }}
<br/>
{{Form::text('name','',array('class' => 'form-control','placeholder'=> 'Nombre'))}}
{{Form::text('group','',array('class' => 'form-control','placeholder'=> 'Cargo'))}}
{{Form::text('email','',array('class' => 'form-control','placeholder'=> 'Correo'))}}
{{Form::textarea('description','',array('class' => 'form-control','placeholder'=>''))}}
<!-- submit buttons -->
{{ Form::submit('Guardar') }}
<!-- reset buttons -->
{{ Form::reset('Reset') }}
{{ Form::close() }}
2.-My upload function in the controller
public function addMember()
{
$name = Input::file('file')->getClientOriginalName();
$newname = Input::file('file')->getFilename();
Input::file('file')->move(storage_path(),$name);
$subpath = storage_path();
$path = $subpath.'/'.$newname2;
$name2 = Input::get('name');
$email = Input::get('email');
$description = Input::get('description');
$group = Input::get('group');
DB::table('contactgroups')->insert(
array('group' => $group, 'name' => $name2, 'path' => $path, 'email' => $email, 'description' => $description)
);
$members = DB::table('contactgroups')->get();
return View::make('admin.members',['members' => $members]);
}
I know i should be using a Model to upload things on my database but that's not the problem right now
3.- My display view
#extends('layouts.main')
#section('content')
#foreach($members as $member)
<div class = "row fondue">
<h3><div class="col-md-12"><b><?=$member->name ?></b></div></h3>
<div class="col-md-4"> <img src="<?=$member->path ?>" alt="Image" class = "contact-img"></div>
<div class="col-md-4"><?=$member->description ?></div>
<div class="col-md-4"><?=$member->email ?></div>
</div>
#endforeach
#stop
and that's all...the info is saved in the database but the images are not showing properly on the view and, the files are uploaded as tmp files i dont know why
From the Laravel documentation
Moving An Uploaded File
Input::file('photo')->move($destinationPath);
Input::file('photo')->move($destinationPath, $fileName);
Source: http://laravel.com/docs/4.2/requests#files

Categories