image upload (move) does not work on laravel - laravel

public function store(Request $request)
{
$request->merge(['slug' => Str::slug($request->baslik), 'user_id' => auth()->user()->id, 'hit' => 0 ]);
$add = Ilan::create($request->post());
$insertedId = $add->id;
if($files=$request->file('images')){
foreach($files as $file){
$photo = new Photo;
$name=rand(0,4000).'-'.Str::slug($request->baslik).'-'.$file->getClientOriginalName();
$file->move(public_path('uploads'),$name);
$photo->ilan_id = $insertedId;
$photo->url = 'uploads/'.$name;
$photo->save();
}
}
return redirect()->route('ilan.index');
}
This is my function. It's working in Local. But when I try it in a server it's not working. Image is not creating and there is no error. Where is the problem, if you help me i will be glad, thank you.
My public folder is: sample.com/references/website
I didnt send public folder to the main folder

you public directory named something else instead of public inside your hosting that is why you are facing that issue ..
follow that link for solving the issue this link is for laravel 5
for laravel 8 you can check that link

Related

Test upload file with laravel 8, assertExists not working

I'm testing upload the files with laravel 8.
My Controller
public function store(Request $request)
{
$path = $request->file('file')->store('uploads');
return $path;
}
My test code
/** #test */
public function check_file_can_be_uploaded()
{
Storage::fake('uploads');
$file = UploadedFile::fake()->image('document.pdf', 300);
$data = Contact::factory()->make([
'file' => $file
])->toArray();
$response = $this->post(route('contact.store'), $data);
Storage::disk('uploads')->assertExists($file->hashName());
}
I see the file in storage folder, but phpunit return Unable to find a file at path [08cnFo56Ce8RIBCwUh7eY8hTZxvdv6atMBdozSaH.pdf].
Failed asserting that false is true.
Where am I going wrong?
I'm having the same issue, as a work around I've used the following:
self::assertFileExists(storage_path('app/public/1/' . $file->hashName()));
Your experience may diff as to the path where it stores the file

Laravel unlink doesn't delete the file [duplicate]

I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder.
So, how do I this to work.
thanks
This is my function again but does not delete the image from images/news folder of public directory>
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/{$news->photo}");
if (File::exists($image_path)) {
//File::delete($image_path);
unlink($image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
You could use PHP's unlink() method just as #Khan suggested.
But if you want to do it the Laravel way, use the File::delete() method instead.
// Delete a single file
File::delete($filename);
// Delete multiple files
File::delete($file1, $file2, $file3);
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
And don't forget to add at the top:
use Illuminate\Support\Facades\File;
Use the unlink function of php, just pass exact path to your file to unlink function :
unlink($file_path);
Do not forget to create complete path of your file if it is not stored in the DB. e.g
$file_path = app_path().'/images/news/'.$news->photo;
this method worked for me
First, put the line below at the beginning of your controller:
use File;
below namespace in your php file
Second:
$destinationPath = 'your_path';
File::delete($destinationPath.'/your_file');
$destinationPath --> the folder inside folder public.
This worked at laravel 8
use File;
if (File::exists(public_path('uploads/csv/img.png'))) {
File::delete(public_path('uploads/csv/img.png'));
}
First, you should go to config/filesystems.php and set 'root' => public_path() like so:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path(),
],
Then, you can use Storage::delete($filename);
Update working for Laravel 8.x:
Deleting an image for example ->
First of all add the File Facade at the top of the controller:
use Illuminate\Support\Facades\File;
Then use delete function. If the file is in 'public/' you have to specify the path using public_path() function:
File::delete(public_path("images/filename.png"));
Using PHP unlink() function, will have the file deleted
$path = public_path()."/uploads/".$from_db->image_name;
unlink($path);
The above will delete an image returned by $from_db->image_name located at public/uploads folder
Try to use:
unlink('.'.Storage::url($news->photo));
Look the dot and concatenation before the call of facade Storage.
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/".$news->photo);
if(file_exists($image_path)){
//File::delete($image_path);
File::delete( $image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
First make sure the file exist by building the path
if($request->hasFile('image')){
$path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image;
if(File::exists($path)){
unlink($path);
}
Try it :Laravel 5.5
public function destroy($id){
$data = User::FindOrFail($id);
if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){
unlink('backend_assets/uploads/userPhoto/'.$data->photo);
}
try{
$data->delete();
$bug = 0;
}
catch(\Exception $e){
$bug = $e->errorInfo[1];
}
if($bug==0){
echo "success";
}else{
echo 'error';
}
}
the easiest way for you to delete the image of the news is using the model event like below
and the model delete the image if the news deleted
at first you should import this in top of the model class use Illuminate\Support\Facades\Storage
after that in the model class News you should do this
public static function boot(){
parent::boot();
static::deleting(function ($news) {
Storage::disk('public')->delete("{$news->image}");
})
}
or you can delete the image in your controller with
this command
Storage::disk('public')->delete("images/news/{$news->file_name}");
but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name
This is the way I upload the file and save it into database and public folder and also the method I delete file from database and public folder.
this may help you and student to get complete source code to get the task done.
uploading file
at the first if you save file into database by giving path public_path() once it not need to used in delete method again
public function store_file(Request $request)
{
if($request->hasFile('file'))
{
$fileExtention = $request->file('file')->getClientOriginalExtension();
$name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
$filePath = $request->file('file')->move(public_path().'/videos',$name);
$video = new Video_Model;
$video->file_path = $filePath;
$video->filename = $request->filename;
$video->save();
}
return redirect()->back();
}
deleting file
from database and public folder as you saved
public function delete_file(Request $request)
{
$file = Video_Model::find($request->id);
$file_path = $file->file_path;
if(file_exists($file_path))
{
unlink($file_path);
Video_Model::destroy($request->id);
}
return redirect()->back();
}
Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path))
{
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage
Hope that it will help someone.
For Delete files from the public folders, we can use the File::delete function into the Laravel. For use File need to use File into the controller OR We can use \File. This consider the root of the file.
// Delete a single file
File::delete($filename);
For delete Multiple files
// Delete multiple files
File::delete($file1, $file2, $file3);
Delete an array of Files
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:
Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
Use public storage directly:
Storage::disk('public')->delete($image_path);
I would suggest second way as the best one.
Hope this help other people.
If you store your image in folder public, try this steps:
For example your image is sample.jpg and your path is public/img/sample.jpg
so this codes will delete your image
use Illuminate\Support\Facades\File;
.
.
.
public function deleteImage(){
$imgWillDelete = public_path() . '/img/sample.jpg';
File::delete($imgWillDelete);
}
Follow the steps carefully to get the image first=>
$img = DB::table('students')->where('id',$id)->first();
$image_path = $img->photo;
unlink($image_path);
DB::table('students')->where('id',$id)->delete();
For delete file from folder you can use unlink and if you want to delete data from database you can use delete() in laravel
Delete file from folder
unlink($image_path);
For delete record from database
$flight = Flight::find(1);
$flight->delete();
public function update(Request $request, $id)
{
$article = Article::find($id);
if($request->hasFile('image')) {
$oldImage = public_path($article->image);
File::delete($oldImage);
$fileName = time().'.'.$request->image->extension();
$request->image->move(public_path('uploads/'), $fileName);
$image ='uploads/'.$fileName;
$article->update([
'image' => $image,
]);
}
$article->update([
'title' => $request->title,
'description' => $request->description,
]);
return redirect()->route('admin.article.index');
}
you can delete file and its record like wise:
public function destroy($id)
{
$items = Reports::find($id); //Reports is my model
$file_path = public_path('pdf_uploads').'/'.$items->file; // if your file is in some folder in public directory.
// $file_path = public_path().'/'.$items->file; use incase you didn't store your files in any folder inside public folder.
if(File::exists($file_path)){
File::delete($file_path); //for deleting only file try this
$items->delete(); //for deleting record and file try both
}
return redirect()->back()->with('message','client code: '.$items->receipt_no.' report details has been successfully deleted along with files');
}
note: items->file is my attribute in database where I have stored the name of the file like so,
I have stored the file in the directory "public/pdf_uploads/filename"
Don't forget to add this in your header
use Illuminate\Support\Facades\File;
For File Syntax:
if(File::exists(public_path('upload/test.png'))){
File::delete(public_path('upload/test.png'));
}else{
dd('File does not exists.');
}
For Storage Syntax:
if(Storage::exists('upload/test.png')){
Storage::delete('upload/test.png');
/*
Delete Multiple File like this way
Storage::delete(['upload/test.png', 'upload/test2.png']);
*/
}else{
dd('File does not exists.');
}
Common Method is :
#unlink('/public/admin/pro-services/'.$task->pro_service_image);

update profile in laravel API for mobile apps

I want to build an api for mobile apps. for now, i want to create an edit profile api. but i dont know how to store an image, if user wants to upload their avatar.
Here is my code:
public function profileedit($id, Request $request){
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar;
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>$users->thumbnail,
'status'=>200,
];
return response()->json($data);
}
how to put the $request->avatar into my project storage, and show it in url form (my project is already uploaded on the server)
The easiest way to store files in Laravel is this.
use Illuminate\Support\Facades\Storage;
public function profileedit($id, Request $request){
//validator place
$users = user::find($id);
$users->name = $request->firstName;
$users->thumbnail = $request->avatar->store('avatars','public');
$users->save();
$data[] = [
'id'=>$users->uid,
'name'=>$users->name,
'avatar'=>Storage::url($users->thumbnail),
'status'=>200,
];
return response()->json($data);
}
but as you probably know, you should run php artisan storage:link command to generate storage shortcut in public directory.
for security reason you can use validator to let only image file store. in this example I limited file to all image types with maximum 4MB size
$request->validate([
'avatar' => 'required|image|max:4096',
]);
for more information these are document links.
File Storage
Validation

deleteFileAfterSend Laravel response doesn't delete file in tests

I an have laravel 5.5 App.
I'm trying to make a test for download PDF with laravel snappy.
So far I have in my CheckTest.php one function:
public function testPrintCheck(){
$check = $this->createCheck();
$route ="/api/checks/print/$check->id";
$response = $this->get($route);
$this->assertEquals($response->headers->get('content-type') , 'application/pdf');
$response->assertStatus(200);
}
In my controller I have:
public function printCheck(Request $request, Check $check){
$pdf = \PDF::loadView("pdf.check");
$file= storage_path(). "/app/checks/$check->id.pdf";
$pdf->save($file);
$headers = array(
'Content-Type: application/pdf'
);
return response()->download($file, "check_n_$check->id.pdf", $headers)->deleteFileAfterSend(true)->setStatusCode(200);
}
The current test works but I expect to delete file that I have create after download (with deleteFileAfterSend(true)) , but the file is not deleted.
So if I add the assert that file not exist it fails.
There is a possible solution to this according to the issue created not so long ago on github:
https://github.com/laravel/framework/issues/36286
Working on Laravel 8.24
Basically we need to force sending file contents, which then triggers file deletion
public function test(): void
{
$response = $this->get('url/to/download');
// Here the file is not deleted yet
$response->sendContent();
// Here the file is deleted
}

How to delete file from public folder in laravel 5.1

I want to delete a News from database and when I hit the delete button all data from database deleted but the image is remains in upload folder.
So, how do I this to work.
thanks
This is my function again but does not delete the image from images/news folder of public directory>
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/{$news->photo}");
if (File::exists($image_path)) {
//File::delete($image_path);
unlink($image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
You could use PHP's unlink() method just as #Khan suggested.
But if you want to do it the Laravel way, use the File::delete() method instead.
// Delete a single file
File::delete($filename);
// Delete multiple files
File::delete($file1, $file2, $file3);
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
And don't forget to add at the top:
use Illuminate\Support\Facades\File;
Use the unlink function of php, just pass exact path to your file to unlink function :
unlink($file_path);
Do not forget to create complete path of your file if it is not stored in the DB. e.g
$file_path = app_path().'/images/news/'.$news->photo;
this method worked for me
First, put the line below at the beginning of your controller:
use File;
below namespace in your php file
Second:
$destinationPath = 'your_path';
File::delete($destinationPath.'/your_file');
$destinationPath --> the folder inside folder public.
This worked at laravel 8
use File;
if (File::exists(public_path('uploads/csv/img.png'))) {
File::delete(public_path('uploads/csv/img.png'));
}
First, you should go to config/filesystems.php and set 'root' => public_path() like so:
'disks' => [
'local' => [
'driver' => 'local',
'root' => public_path(),
],
Then, you can use Storage::delete($filename);
Update working for Laravel 8.x:
Deleting an image for example ->
First of all add the File Facade at the top of the controller:
use Illuminate\Support\Facades\File;
Then use delete function. If the file is in 'public/' you have to specify the path using public_path() function:
File::delete(public_path("images/filename.png"));
Using PHP unlink() function, will have the file deleted
$path = public_path()."/uploads/".$from_db->image_name;
unlink($path);
The above will delete an image returned by $from_db->image_name located at public/uploads folder
Try to use:
unlink('.'.Storage::url($news->photo));
Look the dot and concatenation before the call of facade Storage.
public function destroy($id) {
$news = News::findOrFail($id);
$image_path = app_path("images/news/".$news->photo);
if(file_exists($image_path)){
//File::delete($image_path);
File::delete( $image_path);
}
$news->delete();
return redirect('admin/dashboard')->with('message','خبر موفقانه حذف شد');
}
First make sure the file exist by building the path
if($request->hasFile('image')){
$path = storage_path().'/app/public/YOUR_FOLDER/'.$db->image;
if(File::exists($path)){
unlink($path);
}
Try it :Laravel 5.5
public function destroy($id){
$data = User::FindOrFail($id);
if(file_exists('backend_assets/uploads/userPhoto/'.$data->photo) AND !empty($data->photo)){
unlink('backend_assets/uploads/userPhoto/'.$data->photo);
}
try{
$data->delete();
$bug = 0;
}
catch(\Exception $e){
$bug = $e->errorInfo[1];
}
if($bug==0){
echo "success";
}else{
echo 'error';
}
}
the easiest way for you to delete the image of the news is using the model event like below
and the model delete the image if the news deleted
at first you should import this in top of the model class use Illuminate\Support\Facades\Storage
after that in the model class News you should do this
public static function boot(){
parent::boot();
static::deleting(function ($news) {
Storage::disk('public')->delete("{$news->image}");
})
}
or you can delete the image in your controller with
this command
Storage::disk('public')->delete("images/news/{$news->file_name}");
but you should know that the default disk is public but if you create folder in the public folder and put the image on that you should set the folder name before $news->file_name
This is the way I upload the file and save it into database and public folder and also the method I delete file from database and public folder.
this may help you and student to get complete source code to get the task done.
uploading file
at the first if you save file into database by giving path public_path() once it not need to used in delete method again
public function store_file(Request $request)
{
if($request->hasFile('file'))
{
$fileExtention = $request->file('file')->getClientOriginalExtension();
$name = time().rand(999,9999).$request->filename.'.'.$fileExtention;
$filePath = $request->file('file')->move(public_path().'/videos',$name);
$video = new Video_Model;
$video->file_path = $filePath;
$video->filename = $request->filename;
$video->save();
}
return redirect()->back();
}
deleting file
from database and public folder as you saved
public function delete_file(Request $request)
{
$file = Video_Model::find($request->id);
$file_path = $file->file_path;
if(file_exists($file_path))
{
unlink($file_path);
Video_Model::destroy($request->id);
}
return redirect()->back();
}
Its a very old thread, but I don't see that the solution is here or the this thread is marked as solved. I have also stuck into the same problem I solved it like this
$path = public_path('../storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME');
if (!File::exists($path))
{
File::delete(public_path('storage/YOUR_FOLDER_NAME/YOUR_FILE_NAME'));
}
The key is that you need to remove '..' from the delete method. Keep in mind that this goes true if you are using Storage as well, whether you are using Storage of File don't for get to use them like
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use File; // For File
use Storage; // For Storage
Hope that it will help someone.
For Delete files from the public folders, we can use the File::delete function into the Laravel. For use File need to use File into the controller OR We can use \File. This consider the root of the file.
// Delete a single file
File::delete($filename);
For delete Multiple files
// Delete multiple files
File::delete($file1, $file2, $file3);
Delete an array of Files
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
Two ways to delete the image from public folder without changing laravel filesystems config file or messing with pure php unlink function:
Using the default local storage you need to specify public subfolder:
Storage::delete('public/'.$image_path);
Use public storage directly:
Storage::disk('public')->delete($image_path);
I would suggest second way as the best one.
Hope this help other people.
If you store your image in folder public, try this steps:
For example your image is sample.jpg and your path is public/img/sample.jpg
so this codes will delete your image
use Illuminate\Support\Facades\File;
.
.
.
public function deleteImage(){
$imgWillDelete = public_path() . '/img/sample.jpg';
File::delete($imgWillDelete);
}
Follow the steps carefully to get the image first=>
$img = DB::table('students')->where('id',$id)->first();
$image_path = $img->photo;
unlink($image_path);
DB::table('students')->where('id',$id)->delete();
For delete file from folder you can use unlink and if you want to delete data from database you can use delete() in laravel
Delete file from folder
unlink($image_path);
For delete record from database
$flight = Flight::find(1);
$flight->delete();
public function update(Request $request, $id)
{
$article = Article::find($id);
if($request->hasFile('image')) {
$oldImage = public_path($article->image);
File::delete($oldImage);
$fileName = time().'.'.$request->image->extension();
$request->image->move(public_path('uploads/'), $fileName);
$image ='uploads/'.$fileName;
$article->update([
'image' => $image,
]);
}
$article->update([
'title' => $request->title,
'description' => $request->description,
]);
return redirect()->route('admin.article.index');
}
you can delete file and its record like wise:
public function destroy($id)
{
$items = Reports::find($id); //Reports is my model
$file_path = public_path('pdf_uploads').'/'.$items->file; // if your file is in some folder in public directory.
// $file_path = public_path().'/'.$items->file; use incase you didn't store your files in any folder inside public folder.
if(File::exists($file_path)){
File::delete($file_path); //for deleting only file try this
$items->delete(); //for deleting record and file try both
}
return redirect()->back()->with('message','client code: '.$items->receipt_no.' report details has been successfully deleted along with files');
}
note: items->file is my attribute in database where I have stored the name of the file like so,
I have stored the file in the directory "public/pdf_uploads/filename"
Don't forget to add this in your header
use Illuminate\Support\Facades\File;
For File Syntax:
if(File::exists(public_path('upload/test.png'))){
File::delete(public_path('upload/test.png'));
}else{
dd('File does not exists.');
}
For Storage Syntax:
if(Storage::exists('upload/test.png')){
Storage::delete('upload/test.png');
/*
Delete Multiple File like this way
Storage::delete(['upload/test.png', 'upload/test2.png']);
*/
}else{
dd('File does not exists.');
}
Common Method is :
#unlink('/public/admin/pro-services/'.$task->pro_service_image);

Resources