File not found at path: on laravel 5.6 - php

i am using laravel 5.6, i will try to make function multiple upload video, and get frame and duration with laravel-ffmpeg, but when i try to upload one video for example, always show error like "File not found at path:",
this is my function to store video and get duration & frame :
public function doCreate($lessonsid)
{
if (empty(Session::get('contribID'))) {
return redirect('contributor/login');
}
# code...
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'judul' => 'required',
// 'video.*' => 'mimes:mp4,mov,ogg,webm |required|max:100000',
// 'image.*' => 'mimes:jpeg,jpg,png,gif|required|max:30000'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput();
} else {
$now = new DateTime();
$cid = Session::get('contribID');
$title = Input::get('judul');
$image_video = Input::file('image');
$lessons_video = Input::file('video');
// dd($lessons_video);
// $media = FFMpeg::open('https:/dev.cilsy.id/assets/source/lessons/lessons-74/video-8/1. Introduction (2).mp4');
// $frame = $media->getFrameFromString('00:00:13.37');
// dd($media);
$description = Input::get('desc');
$video=Video::where('lessons_id',$lessonsid)->get();
$count_video=count($video);
if (!is_dir("assets/source/lessons/lessons-$lessonsid")) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid);
}
$i=$count_video + 1;
foreach ($title as $key => $titles) {
$type_video =$lessons_video[$key]->getMimeType();
if (!is_dir("assets/source/lessons/lessons-".$lessonsid."/video-".$i)) {
$newforder=mkdir("assets/source/lessons/lessons-".$lessonsid."/video-".$i);
}
$DestinationPath= 'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;
//insert image
if(!empty($image_video[$key])){
$imagefilename = $image_video[$key]->getClientOriginalName();
$image_video[$key]->move($DestinationPath, $imagefilename);
}else{
$imagefilename = '';
}
if($imagefilename ==''){
$url_image= $imagefilename;
}else{
$urls=url('');
$url_image= $urls.'/assets/source/lessons/video-'.$i.'/'.$imagefilename;
}
//insert video
if(!empty($lessons_video[$key])){
$lessonsfilename = $lessons_video[$key]->getClientOriginalName();
$lessons_video[$key]->storeAs($DestinationPath, $lessonsfilename);
}else{
$lessonsfilename = '';
}
if($lessonsfilename ==''){
$url_video= $lessonsfilename;
}else{
$urls=url('');
$url_video= $urls.'/assets/source/lessons/video-'.$i.'/'.$lessonsfilename;
}
$store = new Video;
$store->lessons_id = $lessonsid;
$store->title = $titles;
$store->image = $url_image;
$store->video = $url_video;
$store->description = $description[$key];
$store->type_video = $type_video;
$store->durasi = 0;
$store->created_at = $now;
$store->enable=1;
$store->save();
if($store){
$media = FFMpeg::open($url_video);
// $frame = FFMpeg::open($link)
// ->getFrameFromSeconds(10)
// ->export()
// ->toDisk('public')
// ->save($filename.'.png');
dd($media);
$durationInSeconds = $media->getDurationInSeconds();
// dd($media);
}
$i++;
}
// Session::set('lessons_title',$title);
// Session::set('lessons_category_id',$category_id);
// Session::set('lessons_image',$image);
// Session::set('lessons_description',$description);
return redirect('contributor/lessons/'.$lessonsid.'/view')->with('success','Penambahan video berhasil');
}
}
this is message error, when i try to upload my video
anyone can help me?

try with public_path()
$DestinationPath= public_path().'/'.'assets/source/lessons/lessons-'.$lessonsid.'/video-'.$i;

You files are not saving, you should use public_path helper for storing and retrieving files back.
$image_video[$key]->move(public_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
Or you can store them into storage folder
$image_video[$key]->move(storage_path('lessons/lessons-'.$lessonsid.'/video-'.$i), $imagefilename);
You can retrieve back files using these helpers.
Hope this helps.

Related

Upload multiple images into database using laravel 5.7

i want to upload multiple images and store them into database, but i got an error like this :
file_get_contents() expects parameter 1 to be a valid path, array given
This is my controller :
public function fileMultiple(Request $request) {
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $image)
{
$name=$image->getClientOriginalName();
$image_encod = base64_encode(file_get_contents($request->file('filename')));
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$data = new Image();
$data->image_name = $image_encod;
$data->save();
}
}
return back()->with('success', 'Your images has been successfully');
}
how to fix it, the image must encode using base64
You can simply change a little bit in foreach loop and use the $key by following:
foreach($request->file('filename') as $key => $image)
{
$name=$image->getClientOriginalName();
$image_encod = base64_encode(file_get_contents($request->file('filename')[$key]));
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$data = new Image();
$data->image_name = $image_encod;
$data->save();
}
The problem is that you're sending the array value.
The following code:
$image_encod = base64_encode(file_get_contents($request->file('filename')));
should be changed into:
$image_encod = base64_encode(file_get_contents($image));
<?php
public function fileMultiple(Request $request) {
$this->validate($request, [
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if(is_array($request->filename) && count($request->filename) > 0){
foreach ($request->filename as $key => $file) {
if($request->hasFile('filename.' . $key)){
$file = $request->file('filename.' . $key);
if($file->store(public_path('/images')))
{
$data = new Image();
$data->image_name = $image_encod;
$data->save();
return back()->with('success', 'Your images has been successfully');
}
else{
throw new \Exception('Unable to save image.');
}
}
}
}
return back()->with('error', 'Unable to save image.');
}

Laravel : Update field when value is exist

I have some problem with updating file. I have a form with the following attributes :
title
text
pdf file
The problem is the update operation will save the pdf file as the following value :
with file : ["example.pdf"]
no file : [""]
It will include [""] to the pdf file value when updated.
I want the pdf file updated to a new file when a new file is selected, old file remained when there is no new file selected and null value to file when there is no file, to begin with.
Here is the update controller.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if ($getFile) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
$old = Announcement::where('id',$main_id)->pluck('brochure');
if (empty($old)) {
$announcements->brochure = null;
}
else {
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}
What am I doing wrong in this code? Please help me. Thank you.
Change this:
$old = Announcement::where('id',$main_id)->pluck('brochure');
To:
$old = Announcement::where('id',$main_id)->value('brochure');
The thing is pluck() will return a collection of brochure, not a string. And value() will return a string or null.
public function update()
{
if (Auth::check()) {
$user_id = Auth::user()->id;
$main_id = Input::get('edit_id');
$announcements = Announcement::find($main_id);
$getFile = Input::file('new_brochure');
$rules = array(
'title' => 'required',
'text' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()->withInput()
->withErrors($validator)
->withInput();
}
if (!empty(Input::file('new_brochure'))) {
$file = array('new_brochure' => Input::file('new_brochure'));
$destinationPath = 'img/brochures/announcements'; // upload path
$extension = Input::file('new_brochure')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('new_brochure')->move($destinationPath, $fileName);
$announcements->brochure = $fileName;
}
else
$old = Announcement::where('id',$main_id)->value('brochure');
$announcements->brochure = $old;
}
$announcements->title = (Input:: get('title'));
$announcements->from = (Input:: get('from'));
$announcements->to = (Input:: get('to'));
$announcements->text = (Input:: get('text'));
$announcements->is_active = '1';
$announcements->created_by = $user_id;
$announcements->updated_by = $user_id;
$current_date = date("Y-m-d H:i:s");
$announcements->created_at = $current_date.".000";
if ($announcements->save()){
$this->request->session()->flash('alert-success', 'Updated successfully!');
}
else{
$this->request->session()->flash('alert-warning', 'Could not update!');
}
return redirect()->route('Announcements_view');
}
}

Access variable outside of Excel::load in Laravel

I would like to ask if how can I access the error message variable when I execute the a foreach loop inside the Excel::load function which reads the csv file that I uploaded so that I can return it via the Response::json();
Here's my code:
$errorMessage['error'] = [];
if($request->hasFile('file')){
if($request->file('file')->getClientOriginalExtension() != "csv"){
$errorMessage['error'][] = "File should be in csv format";
}
else {
$fileName = $request->file('file')->getClientOriginalName().".csv";
$destination = base_path().'/storage/excel/imports';
$request->file('file')->move($destination, $fileName);
$csvFile = base_path().'/storage/excel/imports/'.$fileName;
$demographics = $request->get('demographics');
\Excel::load($csvFile, function($reader) use($demographics,$errorMessage) {
if($demographics == "region"){
foreach($reader->get()->toArray() as $data){
$region = Region::whereRaw("LCASE(`short_name`) = ?", array(strtolower($data['region_name'])))->first();
if($region){
$regionData = Region::find($region->id);
$regionData->total_number_of_provinces = $data['total_provinces'];
$regionData->total_number_of_cities_municipalities = $data['total_cities_and_municipalities'];
$regionData->save();
}
else {
$errorMessage['error'][] = $data['region_name'] . " is not existing in the database";
}
}
}
});
}
}
else {
$errorMessage['error'][] = "Please specify a file";
}
return \Response::json($errorMessage);
Bit smelly, but you can declare it a class property.
/**
* #var array
*/
protected $errorMessage;
public function doStuff()
{
// ...
\Excel::load($file, function($reader) use ($demographics) {
// ...
$this->errormessage['error'][] = $data['region_name'];
});
// ...
return \Response::json($this->errorMessage);
}
Note
You can also pass $errorMessage by reference, which a lot of people think is the better choice (you're using a throw-away function after all).
\Excel::load($file, function($reader) use ($demographics, &$errorMessage)
I don't like to do this however, because in my opinion it's less readable what I meant to do. You can choose one of either picks though!
Useful and short explanation: http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/
$fileName = md5(time()) .'.'.$request->file('file')->getClientOriginalExtension();
$sheet_id = $request->session()->get('sheet_id');
$excel=Excel::load(public_path('/uploads/importsheet/'.$fileName),function ($reader)use ($sheet_id) {
$reader->each(function($sheet) use ($sheet_id) {
$headings = $sheet->keys()->toArray();
for($i=0; $i<count($headings); $i++){
$sheet_id = DB::table('import_sheets_attributes')->insertGetId(
[
'import_sheets_id' => $sheet_id,
'attribute' => $headings[$i],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
});
});
Hope the above sample code will help.

Image not moving to proper folder zend framework2

I started working on Zend Framework image upload.The code is not showing any errors but image not moving to proper destination.
public function uploadAction()
{
error_reporting(E_ALL);
ini_set('display_errors', 1);
$form = new UploadForm();
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload'); //upload destination
$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if($favadapter->receive($favicon))
{
echo "suceess";
}
else
{
echo "Failed";
}
die;
}
}
return array('form' => $form);
}
The image is not received and gives failed message.Can you solve this problem.Thanks in advance
You write "gives failed message" so apparently something goes wrong. You should try to find out what and why... All we can do is guess with the information you are giving inside your question.
If you read the ZF2 documentation on this file adapter class here then you can see that the adaper has a getMessages method. This might give you some insight on what actually goes wrong:
$adapter = new Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
This code snippet comes straight out of the official docs!
Your final running code make sure you comment filters
public function uploadAction()
{
error_reporting(0);
$em = $this->getEntityManager();
$form = new UploadForm($em);
$form->get('submit')->setValue('Add');
$request = $this->getRequest();
if ($request->isPost())
{
$profile = new Upload();
$form->setInputFilter($profile->getInputFilter());
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('fileupload');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data);die;
//set data post and file ...
$form->setData($data);
if ($form->isValid())
{
$favicon = $data['fileupload']['name'];
$ext = pathinfo($favicon, PATHINFO_EXTENSION);
$faviconnewname = "_favicon." . $ext;
$favadapter = new \Zend\File\Transfer\Adapter\Http();
$favadapter->setDestination('public/img/upload/'); //upload destination
//$favadapter->addFilter('Rename', $faviconnewname, $favicon);
if (!$favadapter->receive())
{
$messages = $adapter->getMessages();
echo implode("\n", $messages);
}
else
{
echo "success";
}
// die;
}
}
// if ($request->isPost())
// {
// $fname = $_FILES['fileupload']['name'];
// $tmp_name = $_FILES["fileupload"]["tmp_name"];
// $uploads_dir = 'public/img/upload';
// if(move_uploaded_file($tmp_name,"$uploads_dir/$fname"))
// {
// echo "Uploaded";
// }
// else
// {
// echo "Error";
// }
// }
return array('form' => $form);
}

Only update image if user uploaded a new one, Laravel

I have an edit form which has an image field where a user can upload a new image if he wants to.
But if the user does not upload a new photo I don't want to validate the image field and just use the photo that's already in the database. And not update the image field at all.
Here is my edit function:
public function postEdit($id) {
$product = Product::find($id);
// This should be in product model, just testing here
$edit_rules = array(
'category_id' => 'required|integer',
'title' => 'required|min:2',
'description' => 'required|min:10',
'price' => 'required|numeric',
'stock' => 'integer'
);
// Add image rule only if user uploaded new image
if (Input::has('image')) {
$edit_rules['image'] = 'required|image|mimes:jpeg,jpg,bmp,png,gif';
}
$v = Validator::make(Input::all(), $edit_rules);
if ($product) {
if ($v->fails()) {
return Redirect::back()->withErrors($v);
}
// Upload the new image
if (Input::has('image')) {
// Delete old image
File::delete('public/'.$product->image);
// Image edit
$image = Input::file('image');
$filename = date('Y-m-d-H:i:s')."-".$image->getClientOriginalName();
Image::make($image->getRealPath())->resize(600, 600)->save('public/img/products/'.$filename);
$product->image = 'img/products/'.$filename;
$product->save();
}
// Except image because already called save if image was present, above
$product->update(Input::except('image'));
return Redirect::to('admin/products')->with('message', 'Product updated.');
}
return Redirect::to('admin/products');
}
Using this I can update all the values except the image.
If I don't upload a new photo it saves all other updated values.
If I do upload a new photo it just ignores it and saves all other updated values, doesn't upload the new photo.
Check if the request has the file:
public function update(Request $request)
{
// Update the model.
if($request->hasFile('photo')) {
// Process the new image.
}
// ...
}
public function update() {
$id=Input::get('id');
$rules= array('name'=>'required|regex:/(^[A-Za-z]+$)+/',
'detail'=>'required|regex:/(^[A-Za-z]+$)+/',
'images' => 'required|image');
$dat = Input::all();
$validation = Validator::make($dat,$rules);
if ($validation->passes()){
$file =Input::file('images');
$destinationPath = 'image/pack';
$image = value(function() use ($file){
$filename = date('Y-m-d-H:i:s') . '.' . $file->getClientOriginalExtension();
return strtolower($filename);
});
$newupload =Input::file('images')->move($destinationPath, $image);
DB::table('pkgdetail')
->where('id', $id)
->limit(1)
->update(array('name' => Input::get('name'), 'detail' => Input::get('detail'), 'image' => $newupload));
$data=PackModel::get_all();
return View::make('pkg_dis')->with('data',$data)
->withErrors($validation)
->with('message', 'Successfully updated.');
}
}
use Illuminate\Support\Facades\Input;
public function update(Request $request, $id)
{
if ($tag = Tag::find($id))
{
$this->validate($request, [
'tag_name' => 'required|min:3|max:100|regex: /^[a-zA-Z0-9\s][a-zA-Z0-9\s?]+$/u|unique:tags,tag_name,'.$id.',id',
]);
$tag->tag_name=$request->input('tag_name');
// get the image tag_img_Val
if($request->hasFile('tag_image'))
{
$this->validate($request, [
'tag_image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:1000',
]);
$img = $request->file('tag_image');
$old_image = 'uploads/' . $tag->tag_image;//get old image from storage
if ($img != '')
{
$image = rand() . '_' . ($img->getClientOriginalName());
$path = 'uploads/';
//Storing image
if ($img->move(public_path($path), $image))
{
$tag->tag_image = $image;
if ($tag->update())
{
if (is_file($old_image)) {
unlink($old_image); // delete the old image
}
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
unlink($image); // delete the uploaded image if not updated in database
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not moved"],500);
}
}
else
{
return response()->json(['message' => "Sorry, Image not uploaded"],500);
}
}
else
{
if($tag->update(Input::except('tag_image')))
{
return response()->json(['message' => 'Tag has been updated successfully.'],200);
}
else
{
return response()->json(['message' => "Sorry, Tag not updated"],500);
}
}
}
else
{
return response()->json(['message' => 'Tag not found'], 404);
}
}
You need to use multipart for form enctype
You can use another function to delete the images from the folder. like here
private function unlinkPostImages($images)
{
if(!empty($images)){
foreach ($images as $img){
$old_image = public_path('storage/' . $img->image);
if (file_exists($old_image)) {
#unlink($old_image);
}
}
}
}
Then call this function above image delete function. like this...
$this->unlinkPostImages($getId->images); // this will delete image from folder
$getId->images()->delete(); // --> this delete from database table $post->id
same this Click here..
my update function
public function update(UpdatePostRequest $request, Post $post)
{
//
$data = $request->only(['title', 'description', 'contents', 'price']);
// صورة الإعلان //
if ($request->hasFile('image')) {
Storage::disk('public')->delete($post->image);
$imagePath = $request->image;
$filename = Str::random(10).'-'.time().'-'.$imagePath->getClientOriginalName();
$image_resize = Image::make($imagePath->getRealPath());
$image_resize->fit(120);
$image_resize->orientate();
$image_resize->save(public_path('storage/images/' .$filename), 100);
$sImg = 'images/'. $filename;
$data['image'] = $sImg;
}
// -------- //
if ($request->hasFile('images'))
{
$getId = Post::find($post->id);
$this->unlinkPostImages($getId->images);
$getId->images()->delete();
$uploadPicture = array();
foreach ($request->file('images') as $photo) {
$file = $photo;
$filename = $file->getClientOriginalName();
$picture = date('His').'-'.$filename;
$file->move(public_path('storage/images/'), $picture);
array_push($uploadPicture, new PostImages(array('image' => 'images/'. $picture)));
}
$post->images()->saveMany($uploadPicture);
}
if ($request->input('contents')) {
$data['content'] = $request->contents;
}
//dd($data);
$post->update($data);
session()->flash('SUCCESS', 'تم تحديث الإعلان بنجاح.');
return redirect()->route('post.show', [$post->id, Post::slug($post->title)]);
}
In controller part:
$destinationPath = 'uploads';
$extension = Input::file('image')->getClientOriginalExtension();
var_dump($extension);
$fileName = rand(11111,99999).'.'.$extension;
Input::file('image')->move($destinationPath, $fileName);

Categories