I want to use Intervention Image library for my Laravel project, so I just installed it via Composer and added this line of code to config/app.php:
Intervention\Image\ImageServiceProvider::class,
And also this line was added to aliases part:
'Image' => Intervention\Image\Facades\Image::class,
Now at my Controller I coded this:
class AdminController extends Controller
{
protected function uploadImages($file)
{
$year = Carbon::now()->year;
$imagePath = "/upload/images/{$year}/";
$filename = $file->getClientOriginalName();
$file = $file->move(public_path($imagePath), $filename);
$sizes = ["300","600","900"];
Image::make($file->getRealPath())->resize(300,null,function($constraint){
$constraint->aspectRatio();
})->save(public_path($imagePath . "300_" . $filename));
}
}
But as soon as I fill my form to check if it's work or not, this error message pops up:
Error
Class 'App\Http\Controllers\Admin\Image' not found
Which means this line:
Image::make($file->getRealPath())->resize(300,null,function($constraint){
So why it returns this error while I've included it already in my project ?!
If you know, please let me know... I would really appreciate that.
Thanks
On config/app.php you need to add :
$provides => [
Intervention\Image\ImageServiceProvider::class
],
And,
$aliases => [
'Image' => Intervention\Image\Facades\Image::class
]
Now you can call use Image; on the top on your controller :
use Image;
class AdminController extends Controller
{
// ...
}
Related
how to generate and download images in storage using laravel's faker?
I want when running seeders to download images and save them automatically in the storage/categories folder, but when running seeder the images are downloaded all for a second and then they disappear or are deleted, so I don't know what is happening.
this is CategoryFactory
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class CategoryFactory extends Factory
{
public function definition()
{
return [
'image' => 'categories/' . $this->faker->image(storage_path('app' . DIRECTORY_SEPARATOR . 'public/categories'),640, 480, null, false)
];
}
}
Storage::makeDirectory('categories') will create a directory at storage/app/categories if the driver is set to public. So when using with faker->image() the path needs to be storage_path('app/dummy').
'image' => 'categories/' . $this->faker->image(storage_path('app/categories'),640, 480, null, false)
I am creating a controller that saves photos to the /storage/ folder. To protect myself from submitting a bunch of large photos and not to style their CSS, I wanted to resize them using the Intervention / image library. Unfortunately, despite following the installation instructions directly from the documentation, several uninstallations and reinstallations of the library do not work. When I use this code snippet:
Use Image;
I get an error saying:
Undefined type 'Image'
Following the instructions, I added the following to /config/app.php:
'providers' => [
...
Intervention\Image\ImageServiceProvider::class,
],
'aliases' => [
...
'Image' => Intervention\Image\Facades\Image::class,
...
],
Besides, I cleaned and reconfigured the cache and config, restarted the server, tried to use:
use Intervention\Image\ImageManagerStatic as Image;
But unfortunately that didn't help either.
What am I doing wrong?
You have to use the namespace below
use Intervention\Image\Facades\Image;
Then you can use like-
$image = $request->file('image');
$ext = $image->getClientOriginalExtension();
$img = Image::make($image)->resize(300, 200)->save('storage/folder/filename'.'.'.$ext);
Use Image facade directly
\Intervention\Image\Facades\Image::make(\File::get($file_address))
->fit($width, $height)
->save($path_for_saving);
You can fit or crop the image based on your needs.
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
public function imageUploadPost(Request $request)
{
$photo = $request->file('image');
$imagename = time() . '.' . $photo->getClientOriginalExtension();
// Upload Crop Image...
$destinationPath = public_path('uploads/thumbnail_images');
if (!File::isDirectory($destinationPath)) {
File::makeDirectory($destinationPath, 0777, true, true);
}
$thumb_img = \Intervention\Image\Facades\Image::make($photo->getRealPath())->resize(100, 100);
$thumb_img->save($destinationPath . '/' . $imagename, 100); // Define Quality 100 (Optional)
echo '<pre>';
print_r("Upload Successfully. Store File : laravel_project/public/uploads & laravel_project/public/uploads/thumbnail_images");
}
I'm trying to use Mailable in Laravel.
In developing a new Mailable, I have everything working except attaching an EXISTING file to the mailable.
An error returns as such:
"message": "Unable to open file for reading [/public/storage/shipments/CJ2K4u6S6uluEGd8spOdYgwNkg8NgLFoC6cF6fm5.pdf]",
"exception": "Swift_IoException",
"file": "E:\\webserver\\htdocs\\truckin\\vendor\\swiftmailer\\swiftmailer\\lib\\classes\\Swift\\ByteStream\\FileByteStream.php",
"line": 131,
But if you go through the folders and files, there is in fact a file there and I can open it, I can even open it through an ajax popup to view details.
Here is my mailable:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Shipment;
use App\Shipment_Attachment;
class shipmentAttachments extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* #return void
*/
public $shipment, $attachment, $storagePath;
public function __construct($shipment, $attachment, $storagePath)
{
$this->shipment = $shipment;
$this->attachment = $attachment;
$this->attachmentFile = '/public'.$storagePath;
$this->proNumber = $shipment->pro_number;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('billing#cmxtrucking.com')
->cc('billing#cmxtrucking.com')
->subject('New Attachment(s) - '. $this->proNumber)
->view('emails.shipments.shipmentAttachments',['shipment'=> $this->shipment])
->attach($this->attachmentFile);
}
}
And here is my controller that leads to the mailable:
public function attachmentsEmail(Request $request){
$shipment = Shipment::findOrFail($request->shipmentID);
$attachment = Shipment_Attachment::findOrFail($request->attachmentID);
$storagePath = Storage::url($attachment->attachmentPath);
$email = $request->email;
Mail::to($email)->send(new shipmentAttachments($shipment, $attachment, $storagePath)); //maybe try to use queue instead of send...
return back();
}
So I'm not sure where this could be coming from.
Try to use public_path() laravel helper function instead of '/public'.
$this->attachmentFile = public_path() . '/' . $storagePath;
Maybe you need to change this variable in public/index.php. I have right below the require bootstrap:
$app->bind('path.public', function() {
return __DIR__;
});
Make some tests.
dd(public_path());
dd(public_path() . '/' . $storagePath);
Or maybe verify if file exist with FileSystem class.
Hope this help you!
I was serching a lot about that, it happens the same when you are tryng to build a PDF on dompdf, just exactly the same, you normaly could write this:
('/image/'.$file) and will not work , so you can solve it adding a dot just behind the rout ".", just like this:
('./image/'.$file)
It works when you want to add a attach in a mail sending or when you want to make a PDF including images in it.
If you use Storage, and you are trying to export xlsx files, using Laravel Notifications:
in your notification class:
public function toMail($notifiable) {
$path = Storage::disk('export')->getAdapter()->getPathPrefix();
return (new MailMessage)
->greeting(language_data('Your file is ready', $this->user->language_id).$this->user->name)
->line(language_data('Please, check your Email attachments.', $this->user->language_id))
->subject(language_data('Export Contacts', $this->user->language_id))
->attach($path.$notifiable->filename, [ 'as' => $notifiable->filename, 'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ])
->line(language_data('If you did not request this file, please contact us.', $this->user->language_id));
}
It works fine for me.
Instead of /public we have to use laravel's helper function public_path()
then concatenate actual file path. otherwise the attachment file operation will not work
so your updated code should be like:-
$this->attachmentFile = public_path() . '/' . $storagePath;
Most of these errors occur in larval on Ubuntu (Linux).
It may be skipped in some cases of windows.
Here is my function to download the uploaded files:
public function download() {
$this->viewClass = 'Media';
$params = array(
'id' => 'article.pdf',
'name' => 'article',
'download' => true,
'extension' => 'pdf',
'path' => WWW_ROOT . DS . 'files' . DS
);
$this->set($params);
}
However calling this function results in the following error message:
Error: Media could not be found.
Error: Create the class Media below in file: src\View\Media.php
Any suggestions what is wrong with my code? Thanks in advance!
Any suggestions what is wrong with my code?
Yes:
Wrong CakePHP Version (3.x) for what you try to use
And even in 2.x Media view is deprecated since 2.3 as the documentation clearly states on top of the page: Deprecated since version 2.3: Use Sending files instead.
Read the documentation!
Taken from the link above:
public function sendFile($id)
{
$file = $this->Attachments->getFile($id);
$this->response->file($file['path']);
// Return response object to prevent controller from trying to render
// a view.
return $this->response;
}
And always put the exact CakePHP version you're using in your question.
Error: Create the class Media below in file: src\View\Media.php
Create file in
Path - src/View/
File Name - media.php
I am trying to include a custom defined validation file that is local to my system and wish to use it with 'package' files from an application I downloaded online. The purpose is so that I can have my own custom validators since I made modifications to this application.
I keep getting the error -> 'Class 'Models\Validators\Photo' not found'
Controller:
use JeroenG\LaravelPhotoGallery\Controllers\AlbumsController; /* From Package */
use JeroenG\LaravelPhotoGallery\Controllers\PhotosController; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Album; /* From Package */
use JeroenG\LaravelPhotoGallery\Models\Photo; /* From Package */
use Models\Validators as Validators; /* Custom local file */
class EditPhotosController extends PhotosController {
public function __construct()
{
parent::__construct();
}
public function update($albumId, $photoId)
{
$input = \Input::except('_method');
$validation = new Validators\Photo($input); // Here's where error occurs
/* Validation check and update code etc. */
}
}
}
Photo.php -> File path: Models\Validators\Photo.php
namespace Models\Validators;
class Photo extends Validator {
public static $rules = array(
'album_id' => 'required',
'photo_name' => 'required',
'photo_description' => 'max:255',
);
}
Is this just a simple namespacing issue?
The most likely problem is that composer doesn't add file Models/Validators/Photo.php to the autoload index. Make sure you have provided correct path for your files in composer.json.
Try running
composer dump-autoload
to regenerate the autoload files.