This is the code to upload an image in my controller and its uploading but the link to view the image is broken
if (request()->hasFile('payslip')) {
$payslip = request()->file('payslip')->getClientOriginalName();
request()->file('payslip')->storeAs('payslip', $user->id . '/' . $payslip, '');
$user->update(['payslip' => $payslip]);
}
Below is the code in my view
<img src="{{asset ('payslip/'.Auth::user()->id.'/'. Auth::user()->payslip) }}" alt="payslip" class="credential-img">
**Solved the problem
This is the code in my Register Controller to upload image into public folder**
protected function create(array $data){
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'cellno' => $data['cellno'],
'workno' => $data['workno'],
'address' => $data['address'],
'password' => Hash::make($data['password']),
]);
if (request()->hasFile('payslip')) {
$file = request()->file('payslip');
// dd($file);
$extension = $file->getClientOriginalExtension();
$filename = $user->name . $user->email . '_' . $user->id . '.' . $extension;
$file->move('img/'.$user->id.'/', $filename);
$user->payslip= $filename;
$user->save();
}
return $user;
}
Below is the code in my view
<img src="{{asset ('img/'.Auth::user()->id.'/'. Auth::user()->payslip) }}"
alt="payslip" class="credential-img">
Related
I want to do multiple image uploads in my laravel but so far i get errors like image must be image ... is chaos really ... help please???
public function store(Request $request) {
$request->validate([
'name' => 'required',
'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
'image.*' => 'image',
'description' => 'required',
'quantity' => 'required',
]);
$imgData = [];
if($request->hasfile('image')) {
foreach($request->file('image') as $file)
{
$path = '/images/phones';
$date = Carbon::now();
$tempName = env('APP_URL') . '/storage' . $path . '/'. $date->year.'/' . time() . '.' . $file->getClientOriginalName();
$filename = time() . '.' . $file->getClientOriginalName();
$filePath = $path . "/$date->year";
$file->storeAs( $filePath, $filename, 'public');
$imgData[] = $tempName;
}
$phones = new Phone;
$phones->name = $request->name;
$phones->description = $request->description;
$phones->quantity = $request->quantity;
$phones->price = $request->price;
$phones->brand_id =$request->brand_id;
$phones->image = json_encode($imgData);
$phones->save();
return redirect()->route('phones.index')
->with('success','Product has been created successfully.');
}
So far I get this error that image must be image and another error is displaying required extensions!!
I am a Laravel beginner and I want to build an API with Laravel 8.
I have posts and images and I want to store and update them.
My store method works and the images are saved in the database and public path in images folders, but in update method I can't save it in folder.
These are my codes:
PostController
public function store(Request $request )
{
$data = $request->all();
//validationg posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی']);
}
//separate tags
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
//getting post images from request
$files = $request->file('image');
//saving name and path of images
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$postTitle = $request->title; //post title for folder name and the images inside it
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
$image = new Image;
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image; // make an array of uploaded images
}
}
$post = Post::create($data);
$post->images()->saveMany($images);//save imageas in image table
$post->tag($tags);//save tags in tags table
return response()->json([
'success' => true,
'message' => 'با موفقیت ثبت گردید ',
'data' => $post
]);
}
public function update(Request $request, $id)
{
$post_failed = Post::find($id);
if (is_null($post_failed)) {
return response()->json('پست مورد نظر یافت نشد ', 404);
}
$data = $request->all();
//validation posts and images fields
$validator = Validator::make($data, [
'user_id' => 'required',
'category_id' => 'required',
'title' => 'required|max:150|unique:posts',
'body' => 'required',
'study_time' => 'required',
'tags' => 'nullable|string',
'image' => 'required',
]);
if ($validator->fails()) {
return response()->json(['error' => $validator->errors(), 'خطا در اعتبار سنجی ']);
}
$tags = explode(",", $request->tags);
if ($request->hasfile('image')) {
$postTitle = $request->title; //post title for folder name and the images inside it
//delete last Images from database for updating images
Image::where('imageable_type', 'App\Models\Post')->where('imageable_id' , $id)->delete();
//delete last images images folder
File::delete(public_path('/images/posts/'.$postTitle));
$files = $request->file('image');
foreach ($files as $file) {
$imageName = time().rand(1,10000).'.'.$file->extension();
$imagePath = public_path(). '/images/posts/'.$postTitle;
$image = new Image();
$image->image = $imageName;
$image->path = $imagePath;
$images[] = $image;
}
}
$post = Post::find($id);
$post->user_id = $data['user_id'];
$post->category_id = $data['category_id'];
$post->title = $data['title'];
$post->body = $data['body'];
$post->study_time = $data['study_time'];
$post->tags = $data['tags'];
$post->save();
$post->images()->saveMany($images);
$post->tag($tags);
return response()->json([
'success' => true,
'message' => 'با موفقیت ویرایش گردید ',
'data' => $post
]);
}
The relation between posts and images is polymorphic one to many and I tested it with postman.
Postman
Database
And the path:
Please, help.
In store() method you saved images on disk by using
$imagePath = public_path(). '/images/posts/'.$postTitle;
$file->move($imagePath, $imageName);
In update() you deleted them
File::delete(public_path('/images/posts/'.$postTitle));
and determined path for new files
$imagePath = public_path(). '/images/posts/'.$postTitle;
but nothing happens after this. In whole update() method there is no code that could do something in storage, so of course nothing appears in folder ;)
So again use $file->move() or Storage facade to save files.
TIP
Also this is bad practice to repeat long code logic like that. It would be better to extract this and share between store/update.
I am trying to update image into database & local folder but it's not updating related to the user, how can I do that?
return $request
{
_token: "8CrxYrMtEZR1UO6VDLVByLAqFkC2OuVcwws1pVX4",
first_name: "faizan",
last_name: "Ahmed",
phone: "03322858593",
company_name: "yourstitchart.com",
Country: "GB",
image: "iconfinder_BW_Facebook_glyph_svg_5305154.png"
}
controller
public function update(Request $request)
{
$first_name = $request->first_name;
$last_name = $request->last_name;
$company_name = $request->company_name;
$phone = $request->phone;
$Country = $request->Country;
$user = Auth::user()->id;
if ($request->hasFile('image')) {
$image = $request->file('image');
$extension = $image->getClientOriginalExtension();
Storage::disk('yourstitchart')->put($image->getFilename() . '.' . $extension, File::get($image));
$content = new User();
$content->image = $image->getFilename() . '.' . $extension;
$check = User::where('id', $user)->update([
'first_name' => $first_name,
'last_name' => $last_name,
'company_name' => $company_name,
'phone' => $phone,
'image' => $content->image
]);
} else {
$check = User::where('id', $user)->update([
'first_name' => $first_name,
'last_name' => $last_name,
'company_name' => $company_name,
'phone' => $phone
]);
}
return back()->withSuccess('Profile Updated !', $check);
}
I have error while i am uploading Post Image I can save picture on my computer but in my database filename is distorted.
Here is my PostsController
public function store(Request $request, User $user, Image $image)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'body' => 'required'
]);
if( $request->hasFile('image') ) {
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
Image::make($image)->save( public_path('uploads/images/' . $filename ) );
}
$image = $filename;
auth()->user()->publish(
new Post(request(['body', 'image'])));
return redirect('/');
}
The problem is that you try to insert the wrong variable into your database table. So, improve your code like this:
auth()->user()->publish(
new Post(['photo' => request('body'), 'image' => $image])
);
Hi i am trying to upload a photo but i do not get the filename of the photo in my database..The photo successfully uploads to my folder.i have this in my controller
public function postCreatePost(Request $request)
{
if ($request->hasFile('avatar'))
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('uploads/posts/' .$filename));
Auth::user()->posts()->create([
'body' => $request->body,
'username' => Auth::user()->name,
'photo' => $filename,
]);
$posts = Post::orderBy('created_at', 'desc')->get();
return view('home', ['post' => $posts]);
}
Can anyone please tell me what i am missing