connect a photo to a user for avatar - php

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']));
}

Related

Why doesn't my php laravel application store my image?

I've looked at code from other people and try to implement the same thing, but the application could not store the image to the desire folder, would you please have a look at what the reason is? Thank you!
Here is my code for route:
Route::post('upload_pic', 'UploadController#storePhoto');
Here is my code for the php laravel template:
<div class="panel-body">
<form action="{{url('/upload_pic')}}" method="post" enctype="multipart/form-data">
{{csrf_field()}}
<div class="form-group">
<label for="upload-user-photo">Upload Photos</label>
<input type="file" name="image" class="form-control" placeholder="Upload Student Image, Size:207(W)x408(H)">
</div>
<div class="row">
<div class="col-sm-4">
<input class="btn btn-success" type="submit" value="Upload Student Photo" name="submit">
</div>
</div>
</form>
</div>
Here is my code in the controller:
public function storePhoto(Request $request){
$valid = $request->validate([
'image' => 'required|image|mimes:jpg,png,jpeg,|dimensions:max_width=272,max_height=408,min_width=271,min_height=407'
]);
$data = new Postimage();
$file = $request->file('image');
$filename = $file->getClientOriginalName();
// dd($filename);
$file -> move(public_path('./public/img/student_photos'),$filename);
$data['image'] = $filename;
$data->save();
return redirect('/upload')->with('success', 'Photo Uploaded');
}
Your problem is somewhere here
$filename = $file->getClientOriginalName();
$file -> move(public_path('./public/img/student_photos'),$filename);
First, the file comprises only the file extension. Instead, you should have something like this $filename = 'name.' . $file->getClientOriginalName(); Notice the dot in 'name.'
Secondly, no need to add public to the file path string. So it should be $file->move(public_path('img/student_photos'),$filename);
Finally, make sure the upload folder exists and is writeable

File not uploading

I was working on a project and was trying to develop a file uploading system for skins.
When I tried to upload my skin, I was given "Call to a member function storeAs() on null"
public function uploadSkin(Request $request)
{
/* $request->validate([
'skins' => 'required|mimes:png|max:1024',
]); */
$storage_dir = storage_path('app/skins');
$request->file('skins')->storeAs($storage_dir, Auth::user->name . '.png');
return route('settings')->with('success', 'skin uploaded :)');
}
Form code:
<form method="post" enctype="multipart/form-data" action="/settings">
#csrf
<br/>
<div class="form-group">
<input type="file" class="form-control-file" id="skins" name="skins" required>
</div>
<button type="submit" class="btn btn-success">Upload</button>
</form>
To store a file like an image or any kind of files you can use a code like this:
public function uploadSkin(Request $request){
$image = $request->file('skins');
if ($image != null) {
$image->move('uploads/skins/', Auth::user()->name . $image->getClientOriginalExtension());
}
return route('settings')->with('success', 'skin uploaded :)');
}
To uppload a file there are various ways in the laravel but for now you can try this to simply move your file to your directory:
if($files= $request->file('skins')){
$files->move('uploads/skins/', Auth::user->name . '.png');
}

Why did not Update Images in edit view file in Laravel 5.6?

I have edit blade file in my laravel application. in this edit form update data saving to two tables to vehicles and uploads. I have following codes in edit blade file update images to uploads table,
#foreach( $vehicles-> uploads as $upload)
<img id="preview"
src="{{asset((isset($upload) && $upload->resized_name!='')?'images/'.$upload->resized_name:'images/noimage.png')}}"
height="200px" width="200px"/>
<input class="form-control" style="display:none" name="files[]" type="file" id="files" name="_token" value="{{ csrf_token() }}" enctype="multipart/form-data">
<br/>
Add Image |
<a class="button is-outlined" href="/myads/{{$upload->id}}/delete" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a></td>
<hr>
#endforeach
#endif
update controller is,
$photos = $request->file('files');
if (!is_array($photos)) {
$photos = [$photos];
}
if (!is_dir($this->photos_path)) {
mkdir($this->photos_path, 0777);
}
for ($i = 0; $i < count($photos); $i++) {
$photo = $photos[$i];
$name = sha1(date('YmdHis') . str_random(30));
$save_name = $name . '.' . $photo->getClientOriginalExtension();
$resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();
Image::make($photo)
->resize(250, null, function ($constraints) {
$constraints->aspectRatio();
})
->save($this->photos_path . '/' . $resize_name);
$photo->move($this->photos_path, $save_name);
$upload = Upload::find($id);
$upload->filename = $save_name;
$upload->resized_name = $resize_name;
$upload->original_name = basename($photo->getClientOriginalName());
$upload->vehicle_id = $vehicle->id;
$upload->save();
}
and route is,
Route::post('myads/{id}', [
'uses' => '\App\Http\Controllers\VehicleController#update',
])->name('vehicles.edit');
but when I attach image and click update buttons it is not update image in uploads table. how can fix this problem?
I think that you used wrong method in the update controller.
if (!is_array($photos)) {
$photos = [$photos];
}
Please try this method to convert string to array.
if (!is_array($photos)) {
$photos = explode(' ', $photos);
}
Your HTML code is wrong.
Don't use style="display:none" in input element. Browser will ignore it if they are hidden.
Don't merge CSRF Token with Input files.
Try this:
#foreach( $vehicles-> uploads as $upload)
<img id="preview" src="{{asset((isset($upload) && $upload->resized_name!='')?'images/'.$upload->resized_name:'images/noimage.png')}}" height="200px" width="200px"/>
<input class="form-control" name="files[]" type="file" id="files" enctype="multipart/form-data">
{{ csrf_field() }}
<br/>
Add Image |
<a class="button is-outlined" href="/myads/{{$upload->id}}/delete" onclick="return confirm('Are you sure to want to delete this record?')" >Delete</a>
<hr>
#endforeach

Unable to upload image through form?

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" />

Laravel 5 and redactor file uploads

I am using the following code to upload image in Laravel 5 with redactor, nothing happends, Do I need to create form request class for this as well ?
Route::post('redactorUpload', function(App\Http\Requests $request)
{
$file = $request->file('file');
$fileName = $file->getClientOriginalName();
$request->file('file')->move(public_path().'/uploads', $fileName);
return Response::json(array('filelink' => '/uploads/' . $fileName));
});
You can solve this by using Request class, the static way...i.e.
Route::post('redactorUpload', function()
{
$file = Request::file('file');
$fileName = $file->getClientOriginalName();
$file->move(public_path().'/uploads', $fileName);
return Response::json(array('filelink' => '/uploads/' . $fileName));
});
I assume that you have created the form with method "post" and action "redactorUpload" and enctype to "multipart/form-data"
Example Form :
<form action="redactorUpload" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="file" name="file" id="file">
<input type="submit" value="Upload File" name="submit">
</form>

Categories