Laravel Uploading a photo - laravel-5

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

Related

How to upload multiple images in laravel so I can get them in frontend?

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!!

why images aren't stored in public path

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.

storage link not loading image after symlink Laravel

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

I have store the image file in admin through post method but when trying to put the same code for pdf/word its not working

I want to upload pdf file on page but its not working as done with image and its working
I have made a column filepath for pdf/word then code in postcontroller but not working
public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|image',
'content'=>'required',
'category_id'=>'required'
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
and when I trying to add "filepath column name in data base" for pdf/ word then using in public function store(Request $request)
{
$this->validate($request, [
'title' =>'required',
'featured'=>'required|image',
'content'=>'required',
'category_id'=>'required',
'file' => 'required',
]);
$featured= $request->featured;
$featured_new_name=time().$featured->getClientOriginalName();
$featured->move('uploads/posts', $featured_new_name);
$file=$request->file;
$file=time().$file->getClientOriginalName();
$extension = Input::file('file')->getClientOriginalExtension();
$filename = rand(11111111, 99999999). '.' . $extension;
$fullPath = $filename;
$request->file('file')->move(base_path() . '/uploads/pdf/', $filename);
$post = Post::create([
'title'=>$request->title,
'content'=>$request->content,
'featured'=>'uploads/posts/'. $featured_new_name,
'file'=>'uploads/pdf' .$filename,
'category_id'=>$request->category_id,
'slug'=>str_slug($request->title)
]);
Session::flash('success', 'New Blog has been Published on Website for Particular Menu');
return redirect()->back();
}
There is an issue in your code, you are saving the image in your base path whereas you want to save it into your public path so use
$request->file('file')->move(public_path() . '/uploads/pdf/', $filename);
instead of
$request->file('file')->move(base_path() . '/uploads/pdf/', $filename);
To save file update your code
validation of file type
'file' => 'required|mimes:pdf,doc|max:10000',
save file
if($request->hasfile('file'))
{
$file = $request->file;
$input = rand(11111111, 99999999).'.'.$file->getClientOriginalExtension();
$destinationPath = public_path('/uploads/pdf/100');
$file->move($destinationPath, $input);
}

Laravel user post image upload error

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

Resources