I am coding a blog post, when i click add post the image from any folder is put into public/user/img/
How I delete it when i delete the whole table line? (click delete a post), please see the public function deletePost($id) below, I can delete the details (text) in a row but cannot delete the file in the folder.
Please help
public function deletePost($id){
$posts = Post::where('id',$id);
$posts->delete();
return back()->with('delete_posts_success','Deleted!');
}
public function getAddPost() {
return view('admin.publish');
}
public function postAddPost(Request $request) {
$post = $request->all();
$post = new Post;
$post->title = $request->title;
$post->author = $request->author;
$post->content = $request->content;
$post->intro = $request->intro;
$post->type = $request->type;
if($request->hasFile('image')) {
$file = $request->file('image');
$extension = $file->getClientOriginalExtension();
if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg') {
return back()->with('Error', 'File extension must be jpg, png, jpeg');
}
$imageName = $file->getClientOriginalName();
$file->move("user/img", $imageName);
$post->image = $imageName;
} else {
$imageName = null;
}
$post->save();
return back()->with('create_posts_success','Published!');
}
you must be saving filename in database somewhere for this uploaded post
now when you delete that post,
-> get the name of the file from your db record,
-> check if the file exists at the location using file_exists()
-> delete the found file using unlink()
-> get file deletion response (true|false)
in your case, it becomes something like below
$filePathName = 'user/img/' . $post->image;
if( file_exists($filePathName) ){
unlink($filePathName);
}
ignore my syntax mistakes please
Done
Related
Hello I am a newbie, I just started creating a project for quiz application.I have repeated code in my store and update
function,how can i reduce the duplication and write a cleaner code, any help will be appreciated
Thanks Nabeel
This is my store method
public function store(Quiz $quiz, QuestionRequest $request)
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
//$path = $file->storeAs('app/img/',$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
This is my update method
public function update(Quiz $quiz,QuestionRequest $request,Question $question)
{
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
elseif(!empty($question->imgpath) && $request->hasfile('image'))
{
$file=$request->file('image');
$fileWithExt = $file->getClientOriginalName();
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$nameoffile = $filename.'_'.time().'.'.$extension;
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=$question->imgpath;
}
You can create a new trait or function in your model class and can use that in your controller . Like this
In your Quiz.php just create a new function called fileUpload()
php artisan fileUpload($data)
{
$file=$data;
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
return $path;
}
And in your controller in store() and update() you can just do this
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$path = $quiz->fileUpload($request->file('image'));
}
else
{
$path=null;
}
}
I am new in Laravel and I develop a web application where someone can upload a car ad and other users can write comments bellow that. Instead of developing a simple CRUD application I thought about developing also a table that will be related to these ads and will store the photos. Up to this point, I have made the relations, I can show images and I have two problems: The first problem is that not all images are moved to storage/photos folder and the second problem is that all the records in the database have the same name. For example, if I want to upload images 1,2,3 then in the database all the files will have the name 1.
Bellow, you may find the store code. This code stores all the ads and also the images if they exist.
public function store(Request $request)
{
//
$this->validate($request, [
'name' => 'required',
'cc' => 'required',
'desc' => 'required',
'date' => 'required'
]);
$ad = new Ad;
$ad->name = $request->input('name');
$ad->cc = $request->input('cc');
$ad->desc = $request->input('desc');
$ad->date = $request->input('date');
$ad->user_id = auth()->user()->id;
$ad->save();
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
if ($check) {
foreach ($request->photos as $photo) {
$photo->move('storage/photos', $filename);
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
return redirect('/home')->with('success', 'ad + image created');
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
}
return redirect('/home')->with('success','ad created');
}
Thank you in advance!
1st mistake, you did looping twice
2nd mistake (you might not realize this) you didnt merge the filename and extension, this will cause an issue when you retrieving the image in blade
therefore correction on your code plus comment to explain it
if ($request->hasFile('photos')) {
$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = $request->file('photos');
foreach ($files as $file) {
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
//$file->move('storage/photos', $filename);
$check = in_array($extension, $allowedfileExtension);
$fullpath = $filename . '.' . $extension ; // adding full path
if ($check) {
// removing 2nd loop
$file->move('storage/photos', $fullpath); // you should include extension here for retrieving in blade later
$img = new AdsPhoto;
$img->ad_id = $ad->id;
$img->filename = $filename;
$img->save();
}
} else {
echo '<div class="alert alert-warning"><strong>Warning!</strong> Sorry Only Upload png , jpg , doc</div>';
}
}
return redirect('/home')->with('success', 'ad + image created');
}
From the documentation, if you want to put your file on storage instead of on public folder you need to put these few lines of code as below in the your controller class
<?php
...
use Illuminate\Support\Facades\Storage;
...
class YourController extends Controller{
...
// Automatically generate a unique ID for file name...
Storage::putFile('photos', new File('/path/to/photo'));
...
}
This command will put your file into storage folder
Using the below code, it should upload to the path specified in $path but for some reason, it saves the links to all pictures to c:\xampp\tmp with the .tmp extension but will move them to the correct folder anyway. What have I done wrong?
public function store(Request $request){
//
if($file = $request->file('image')){
$name = $file->getClientOriginalName();
$path = 'public/images';
if($file->move($path, $name)){
$post = new Gallery();
$post->image = $request->image;
$post->name = $request->name;
$post->species_id = $request->species_id;
$post->tag = $request->tag;
$post->patreon = $request->tag;
$post->save();
return redirect()->route('admin.gallery.index');
};
};
}
I want to edit the the blog form in Laravel. All other text information like Title, Body are successfully edited. But Image could not be updated. New image is not uploaded and image path is set as C:\xampp\tmp\php2030.tmp.
My Controller for edit.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$post->update($requestData);
if ($request->hasFile('image'))
{
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
$image = '/images/'.$fileNameToStore;
$post->save();
}
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
What is wrong with it?
When PHP receives a file upload, by default it writes it to a temporary directory like you're getting, and automatically deletes the file after the request has been handled.
What you need to do is move the uploaded file to a safe location.
Laravel 5.5 has a store method for file uploads that might be of interest.
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
if ($request->hasFile('image')) {
$file = $request->file('image');
$fileNameExt = $request->file('image')->getClientOriginalName();
$fileNameForm = str_replace(' ', '_', $fileNameExt);
$fileName = pathinfo($fileNameForm, PATHINFO_FILENAME);
$fileExt = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $fileName.'_'.time().'.'.$fileExt;
$pathToStore = public_path('media');
Image::make($file)->resize(600, 531)->save($pathToStore . DIRECTORY_SEPARATOR. $fileNameToStore);
// UPDATE TEMPORARY IMAGE PATH WITH ACTUAL PATH
$requestData['image'] = "/media/{$fileNameToStore}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Please, use the code below:
public function update(Request $request, $id)
{
$requestData = $request->all();
$post = Post::findOrFail($id);
$pathToStore = public_path('media');
if ($request->hasFile('image'))
{
$file = $request->file('image');
$rules = array('file' => 'required|mimes:png,gif,jpeg'); // 'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
if($validator->passes())
{
$filename = $file->getClientOriginalName();
$extension = $file -> getClientOriginalExtension();
$picture = sha1($filename . time()) . '.' . $extension;
$upload_success = $file->move($pathToStore, $picture);
if($upload_success)
{
//if success, create thumb
$image = Image::make(sprintf($pathToStore.'/%s', $picture))->resize(600, 531)->save($pathToStore.'/thumb/'.$picture);
}
}
$requestData['image'] = "$pathToStore/{$picture}";
}
$post->update($requestData);
session()->flash('message', 'Successfully updated the post');
return redirect('/');
}
Any best way to do this will be gratefull
what this do is grab the input from a form and save it to the database.
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
// $extension =$file->getClientOriginalExtension();
$upload_success = Input::file('path')->move($destinationPath, $filename);
$photo = Photo::find($_POST['id']);
$photo->caption = $_POST['caption'];
$photo->path = $destinationPath . $filename;
$photo->save();
if( $upload_success ) {
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
} else {
return Response::json('error', 400);
}
}
this work just fine but i wonder if there a simplify way to do this like how i can get post data from the form send to update to update the photo information instead of me using the $_POST and get the id from the form parse into the update($id) ect. Thanks
You can use the Input class, instead of accessing the post directly.
I would probably re-write the function a little like this:
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
if( Input::file('path')->move($destinationPath, $filename) )
{
$photo = Photo::find(Input::get('id'));
$photo->caption = Input::get('caption');
$photo->path = $destinationPath . $filename;
$photo->save();
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
}
else
{
return Response::json('error', 400);
}
}
The other option is to extract some of this data directly into your Photo model, and do it in there.