I'm learning to create some forum, but when I update a photo profile, it can't show. When I try to inspect element it says:
"Failed to load resource: the server responded with a status of 404 (Not Found)"
This is my Controller:
public function update()
{
$avatar = request()->file('avatar');
$avatar_validate = 'image|mimes:jpeg,png,jpg,svg|max:2048';
request()->validate([
'username' => 'required|alpha_num|min:6|max:20|unique:users,username,' . auth()->id(),
'name' => 'string|required',
'avatar' => $avatar ? $avatar_validate : "",
]);
$hash = auth()->user()->hash;
$avatar_name = $avatar->storeAs('profile-picture', "{$hash}.{$avatar->extension()}");
auth()->user()->update([
'username' => request('username'),
'name' => request('name'),
'avatar' => $avatar_name,
]);
return redirect()->route('users.show', auth()->user()->usernameOrHash());
}
Try this:
$hash = auth()->user()->hash;
$filename = $hash . $avatar->getClientOriginalExtension();
$avatar_name = $avatar->storeAs('profile-picture', $filename);
Also maybe you have some "trash" files stored with a weird filename in your "profile-picture" directory
Related
I am trying to update users details but anytime i do not select image i get this error message: "Undefined array key 1" i am guessing it because i do not pass a check to see if an image is coming with the request. Or what am i doing wrong, my code is below.
public function update(UserRequest $request, $id)
{
$user = User::find($id);
if($request->profile_image)
{
$exploded = explode(',', $request->profile_image);
$decoded = base64_decode($exploded[1]);
$fileName = Str::slug("{$request->username}"). ".jpg";
$img = Image::make($decoded)->resize(360, 358)->encode('jpg');
$request->merge(['profile_image' => $fileName]);
Storage::disk('public')->put($fileName,(string) $img);
}
$user->update($request->all());
return response()->json([
'user' => $user,
]);
}
I ended up doing this
public function update(UserRequest $request, $id)
{
$user = User::find($id);
if($request->file('profile_image') )
{
$file = $request->profile_image;
$exploded = explode(',', $file);
$decoded = base64_decode($exploded[1]);
$fileName = Str::slug("{$request->username}"). ".jpg";
$img = Image::make($decoded)->resize(360, 358)->encode('jpg');
// $fileName = Str::slug("{$request->title}".'.'.'jpg');
// $img = Image::make($decoded)->resize(265, 200)->encode('jpg');
$request->merge(['profile_image' => $fileName]);
Storage::disk('public')->put($fileName,(string) $img);
}
$user->update([
'name' => $request->name,
'username' => $request->username,
'email' => $request->email,
// 'password' => $request->password,
'profile_image' => $request->profile_image,
'description' => $request->description,
]);
// $user->update($request->all());
return response()->json([
'user' => $user,
]);
}
But i get this error "message": "SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'profile_image' at row 1 (SQL: update `users` set `profile_image` = data:image/jpeg;base64,/9j/4QAC/9sAhAAGBAQ
Any help would be appreciated
can someone help me, i want to add article with image. image has successfully entered the directory but in the database the name is always D:\xampp\tmp\php......tmp.
I have changed the system file to public.
Controller
public function store(Request $request)
{
//
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$validatedData['thumbnail'] = $request->thumbnail->move(public_path('uploads/article/'), $imageName);
}
//dd($validateData['thumbnail']);
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Try this
if ($request->file('thumbnail')) {
$imageName = time().'.'.$request->file('thumbnail')->getClientOriginalExtension();
$request->thumbnail->move(public_path('uploads/article/'), $imageName);
$validatedData['thumbnail'] = url('uploads/article/'.$imageName);
}
The reason why it's return a path instead of url because you're using public_path instead of url()
Controller Code
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
// Check if request has file
if($request->hasFile('thumbnail')){
// Get File
$file = $request->file('thumbnail');
// Get File Extention
$fileGetFileExtension = $file->getClientOriginalExtension();
// Create customized file name
$fileName = Str::random(20).'_'.date('d_m_Y_h_i_s').'.'.$fileGetFileExtension;
// Save File to your storage folder
Storage::disk('public')->put('uploads/article/'.$fileName,File::get($file));
}else{
$fileName = null;
}
$validatedData['thumbnail'] = $fileName;
Article::create($validateData);
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
Run php artisan storage:link, if not created
In blade you can get your file like this
I hope this helps. :D
thanks for your answer my problem has been solved with code like this, but only the name of the file stored in the database not with the name of the directory.
public function store(Request $request)
{
$validateData = $request->validate([
'title' => 'required|max:255',
'thumbnail' => 'image|file|max:8192',
'slug' => 'required',
'description' => 'required',
]);
$imageName = time().'.'.$request->thumbnail->getClientOriginalExtension();
$request->thumbnail->move(public_path('articles/'), $imageName);
$Article = new Article;
$Article->title = $validateData['title'];
$Article->thumbnail = $imageName;
$Article->slug = $validateData['slug'];
$Article->description = $validateData['description'];
$Article->save();
return redirect('/admin-article')->with('success', 'Data has been successfully added');
}
I need upload a image to Google storage and insert the below JSON object with the gcs image path in MongoDB.
The image is successfully getting uploaded in GCS, but I am not able to get the image url of the image and also not able to update the path in mongoDB.
JSON object format
{
"original": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"thumbnail": "/pictures/1620305924456-74535-605b8a97a02cf2c1",
"fileType": "image"
}
Can anyone help me to implement the this logic.
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$disk = Storage::disk('gcs');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk->put('pictures', $request->file('imageUrl'));
$player->name ='test';
$player->imageUrl = [
'original' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'thumbnail' => '/pictures/nScT0KD7LoQucnfoFBLFfNAw9pmdfPnvtyC0VHq6.jpg',
'fileType'=> 'image'
];
Appreciation::create($player);
return redirect()->route('appreciation.index')
->with('success','Record created successfully.');
}
Thanks in advance
Finally I fixed it using below code .
request()->validate([
'name' => 'required',
'imageUrl' => 'required|image|mimes:jpeg,png,jpg|max:2048',
]);
$appreciation = new Appreciation();
$appreciation->name = $request->get('name');
$imagePath = $request->file('imageUrl');
$imageName = $imagePath->getClientOriginalName();
$disk = Storage::disk('gcs');
$url = $disk->url('/pictures/'.$imageName);
$disk->putFileAs('/pictures/', $request->file('imageUrl'), $imageName);
$data = [
'original' =>'/pictures/'.$imageName,
'thumbnail' => '/pictures/'.$imageName,
'fileType'=> 'image'
];
$appreciation->imageUrl = $data;
$appreciation->save();
I was trying to delete old avatar after uploading new avatar. Just I couldn't find solution. I am new to laravel5, Could you help me? I am using a project from github. please look at "munafio cubetalk" on github. maybe I need to change something more. It doesn't delete user avatar also when user deletes his account.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:1024',
'fullname' => 'required',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
if ($request->hasFile('avatar')) {
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = rand(9,999999999)+time().".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}
}
You can use laravel delete method to do that, make sure you import use Illuminate\Support\Facades\Storage; top of your controller class.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpeg,png,jpg|max:1024',
'fullname' => 'required',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
if ($request->hasFile('avatar')) {
// update your code in here
$avatar_name = Auth::user()->avatar;
Storage::delete($avatar_name);
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = rand(9,999999999)+time().".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}
}
Finally I solved it.
I post my edited code. If someone needs help later.
public function s_general(Request $request){
$this->validate($request,[
'username' => 'required|min:3|max:50',
'avatar' => 'nullable|image|mimes:jpg,jpeg|max:1024',
'fullname' => 'required',
'location' => 'max:255',
'bio' => 'max:340',
'email' => 'required|email'
]);
if ($request['username'] == Auth::user()->username &&$request['fullname'] == Auth::user()->name && $request['location'] == Auth::user()->location && $request['bio'] == Auth::user()->bio && $request['email'] == Auth::user()->email && !$request->hasFile('avatar')) {
return redirect()->back()->with('general_msg', Lang::get('trans.noChanges_MSG'));
}else{
$avatar = $request->file('avatar');
$user = Auth::user();
$uid = Auth::user()->uid;
$oldavatar = '/storage/avatar/'.$user->avatar;
if ($request->hasFile('avatar')) {
Storage::delete('$oldavatar');
$avatar_ext = $avatar->getClientOriginalExtension();
$avatar_name = $uid.".".$avatar_ext;
$avatar_new = $avatar->storeAs("avatar",$avatar_name);
}else{
$avatar_name = Auth::user()->avatar;
}
$update_general = User::where('uid',Auth::user()->uid)->update(['username' => $request['username'],'name' => $request['fullname'], 'bio' => $request['bio'], 'location' => $request['location'], 'email' => $request['email'],'avatar' => $avatar_name]);
return redirect()->back()->with('general_msg', Lang::get('trans.changes_saved'));
}
Hello I got an error when i tried to update image file. I have 2 form (create and edit). When I create an user with image upload it success and store with right file name to public path and database (filename.jpg).
But when I tried to update, image file success upload to public path with right file name (filename.jpg) but file name that insert to database becomes D:/Xampp/tmp/xxxx.tmp. Can anybody help me? I'm stuck from yesterday.
Create method:
public function store(CreateDosenRequest $request)
{
$user = User::create([
'name' => $request->input('name'),
'username' => $request->input('username'),
'email' => $request->input('email'),
'password' => $request->input('password'),
'admin' => $request->input('admin'),
]);
if (Input::hasFile('fotodosen')) {
$data = Input::file('fotodosen');
$photo = Input::file('fotodosen')->getClientOriginalName();
$fileName = rand(11111, 99999) . '.' . $photo;
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $fileName);
$data = $fileName;
}
$dosen = Dosen::create([
'iddosen' => $request->input('iddosen'),
'nipy' => $request->input('nipy'),
'namadosen' => $user->name,
'user_id' => $user->id,
'alamatdosen' => $request->input('alamatdosen'),
'notelpdosen' => $request->input('notelpdosen'),
'tempatlahirdosen' => $request->input('tempatlahirdosen'),
'tanggallahirdosen' => $request->input('tanggallahirdosen'),
'agamadosen' => $request->input('agamadosen'),
'fotodosen' => $data, //you have to add it hear
]);
return redirect('admin/dosen')->with('message', 'Data berhasil ditambahkan!');
}
Edit method:
public function update($id)
{
if (Input::file('fotodosen')) {
$data = Input::file('fotodosen');
$filename = Input::file('fotodosen')->getClientOriginalName();
$destination = public_path() . '/uploads/';
Request::file('fotodosen')->move($destination, $filename);
$data = $filename;
}
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen', 'statusdosen', 'fotodosen']);
$user = User::find($id);
$user->dosen()->update($dosenUpdate);
if(Auth::user()->admin==1) {
return redirect('/admin/dosen')->with('message', 'Data berhasil diubah!');
}
return redirect('/dosen')->with('message', 'Data berhasil diubah!');
}