uploading image and got error in laravel "Undefined variable: data" - laravel

I am trying to update the product and for that I am updating the pictures. I meant if user want to add more pictures to it but when I do this I get below error
Undefined variable: data
Also I want to restrict the total uploading pictures to max 3 pictures or 2 pictures and 1 video
When I add a video it does not show like it does not play
Any help would be great. Thank for the help in advance
public function editProduct($id, Request $request) {
if(Auth::check()) {
$pn = Input::get('pn');
$desc = Input::get('desc');
$price = Input::get('price');
// $products = Product::all();
$products = Product::where('id', $id)->first();
// foreach($products as $p) {
if(($products->user_id == Auth::user()->id) && ($products->id == $id)) {
$this->validate($request, [
'filename.*' => 'required|max:5000',
// 'filename.*' => 'image|mimes:jpeg,png,jpg,mp4|max:5000'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name = $image->getClientOriginalName();
$filename = time(). '-' . $image;
$file_path = $image->move(public_path().'/assets/images/', $name);
$data[] = $name;
}
}
$new_name = json_encode($data);
$products = Product::where('user_id', Auth::user()->id)
->where('id', $id)->update([
'product_name' => $pn,
'description' => $desc,
'price' => $price,
'filename' => $new_name,
]);
}
} else {
Session::flash("message", "OOPS! You dont have permission to edit the items. Please login first.");
return redirect("/register-user");
}

I was missing enctype="multipart/form-data" files=true in my form in the view so it was not getting a file from the blade so got it fixed now

Related

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.

how to send multiple files with one key in laravel using guzzle Http

I can send multiple files and string data with post man like bellow:
but the question is how to send similar request with laravel http ?
what I did is :
public function performMultiPartRequest($requestUrl, $body)
{
$response = Http::withHeaders(['Accept' => 'application/json']);
$data = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') // for string data. works well.
array_push($data,[$key, $value]);
else if (gettype($value) == 'array') { // array of files. doesn't work!
foreach ($value as $file) {
$extension = $file->getClientOriginalExtension();
$response->attach($key , fopen($file, 'r'), mt_rand(100,1000).".".$extension);
}
}
else { // one file. works well.
$extension = $value->getClientOriginalExtension();
$response->attach($key, fopen($value, 'r'), 'temp.'.$extension);
}
}
$response = $response->post($this->baseUri.$requestUrl, $body);
return $response;
}
when I try to send some string key value with a file or files with different keys, it's ok, but when I try to send data with multiple file upload (one key) error happens.
the error message is:
A 'contents' key is required with status code 0
unfortunately I didn't find a solution to do the job with Illuminate\Support\Facades\Http yet, but because of time limitation of the project, I used GuzzleHttp\Client instead:
$client = new Client([
"base_uri" => $url,
]);
$data = [];
$data['multipart'] = [];
foreach ($body as $key => $value) {
if (gettype($value) == 'string') {
array_push($data['multipart'], [
'name' => $key,
'contents' => $value
]);
} else if (gettype($value) == 'array') {
foreach ($value as $k => $file) {
if (file_exists($file)) {
$extension = $file->getClientOriginalExtension();
array_push($data['multipart'], [
'name' => $key."[]",
'contents' => fopen($file, 'r'),
'filename' => mt_rand(100, 1000) . "." . $extension
]);
}
}
}
}
$response = $client->request('POST', $requestUrl, $data);
it works fine for my case.
but any solution to laravel Http facade will be appreciated for this problem.

Uploading multi images in Laravel 5.8

I am a beginner in laravel. I'm trying to submit a post with the option to upload multiple files if the user wants. I keep getting the error "Undefined variable: data." Where did I go wrong?
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}
I think that it will be better to declare your array outside the foreach loop.
You can try something like this:
Outside your foreach loop.
$data = array();
Inside your foreach loop, try to populate the array like this:
array_push($data, $name);
public function store(Request $request)
{
//validate
$this->validate($request, [
'title' => 'required|min:10',
'body' => 'required|min:20',
'filename' => 'nullable|max:2480',
'filename.*' => 'mimes:jpeg,jpg,png'
]);
//Initialize an empty array
$data = array();
//store Image
if($request->file('filename'))
{
foreach($request->file('filename') as $image)
{
$name=time().$image->getClientOriginalName();;
$image->move(public_path().'/images/', $name);
//populate array here
array_push($data, $name);
}
}
$post= new Post();
$post->user_id = auth()->user()->id;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->filename=json_encode($data);
$post->save();
return back()->withMessage('Post created successfully.');
}

Save image to database

I want to save image name to database but it always save to C:\xampp\tmp\phpAB3A.tmp. btw im not using xampp, im using laragon.How to change the path? i want to save to storage/app/public
'name'=> 'required',
'email' => 'required',
//'logo' => 'required',
$imageName = time().'.'.request()->logo->getClientOriginalExtension();
request()->logo->move(storage_path('app/public'), $imageName);
Company::create($request->all());
return redirect()->route('company.dashboard')->with('Success');
In your Company::create you have to define the path... Something like:Company::create([
'path' => torage_path('app/public',$imageName),....]);
I'm using laravel 5.8 and this code worked for me.
In controller
<?php
public function store()
{
// I did like this, because storeLogo method is reusable
$data = request()->validate([ /* ... */ ]);
$company = Company::create($data);
$this->storeLogo($company);
// but you can do like this
$data = request()->validate([ /* ... */ ]);
if (request()->has('logo')) {
$data['logo'] = request()->logo->store('', 'public');
}
$company = Company::create($data);
}
private function storeLogo(Company $company)
{
if (request()->has('logo')) {
$company->update([
'logo' => request()->logo->store('', 'public'),
// logo file is stored at /storage/app/public/
]);
}
}
$input = $request->all();
$fileName = '';
if ($request->hasFile('logo')) {
$destinationPath = storage_path('app/public');
$file = $request->logo;
$fileName = time() . '.'.$file->clientExtension();
$file->move($destinationPath, $fileName);
}
$input['logo'] = $fileName;
Company::create($input);

Cannot upload file using guzzle and send to laravel API

I have two laravel projects, one for API and one for front end. What I want to achieve is to send the uploaded file on my front end and send it to my API using guzzlehttp6. Here's my code.
FrontEnd Laravel:
public function store(Request $request, $module_id)
{
$videos = $request->file('file');
// $name = time().$videos->getClientOriginalName();
// $path = ('videos');
// $videoFinal = $videos->move($path, $name);
$file_name = fopen($videos, 'r');
$client = new Client(['base_uri' => 'http://localhost/api.kourse/public/api/v1/']);
try{
$response = $client->request('POST', 'modules/'.$module_id.'/videos',[
'file_name' => $file_name
]);
}catch(ClientException $e){
return $e->getResponse();
}
}
When returning the $videos im getting the path of the file.
Here's my API
public function store(VideoRequest $request, $moduleId)
{
$module = Module::find($moduleId);
if( !$module )
{
return response()->json([
'message' => 'Module does not exist',
'code' => 404
],404);
}
$file = $request->file('file_name');
$name = time(). $file->getClientOriginalName();
$path = '/videos';
$file->move(public_path().$path, $name);
Video::create([
'file_name' => $name,
'file_path' => $path.$name,
'module_id' => $module->id
]);
return response()->json([
'message' => 'Successfully created and assgin video to this module'
],200);
}
What Iam getting is that :
{message: {file_name: ["The file name field is required."]}, code: 422}
code
:
422
as defined in my VideoRequest.
Can anyone help me on this.

Resources