How to delete old avatar after uploading new on laravel? - php

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

Related

Google login integration not working, redirect to homepage without no profile

It was works fine. But problem arise after migrating domain & hosting. When I tried to login/signup with google login, it connect with Client ID & Secret correctly. But after, it redirect to homepage without any data or profile showing. On other side, same Client ID & Secret works fine in localhost.
Route::post('googlelogin', 'Api\Auth\LoginController#googlelogin');
#Controller
public function googlelogin(Request $request){
$this->validate($request, [
'email' => 'required',
'name' => 'required',
'uid' => 'required',
'password' => ''
]);
$authUser = User::where('email', $request->email)->first();
if($authUser){
$authUser->google_id = $request->uid;
$authUser->fname = $request->name;
$authUser->save();
if(isset($authUser) && $authUser->status == '0'){
return response()->json('Blocked User', 401);
}
else{
if (Hash::check('password', $authUser->password)) {
return $response = $this->issueToken($request,'password');
} else {
$response = ["message" => "Password mismatch"];
return response($response, 422);
}
}
}
else{
$verified = \Carbon\Carbon::now()->toDateTimeString();
$user = User::create([
'fname' => request('name'),
'email' => request('email'),
'password' => Hash::make($request->password !='' ? $request->password : 'password'),
'google_id' => request('uid'),
'status'=>'1',
'email_verified_at' => $verified
]);
return $response = $this->issueToken($request, 'password');
}
}

How to ignore unique validation when updating fields in laravel8?

I currently use Laravel 8 and I want to know how do I ignore unique validation when a user is updating their profile? If the user is updating every field except the pageName I don't want it to throw a vaildation error cause the user is already the owner of that pageName. I tried this code but it gives error: ErrorException
Undefined variable: user
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Auth;
use DB;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
return view('studio/index', ['littlelink_name' => $littlelink_name, 'links' => $links, 'clicks' => $clicks]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$information = User::select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->where('id', $id)->get();
$links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->get();
return view('littlelink', ['information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show buttons for add link
public function showButtons()
{
$data['buttons'] = Button::select('name')->get();
return view('studio/add-link', $data);
}
//Save add link
public function addLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required'
]);
$link = $request->link;
$button = $request->button;
$userId = Auth::user()->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
$links = new Link;
$links->link = $link;
$links->user_id = $userId;
$links->button_id = $buttonId;
$links->save();
return back()->with('message', 'Link Added');
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$link = $request->link;
$linkId = $request->id;
if(empty($link && $linkId))
{
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
return redirect()->away($link);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['links'] = Link::select('id', 'link', 'click_number', 'up_link')->where('user_id', $userId)->orderBy('created_at', 'desc')->paginate(10);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
return back();
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if($upLink == 'yes'){
$up = 'no';
}elseif($upLink == 'no'){
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$buttons = Button::select('name')->get();
return view('studio/edit-link', ['buttons' => $buttons, 'link' => $link, 'id' => $linkId]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|url',
'button' => 'required',
]);
$link = $request->link;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name' , $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_color', 'littlelink_fontcolor', 'littlelink_pixiv', 'littlelink_description')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(request $request)
{
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name'.$user->id,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$profilePhoto = $request->file('image');
$pageName = $request->pageName;
$pageColor = $request->pageColor;
$pageFontcolor = $request->pageFontcolor;
$pageDescription = $request->pageDescription;
$pagePixiv = $request->pagePixiv;
User::where('id', $userId)->update(['littlelink_name' => $pageName, 'littlelink_color' => $pageColor, 'littlelink_fontcolor' => $pageFontcolor, 'littlelink_pixiv' => $pagePixiv, 'littlelink_description' => $pageDescription]);
if(!empty($profilePhoto)){
$profilePhoto->move(public_path('/img'), $littlelink_name . ".png");
}
return back()->with('message', 'Saved');
}
//Show user (name, email, password)
public function showProfile()
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'required|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
User::where('id', $userId)->update(['name' => $name, 'email' => $email, 'password' => $password]);
return back();
}
}
Anyone know how to fix this?
You can change your code to the following
$userId = Auth::user()->id;
$request->validate([
'image' => 'nullable|mimes:jpeg,jpg,png|max:100',
'pageName' => 'nullable|alpha_dash|unique:users,littlelink_name,'.$userId,
'pageColor' => 'nullable',
'pageFontcolor' => 'nullable',
'pageDescription' => 'nullable|regex:/^[\w.\- ]+$/i',
'pagePixiv' => 'nullable|url',
]);
you can use the Rule object to make that validation:
'pageName' => ['nullable','alpha_dash', Rule::unique('users','littlelink_name')->ignore($user->id)

Array to string conversion using laravel 6

i added some fields to users table of laravel auth, and when i want to create a new user it gives me error Call to a member function hasFile () on array.
RegisterController.php
protected function create(array $data)
{
$jdate = Carbon::now();
//image
if($data->hasFile('image'))
{
$image = $data->file('image');
$imagee = Crypt::encryptString($image);
$image->storeAs("public\annonces\\".$jdate->format('F').$jdate->year,$imagee.'.'.$image->extension());
$data->image = "annonces\\".$jdate->format('F').$jdate->year."\\".$imagee.'.'.$image->extension();
}
//images
$dataim = array();
if($data->hasFile('images'))
{
foreach($data->file('images') as $file)
{
$namee = "public\\annonces\\".$jdate->format('F').$jdate->year."\\".time().'.'.$file->extension();
$name = Crypt::encryptString($namee).'.'.$file->extension();
$file->storeAs("public\\annonces\\".$jdate->format('F').$jdate->year, $name);
array_push($dataim,$name);
}
}
$data->images=json_encode($dataim);
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'telephone' => $data['telephone'],
'ville' => $data['ville'],
'ighrem' => $data['ighrem'],
'autrei' => $data['autrei'] ?? null,
'hay' => $data['hay'],
'autreh' => $data['autreh'] ?? null,
'adressem' => $data['adressem'],
'adresser' => $data['adresser'],
'image' => $data['image'] ?? null,
'images' => $data['images'] ?? null
]);
}
May you use as below
protected function create(Request $data){}

Too few arguments to function App\Http\Controllers\MyControllers\GameController::update(), 2 passed and exactly 3 expected

I get this error when I try to update my posts
In form everything is correct I guess, because I haven't changed anything there.
Thats my form method:
<form method="post" action="{{ route('games.update', $game->id) }}">
#method('PATCH')
#csrf
</form>
This is my update method:
everything was working but suddenly it started giving this error
public function update(Request $request, $id, Game $game)
{
if ($game->author !== auth()->user()->id || auth()->user()->cannot('edit games'))
abort(404);
$request->validate([
'title' => 'required',
'type' => 'required',
'city' => 'required',
'district' => 'required',
'comment' => 'required',
'full_comment' => 'required',
'photo' => 'sometimes|mimes:jpeg,jpg,gif,bmp,png',
]);
$game = Game::find($id);
$game->title = $request->get('title');
$game->type = $request->get('type');
$game->city = $request->get('city');
$game->district = $request->get('district');
$game->comment = $request->get('comment');
$game->full_comment = $request->get('full_comment');
if ($request->has('photo')) {
$photoName = $game->id . '_photo' . time() . '.' . request()->photo->getClientOriginalExtension();
$game->photo = $request->get('photo');
$game->photo = $photoName;
$request->photo->storeAs('game-photos', $photoName);
}
$game->save();
return redirect('/games')->with('success', 'Game has been updated');
}
Should work like this:
public function update(Request $request, $id)
{
$request->validate([
'title' => 'required',
'type' => 'required',
'city' => 'required',
'district' => 'required',
'comment' => 'required',
'full_comment' => 'required',
'photo' => 'sometimes|mimes:jpeg,jpg,gif,bmp,png',
]);
$game = Game::find($id);
$game->title = $request->get('title');
$game->type = $request->get('type');
$game->city = $request->get('city');
$game->district = $request->get('district');
$game->comment = $request->get('comment');
$game->full_comment = $request->get('full_comment');
if ($game->author !== auth()->user()->id || auth()->user()->cannot('edit games')) {
abort(404);
}
if ($request->has('photo')) {
$photoName = $game->id . '_photo' . time() . '.' . request()->photo->getClientOriginalExtension();
$game->photo = $request->get('photo');
$game->photo = $photoName;
$request->photo->storeAs('game-photos', $photoName);
}
$game->save();
return redirect('/games')->with('success', 'Game has been updated');
}
Remove the 3rd formal parameter called
Game $game
If you don’t have route model binding implementation on the Game model

File name change to xxxx.tmp when update file upload Laravel 5.2

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

Categories