Here's my HTML:
<label for="attachement1">Attach a file: <small style="color:#999;">(type: zip/rar and below 10mb)</small></label>
<input type="file" name="file1"/><br/>
<label for="snapshot">Snapshot / Thumbnail:</label>
<input type="file" name="thumbnail" required/><br/>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-primary" name="Submit" value="Publish" />
Here is the code in my controller file (for the update function):
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'thumbnail' => 'mimes:jpg,jpeg,png|max:800',
'file1' => 'mimes:rar,zip|max:10000',
]);
$file1=$request->file('file1');
if(is_null($request->file('file1'))){
$p=pages::where('id', '=', $request['id'])->first();
$attmt1=$p->attachment;
}
else
{
$upload_dir='uploads';
$attmt1=$file1->getClientOriginalName();
$move=$file1->move($upload_dir, $attmt1);
}
if(is_null($request->file('thumbnail'))){
$p=pages::where('id', '=', $request['id'])->first();
$image=$p->thumbnail;
}
else
{
$img=$request->file('thumbnail');
$upload_dir='thumbnails';
$image=$img->getClientOriginalName();
$move=$img->move($upload_dir, $image);
//end thumbnail process
}
$mypage->title = $request->title;
$mypage->body = $request->body;
//$mypage->thumbnail = $request->thumbnail;
$mypage->slug = str_slug($request->slug, '-');
$mypage->menu_name = $request->menu_name;
$mypage->save();
return redirect()->route('menupages.index')->with('message', 'Page updated successfully.');
}
When I try to edit an item and upload an image (.jpg format), and click submit, I get a "The thumbnail must be a file of type: jpg, jpeg, png." I checked the database and the file was not recorded.
For some reason, it is detecting the image as some foreign image file type even though it is .jpg.
Are you Add enctype="multipart/form-data" on your form?
<form method="post" Action= "" enctype="multipart/form-data">
</form
When you want to upload something, you always need to add the following code to your form.
enctype="multipart/form-data"
If you don't do this, you can't upload something.
Did you add this to your html form?
I got help from a developer on this so I will post how we were able to solve the problem.
Here's the full revised code for the function:
Controller:
public function update(Request $request, $id)
{
$this->validate($request, [
'thumbnail' => 'mimes:jpg,jpeg,png|max:300000',
'file1' => 'mimes:rar,zip|max:10000',
]);
$file1 = $request->file('file1');
if(is_null($request->file('file1'))){
// $p=pages::where('id', '=', $request['id'])->first();
$p = MenuPage::find($request['id']);
$attmt1 = $p['attachment'];
}
else
{
$upload_dir = 'uploads';
$attmt1 = $file1->getClientOriginalName();
$file1->move($upload_dir, $attmt1);
}
if(is_null($request->file('thumbnail'))){
// $p=pages::where('id', '=', $request['id'])->first();
$p = MenuPage::findOrFail($request['id']);
$image = $p->thumbnail;
}
else
{
$img = $request->file('thumbnail');
$upload_dir = 'thumbnails';
$image = $img->getClientOriginalName();
$img->move($upload_dir, $image);
//end thumbnail process
}
//$check=pages::where('id', $request['id'])
//->update([
// 'title' => $title,
// 'body' =>$body,
// 'thumbnail' =>$thumbnail,
// 'slug' =>$slug,
// 'school' =>$school,
// 'attachment' =>$attmt1,
// 'menu_name' =>$menu_name,
// ]);
$mypage = MenuPage::find($id);
$mypage->title = $request->title;
$mypage->body = $request->body;
$mypage->thumbnail = $image;
$mypage->attachment = $attmt1;
$mypage->slug = str_slug($request->slug, '-');
$mypage->menu_name = $request->menu_name;
$mypage->save();
return redirect()->route('menupages.index')->with('message', 'Page updated successfully.');
}
View file (the bottom part):
<label for="attachement1">Attach a file: <small style="color:#999;">(type: zip/rar and below 10mb)</small></label>
<input type="file" name="file1"/><br/>
<label for="snapshot">Snapshot / Thumbnail:</label>
<input type="file" name="thumbnail" required/><br/>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="_method" type="hidden" value="PUT">
<input type="submit" class="btn btn-primary" name="Submit" value="Publish" />
Related
I have a model and when I am creating a new one I want to be able to store an image from controller, like this:
public function create($id)
{
//
$user = User::FindOrFail($id);
$photos = Photo::all();
return view('posts.create', ['user'=>$user, 'photos'=>$photos]);
}
public function store(Request $request, $id)
{
//
$validateData = $request->validate([
'title' => 'required|string',
'text' => 'nullable|max:255',
'image' => 'nullable|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
'user_id' => 'nullable|int',
]);
// return 'passed validation';
$size = $request->file('image')->getSize();
$name = $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('public/images/', $name);
$photo = new Photo();
$photo->name = $name;
$photo->size = $size;
$photo->save();
$a = new Post;
$a->title = $validateData['title'];
$a->text = $validateData['text'];
$a->image = $photo;
$a->user_id = $id;
$a->save();
session()->flash('message', 'Post was created');
return redirect()->route('posts.index', ['id'=>$id]);
}
While I try to also display all available images in create blade:
<form method="POST" action="{{route('posts.store', ['id'=>$user->id])}}">
#csrf
<p>Title: <input type="text" name="title" value="{{old('title')}}"></p>
<p>Text: <input type="text" name="text" value="{{old('text')}}"></p>
#csrf
<input type="file" name="image">
<input type="submit" name="Upload">
<ul>
#foreach ($photos as $photo)
<li>
<p>
{{ $photo->name }}
</p>
<img src="{{ asset('storage/images/'. $photo->name) }}">
</li>
#endforeach
</ul>
Cancel
When I try to submit I get the following errors:
The image must be an image.
The image must be a file of type: jpg, png, jpeg, gif, svg.
This error can't be true as I try to upload only jpg and png images, but I can't understand where I do something wrong.
Edit: Is there a way to store the image without declaring a new model?
I have a form like this:
<form action="{{ route('popups.store') }}" method="POST" enctype="multipart/form-data">
#csrf
<div id="dynamic_field">
<label>Date of showing</label>
<input type="text" id="date" name="datep" class="form-control datepicker" value="" autofocus>
<label for="title" class="control-label">Title</label>
<input type="text" id="title" name="title" class="form-control" value="" autofocus>
<label for="link" class="control-label">Link</label>
<input type="text" id="link" name="linkp[]" class="form-control" value="" autofocus>
<label for="bio" class="control-label">Text</label>
<textarea class="form-control" name="bio[]" rows="3"></textarea>
<label for="filep" class="control-label">Image</label>
<input type="file" class="form-control-file" id="filep" name="filep[]">
<button class="btn btn-success" type="submit">Submit</button>
<a id="add" class="btn btn-info" style="color:white">Add new form</a>
</div>
</form>
As you can see, I have added a link with id="add" for adding additional form fields dynamically with javascript.
So it means a user can add several images, texts and links. And that's why I used filep[], bio[] and linkp[], as the name of those form fields (in order to save them as an array).
Then at the Controller, I added this:
public function store(Request $request)
{
try{
$data = $request->validate([
'datep' => 'nullable',
'title' => 'nullable',
'linkp' => 'nullable',
'bio' => 'nullable',
'filep' => 'nullable',
]);
$newPop = Popup::create([
'datep' => $data['datep'],
'title' => $data['title']
]);
$files = $request->file('filep');
if($request->hasFile('filep'))
{
foreach ($files as $file) {
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
$request->filep->move(public_path('popups'), $newImageName);
Popup::where('id',$newPop->id)->update(['image_path'=>",".$newImageName]);
}
}
}catch (\Exception $e) {
dd($e);
}
return redirect()->back();
}
So for each image, I tried moving it into public/popups folder and then it should update the existing record of table with id of $newPop->id.
But it shows me this error:
Call to a member function extension() on array
Which is referring to this line:
$newImageName = time() . '-' . $request->name . '.' . $request->filep->extension();
So what's going wrong here? How can I upload multiple images with using array?
You can try this -
if($files=$request->file('filep')){
foreach ($files as $key=>$file) {
$extension = $file->getClientOriginalName();
$fileName = time().'-' .$request->name.'.'.$extension; // I don't know where did you get this $request->name, I didn't find it on your code.
$created = Popup::create([
'datep' => $request->datep[$key],
'title' => $request->title[$key],
'image_path' => $fileName
]);
if($created){
// $file->move('popups',$fileName); to store in public folder
// If you want to keep files in storage folder, you can use following : -
Storage::disk('public')->put('popups/'.$location,File::get($file));
// Dont't forget to run 'php artisan storage:link'
// It will store into your storage folder and you can access it by Storage::url('file_path)
}else{
// Your error message.
}
}
}
working with Laravel 5.6 and MySQL. I am going to update categoryname and image in my categories table using the following controller function?
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('categories.form', ['image' => Category::find($id)]);
else {
$rules = [
'categoryname' => 'required',
];
$this->validate($request, $rules);
$image = Category::find($id);
if ($request->hasFile('image')) {
$dir = 'images/';
if ($image->image != '' && File::exists($dir . $image->image))
File::delete($dir . $image->image);
$extension = strtolower($request->file('image')->getClientOriginalExtension());
$fileName = str_random() . '.' . $extension;
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
} elseif ($request->remove == 1 && File::exists('images/' . $image->image)) {
File::delete('images/' . $image->post_image);
$image->categoryimage = null;
}
}
$image->categoryname = $request->categoryname;
$image->save();
return redirect()->route('categories.index');
}
and route
Route::match(['get', 'put'], 'category/update/{id}', 'CategoryController#update');
and edit form
#if(isset($image))
<form method="PUT" action="http://localhost:8000/category/update/{{$image->id}}" enctype="multipart/form-data">
<input type="hidden" name="_method" value="put">
<label for="description" class="col-form-label col-md-3 col-lg-2">Description</label>
<div class="col-md-8">
<input class="form-control" autofocus placeholder="Description" name="categoryname" type="text" id="categoryname" value="{{ isset($image) ? $image->categoryname : '' }}">
<label for="image" class="col-form-label col-md-3">Image</label>
<div class="col-md-5">
<img id="preview"
src="{{asset((isset($image) && $image->categoryimage!='')?'images/'.$image->categoryimage:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="image" type="file" id="image" name="_token" value="{{ csrf_token() }}">
<br/>
Add Image |
<a style="color: red" href="javascript:removeImage()">Remove</a>
<input type="hidden" style="display: none" value="0" name="remove" id="remove">
but when I try to update data it is not updating. only refresh to the same page. no, any error
url look like this
http://localhost:8000/category/update/21?categoryname=tractorrer&image=&remove=0 //tractorrer is updated category name
how can fix this problem?
Theres a few things concerning about your code examples. Like only having 1 method called update for both GET and PUT routes. Probably not a good habit to get into. Especially since, if it is a get route, you're not updating anything. So already the method name / description of what it does, is wrong.
But that aside, you are not seeing anything because you cannot use method="PUT" on your form. You need to use method="POST" and then inside your form, you need these lines. One to tell the form that this is a patch request, and one to put the csrf token in.
{{csrf_field()}}
{{ method_field('PATCH') }}
and I would update your route to PATCH, not PUT.
First.
Have you dump all of the request like this to check whether it contains categoryname.
dd($request->all());
If the dd does not print categoryname value, then it seems to be the problem when you sending request.
Then.
Try using method="POST" instead of method="PUT" If you have not try yet.
I have never used PUT with form submit before
First,
You set POST instead of PUT of form method.
Second,
Your codes look a little messy. I updated your action codes;
public function update(Request $request, $id)
{
if ($request->isMethod('get')){
return view('categories.form', ['image' => Category::find($id)]);
} else{
$rules = [
'categoryname' => 'required',
];
$this->validate($request, $rules);
$image = Category::find($id);
if ($request->hasFile('image')) {
$dir = 'images/';
if ($image->image != '' && File::exists($dir . $image->image))
File::delete($dir . $image->image);
$extension = strtolower($request->file('image')->getClientOriginalExtension());
$fileName = str_random() . '.' . $extension;
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
} elseif ($request->remove == 1 && File::exists('images/' . $image->image))
{
File::delete('images/' . $image->post_image);
$image->categoryimage = null;
}
$image->categoryname = $request->categoryname;
$image->save();
return redirect()->route('categories.index');
}
}
Can you try again with my directives. I hope it helping your problem.
I can get photos to upload as a user,
but I need to be able to pick that photo I just uploaded and display it as an avatar?
the problem is all the photos from all the users go into the same public folder so not sure how to show only the photo that the user uploaded
I am using Laravel
here is my form:
<h1>File Upload</h1>
<form class="picwid" action="{{ URL::to('../user/edituser') }}" method="post" enctype="multipart/form-data">
<label>Select image to upload:</label>
<input type="file" name="file" id="file">
<input type="submit" value="Upload" name="submit">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
</form>
here is my function:
public function uploads(Request $request) {
$users = DB::table('users')->where('id', '=', auth()->id())->latest()->get();
if(Input::hasFile('file')){
$file = Input::file('file');
$file->move('profilepics', $file->getClientOriginalName());
$myImage = '<img src="profilepics"/>' . $file->getClientOriginalName();
}
return view('edituser', compact(['baskets', 'myImage']));
}
and here is my avatar output:
<div class="media-left">
<img src="../profilepics/ty.jpg" class="media-object" style="width:60px">
</div>
I changed the function uploads to:
public function uploads() {
$users = DB::table('users')->where('id', '=', auth()->id())->latest()->get();
$users_id = auth()->id();
if(Input::hasFile('file')){
$file = Input::file('file');
$file->move("profilepics/ $users_id", $file->getClientOriginalName());
}
return view('edituser', compact(['baskets', 'myImage', 'users_id']));
}
So I am making a function for file uploading in my project.
however, when I try it I get this error : Call to a member function isValid() on string
My code for the upload function :
public function upload(Request $request){
$file = array('profielfoto' => $request->input('profielfoto'));
$rules = array('profielfoto' => 'required',);
$validator = Validator::make($file,$rules);
if($validator->fails()){
return redirect('/profiel')->withInput()->withErrors($validator);
}
else{
if($request->input('profielfoto')->isValid()){ //<- gives error
$destinationPath = 'assets/uploads';
$extension = $request->input('profielfoto')->getClientOriginalExtension();
$fileName = rand(1111,9999).'.'.$extension;
$request->input('profielfoto')->move($destinationPath,$fileName);
Session::flash('alert-success', 'Foto uploaden gelukt');
return redirect('/profiel');
}
else{
Session::flash('alert-danger', 'Foto uploaden mislukt');
return redirect('/profiel');
}
}
}
The form in the blade view on the 4th line from down below is the location for the input!
<form method="POST" action="/profiel/upload" files="true">
{!! csrf_field() !!}
<input type="hidden" name="_method" value="PUT">
<input type="hidden" class="form-control id2" id="id2" name="id" value="{{$user->id}}">
<img src="assets/images/avatar.png" alt="gfxuser" class="img-circle center-block">
<div class="form-group center-block">
<label class="center-block text-center" for="fotoinput">Kies uw foto</label>
<input class="center-block" type="file" name="profielfoto" id="profielfoto">
</div>
<button type="submit" class="btn btn-success"><span class="fa fa-check" aria-hidden="true"></span> Verander foto</button>
</form>
You must ask isValid() to a file, not to the name of the file. That's why you get the error. You can get the file through $request->file() or through Input::file() :
else{
if( $request->file('profielfoto')->isValid()){ //<- gives error
Also your form should include the correct enctype to send files:
<form enctype="multipart/form-data">
I think you should use as this.
$file = $request -> file('Filedata');
if (!$file -> isValid()) {
echo Protocol::ajaxModel('JSEND_ERROR', 'not an valid file.');
return;
}
Add attribute on
enctype="multipart/form-data"