How do grant rw access to public folder in laravel - laravel

I get this error after i migrated my project from windows to mac.
The "/private/var/folders/6w/zypn4xb120l6x6f1kjx9_nxw0000gn/T/phpwroBVT" file does not exist or is not readable.
here is my code
if($request->hasFile('image')){
$image = $request->file('image');
$image_name = $image->getClientOriginalName();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $image_name);
$summary = $request->summary;
$body = $request->body;
$title = $request->title;
$service = Service::create([
'title'=> $title,
'summary'=>$summary,
'body'=>$body,
'image'=> $image
]
);
if($service){
return redirect()->back()->with('success','services added');
}
}
the images goes into the public/images/services folder but i get the above error

I faced the similar error and I found out that i was accessing the global variable declared in the controller without "this" pointer reference. For example
class BlogController extends Controller
{
public $attachment_folder_name = "/blogs/";
}
You should access this variable with following syntax.
echo $this->attachment_folder_name
And not like this
echo $attachment_folder_name

Related

Laravel download image

I have a function to add an image, and upon successful addition in the database, we have a path like public/images/asd.png. The question is how to make sure that when added to the name of the picture, an ID is added, and we have something like public/images/asd1.png, public/images/asd2.png, etc.
function in Model
public function getOriginImageUrl()
{
return $this->attributes['image'];
}
public function getImageAttribute($value)
{
return Storage::exists($value) ? Storage::url($value) : null;
}
function in Controller
if ($request->hasFile('image')) {
$file = $request->file('image');
$blog->image = $file->storeAs('public/images', $file->getClientOriginalName());
}
Instead of id you can combine time() with image name.
if ($request->hasFile('image')) {
$file = $request->file('image');
$namewithextension = $file->getClientOriginalName(); //Name with extension 'filename.jpg'
$name = explode('.', $namewithextension)[0]; // Filename 'filename'
$extension = $file->getClientOriginalExtension(); //Extension 'jpg'
$uploadname = $name. '-' .time() . '.' . $extension;
$blog->image = $file->storeAs('public/images', $uploadname);
}

Updating an image in laravel does not save to DB, only saves when adding new record

I have the form of a service where a name, description, and photo is required. When adding a new service the form works fine, everything is saved in the database.
Problem is when I want to change the photo and upload a new one its not working.
**Here is my controller method **, for both adding and updating service
public function post(ServiceRequest $request, Service $service)
{
$service = Service::firstOrNew(['id' => $request->get('id')]);
$service->id = $request->get('id');
$service->name = $request->get('name');
$service->description = $request->get('description');
$image = $request->file('photo')->store('services/');
$service->photo = $image;
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$name = time() . $service->name . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $name);
}
if ($request->has('photo')) {
$image = $request->file('photo');
}
$service->save();
Alert::success('Service Saved');
return redirect()->back();
// dd($service);
}
I need some assistance with updating the image and removing an old one that was added on update record.

Creating default object from empty value "error in laravel"

Hi I'm working on update products form of e-commerce site but when I try to edit details then it shows error "Undefined variable: fileName" and error line is:
Product::where(['id'=>$id])->
update(['product_name'=>$data['product_name'],
'product_code'=>$data['product_ code'],
'product_color'=>$data['product_color'],
'description'=>$data['description'],
'price'=>$data['price'],'image'=>$fileName]);
return redirect()->back()->with('flash_message_success','Product
updated successfully!');
or when i try to update image only then its error is: "Creating default object from empty value", or error line is:
$product->image = $filename;
this is code of ProductsController:
public function editProduct(Request $request, $id=null){
if($request->isMethod('post')){
$data = $request->all();
//echo "<pre>"; print_r($data); die;
if($request->hasFile('image')){
$image_tmp = Input::file('image');
if($image_tmp->isValid()){
$extension = $image_tmp->getClientOriginalExtension();
$filename = rand(111,99999).'.'.$extension;
$large_image_path =
'images/backend_images/products/large/'.$filename;
$medium_image_path =
'images/backend_images/products/medium/'.$filename;
$small_image_path =
'images/backend_images/products/small/'.$filename;
// Resize Images
Image::make($image_tmp)->save($large_image_path);
Image::make($image_tmp)->resize(600,600)->save($medium_image_path);
Image::make($image_tmp)->resize(300,300)->save($small_image_path);
// Store image name in products table
$product->image = $filename;
}
}
if(empty($data['description'])){
$data['description'] = '';
}
Product::where(['id'=>$id])-
>update(['product_name'=>$data['product_name'],
'product_code'=>$data['product_code'],
'product_color'=>$data['product_color'],
'description'=>$data['description'],
'price'=>$data['price'],'image'=>$fileName]);
return redirect()->back()->with('flash_message_success','Product
updated successfully!');
}
//Get product details
$productDetails = Product::where(['id'=>$id])->first();
return view('admin.products.edit_product')-
>with(compact('productDetails'));
}
"Undefined variable: fileName"
There's a typo in your variable. Change $fileName to $filename.
i guess you need to do something like this
$product=new Product();
$product->image = $filename;
also where did you define $fileName in your code?

Cannot use object of type Illuminate\Http\UploadedFile as array

I try to send attachement files but i get
Cannot use object of type Illuminate\Http\UploadedFile as array
I use laravel 5.4
Someone know why i'm getting this error ?
( I don't upload the file into a directory, i just want to send the file who was requested on my controller )
Hope someone could help , best regards :)
Here my controller :
public function postSendMassive(Request $request){
$files = $request->file('uploads');
$emails = Structure::where('type_structure_id', 4)->pluck('adresse_email_structure');
$subject = $request->subject;
$bodyMessage = $request->texte;
foreach($files as $file) {
$files[] = [
'file' => $file->getRealPath(),
'options' => [
'mime' => $file->getClientMimeType(),
'as' => $file->getClientOriginalName()
],
];
}
Mail::to('test#gmaIL.com')->send(new MassiveEmail($subject , $bodyMessage , $files));
return back()->with('status', "Email envoyé");
}
here my build mail :
public function build()
{
$subject = $this->subject;
$bodyMessage = $this->bodyMessage;
$files = $this->files;
$email = $this->markdown('email.MassiveMail',compact('bodyMessage'))
->subject($subject.'-'.'FFRXIII Licences & Compétitions');
foreach($this->files as $file) {
$email->attach($file['file'],$file['options']);
}
return $email;
}
This is because $request->file('uploads') returns an object and you're trying iterate over it with foreach
If you want to upload multiple files, make sure you're doing something like this:
<input type="file" name="uploads[]" multiple />
And iterate over uploaded files:
foreach ($request->uploads as $file)
This works!
if($request->hasFile('files')){
foreach ($request->files as $file) {
//get file name with extenstion
$fileNameWithExt = $file->getClientOriginalName();
//get just filename
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $file->getClientOriginalExtension();
//file to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload to store
$path = $file->storeAs('${your_storage_path}', $fileNameToStore);
}
}

Download File doesnt work

Im trying to create a download file functionality, but it doesnt work, it gives me a error of:
"The file "/storage/app/candidates/cvs/3/1493594353.pdf" does not exist", but im just looking at the file, and is there.
Am i missing something?
Note: im using laravel 5.4
File structure:
storage
- app
-- candidates
---cvs
----3
-----1493594353.pdf
- public
Route:
Route::post('candidate/cv/download-cv/','CurriculumVitaeController#downloadCV');
Controller:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = Storage::url('app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv);
$headers = ['Content-Type: application/pdf'];
$newName = 'cv-'.time().'.pdf';
return response()->download($path, $newName, $headers);
}
Change your controller download method to this:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = storage_path().'/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv;
$headers = ['Content-Type: application/pdf'];
$newName = 'cv-'.time().'.pdf';
return response()->download($path, $newName, $headers);
}
Also, to make things more dynamic, you could assign the Content-type and the returned file name extension on the fly, like this:
public function downloadCV()
{
$candidate = Candidate::where('user_id',Auth::user()->id)->first();
$candidateCv = CandidateCv::where('candidate_id',$candidate->id)->first();
$path = storage_path().'/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv;
$headers = ['Content-Type: '.Storage::mimeType('/app/candidates/cvs/'.$candidate->id.'/'.$candidateCv->cv)];
$newName = 'cv-'.time().'.'.pathinfo($path, PATHINFO_EXTENSION);
return response()->download($path, $newName, $headers);
}

Resources