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
Related
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)
Can someone help me with this Laravel problem?
I get Error Call to a member function update() on boolean, when I edit and update Image for an ad.
So when I create a new Ad the image will store but when updating the Ad with a new image the old image stays and I get this error for this line in storeImage.
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
This is my AdsController
public function edit($id)
{
$ad = Ad::find($id);
return view('ads.edit_ad', compact('ad', 'id'));
}
public function update(Request $request, $id)
{
$ad = Ad::find($id);
$user_id = Auth::user()->id;
$rules = [
'ad_title' => 'required',
'ad_description' => 'required',
'purpose' => 'required',
'image' => 'sometimes|file|image|max:5000',
];
$this->validate($request, $rules);
$title = $request->ad_title;
$is_negotialble = $request->negotiable ? $request->negotiable : 0;
$data = [
'title' => $request->ad_title,
'description' => $request->ad_description,
'type' => $request->type,
'price' => $request->price,
'purpose' => $request->purpose,
'address' => $request->address,
'user_id' => $user_id,
];
$updated_ad = $ad->update($data);
if ($updated_ad){
$this->storeImage($updated_ad);
}
return redirect()->back()->with('success','Ad Updated');
}
public function destroy(Ad $ad)
{
$ad->delete();
return redirect()->back()->with('success','Ad Deleted');
}
/**
* Listing
*/
public function listing(Request $request){
$ads = Ad::all();
$roles = Role::all();
return view('listing', compact('ads'));
}
public function myAds(){
$user = Auth::user();
$ads = $user->ads()->orderBy('id', 'desc')->paginate(20);
return view('ads.my_ads', compact('ads'));
}
private function storeImage($ad){
if (request()->has('image')) {
$ad->update([
'image' => request()->image->store('uploads', 'public'),
]);
$image = Image::make(public_path('storage/' . $ad->image))->fit(300, 300, null, 'top-left');
$image->save();
}
}
At the bottom of your update() function, try to change this:
if ($updated_ad){
$this->storeImage($updated_ad);
}
to this:
if ($updated_ad){
$this->storeImage($ad);
}
The Eloquent models update() function returns a boolean of whether the update completed successfully. After running the update() function on the $ad variable, it is mutated and contains the updated data, and you can use it as an argument in your storeImage() function.
I am creating a laravel API for complaints. This code is not saving multiple images in the database and I have to show multiple images in JSON response in an array. I am using array_get but it's not working for me. I have tried many things but it is not saving images in database. I have no idea. I am saving images in other table.
public function Complains(Request $request)
{
$response = array();
try {
$allInputs = Input::all();
$userID = trim($request->input('user_id'));
$cordID = trim($request->input('cord_id'));
$phone = trim($request->input('phone'));
$address = trim($request->input('address'));
$description = trim($request->input('description'));
// $image = array_get($allInputs, 'image');
$validation = Validator::make($allInputs, [
'user_id' => 'required',
'cord_id' => 'required',
'phone' => 'required',
'address' => 'required',
'description' => 'required',
]);
if ($validation->fails()) {
$response = (new CustomResponse())->validatemessage($validation->errors()->first());
} else {
$checkRecord = User::where('id', $userID)->get();
if (count($checkRecord) > 0) {
$complainModel = new Complains();
$complainModel->user_id = $userID;
$complainModel->cord_id = $cordID;
$complainModel->phone_no = $phone;
$complainModel->address = $address;
$complainModel->description = $description;
$saveData = $complainModel->save();
if ($saveData) {
if ($request->file('image')) {
$path = 'images/complain_images/';
// return response()->json(['check', 'In for loop']);
foreach ($request->file('image') as $image) {
$imageName = $this->uploadImage($image, $path);
$ImageSave = new ComplainImages();
$ImageSave->complain_id = $complainModel->id;
$ImageSave->image_url = url($path . $imageName);
$ImageSave->save();
}
}
$jsonobj = array(
'id' => $userID,
'name' => $cordID,
'email' => $phone,
'phone' => $address,
'description' => $description,
);
return Response::json([
'Exception' => "",
'status' => 200,
'error' => false,
'message' => "Complain Registered Successfully",
'data' => $jsonobj
]);
}
}else{
$response = (new CustomResponse())->failResponse('Invalid ID!');
}
}
} catch (\Illuminate\Database\QueryException $ex) {
$response = (new CustomResponse())->queryexception($ex);
}
return $response;
}
public function uploadImage($image, $destinationPath)
{
$name = rand() . '.' . $image->getClientOriginalExtension();
$imageSave = $image->move($destinationPath, $name);
return $name;
}
There is a mistake in looping allImages. To save multiple images try below code
foreach($request->file('image') as $image)
{
$imageName = $this->uploadImage($image, $path);
// other code here
}
Check if you are reaching the loop
return response()->json(['check': 'In for loop'])
I've been getting the error Creating default object from empty value laravelI was successful to insert new rows with the following code but today when I tried testing the code it is returning the error pointing on the line $reviw->rating = $request->productrating;.
Structure of my db table is:
id|fname|lname|email|country|title|content|rating|thumbnail|tour_id|status
public function store(Request $request)
{
// dd($request->all());
$this->validate($request, [
'fname' => 'required',
'lname' => 'required',
'email' => 'required',
'country' => 'required',
'title' => 'required|min:10',
'productrating' => 'required',
'content' => 'required|min:10'
]);
// dd($request->productrating);
$review = new Review;
$review->fname = $request->fname;
$review->lname = $request->lname;
$review->email = $request->email;
$review->country = $request->country;
$review->title = $request->title;
$review->content = $request->content;
$reviw->rating = $request->productrating;
if($request->hasFile('fileupload1')){
$image = $request->file('fileupload1');
$filename = 'thumb'.time().'.'.$image->getClientOriginalExtension();
$location = 'images/client_review/'.$filename;
Image::make($image)->resize(200, 200)->save($location);
$review->thumbnail = $location;
}
$review->tour_id = $request->product_id;
$review->status = false;
$review->save();
Session::flash('success','Thank You for submitting us your review.');
return view('public.pages.message-review');
}
I'm sending following data from the form to save into the table.
I think you need to update your code like :
$review = new Review;
$review->fname = $request->fname;
$review->lname = $request->lname;
$review->email = $request->email;
$review->country = $request->country;
$review->title = $request->title;
$review->content = $request->content;
$review->rating = $request->productrating;
You have an error in $reviw->rating = $request->productrating; change $reviw to $review and it will work
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!');
}