Reputation: 61
I'm doing a project on Laravel 7 with FakerPHP, I want to populate my database with some random images and at the same time saving them on my local storage folder, but they can't get stored in the folder and I don't know why.
Here's my seeder:
for ($i=0; $i<20; $i++) {
$newApartment = new Apartment();
$newApartment->image = $faker->image('public/storage/images',300, 300);
$newApartment->save();
};
I want them to get stored on /images
, but when I run the seeder no images is saved and when I check on my database all that appears is 0
on the image
column.
The storage works fine, I have no problems when uploading images directly from the site.
I really don't know what I'm missing here, given that not a single error occurs and the seeding proceeds just fine.
Upvotes: 3
Views: 3793
Reputation: 191
I modified the standard faker and use another photo service:
namespace App\Helpers;
use Faker\Factory;
use Illuminate\Support\Facades\File;
class Image
{
/**
* Generates a URL that will return an accidental image.
*
* @param integer $width Image width.
* @param integer $height Image height.
* @param bool $randomizeColors Random colors.
* @param bool $randomizeTxt Random one word.
* @param string $format Image format (jpg|png|gif).
* @return string
*/
public static function imageUrl(
int $width = 640,
int $height = 480,
bool $randomizeColors = false,
bool $randomizeTxt = false,
string $format = 'jpg'
): string
{
$baseUrl = "https://dummyimage.com";
$size = "/{$width}x{$height}";
$colors = "/aaa/fff";
$format = '.' . preg_replace('~^\b(?:jpg|png|gif)$~', '.jpg', $format);
if ($randomizeColors) {
$backgroundColor = str_replace('#', '', Factory::create()->safeHexColor);
$foreColor = str_replace('#', '', Factory::create()->safeHexColor);
$colors = "/{$backgroundColor}/{$foreColor}";
}
return $baseUrl . $size . $colors . $format . ($randomizeTxt ? '&text=' . Factory::create()->word : '');
}
/**
* Loads a random image to the disk and returns its location.
*
* @param string $dir Directory.
* @param integer $width Image width.
* @param integer $height Image height.
* @param bool $randomizeColors Random colors.
* @param bool $randomizeTxt Random one word.
* @param string $format Image format (jpg|png|gif).
* @param bool $fullPath Full path of file.
* @return bool|string|\InvalidArgumentException
*/
public static function fake(
string $dir = null,
int $width = 640,
int $height = 480,
bool $randomizeColors = false,
bool $randomizeTxt = false,
string $format = 'jpg',
bool $fullPath = false
)
{
$dir = is_null($dir) ? sys_get_temp_dir() : $dir;
if (!is_dir($dir) || !is_writable($dir)) {
throw new \InvalidArgumentException("Unable to write to directory $dir");
}
$name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
$filename = $name . ".$format";
$filepath = $dir . DIRECTORY_SEPARATOR . $filename;
$url = static::imageUrl($width, $height, $randomizeColors, $randomizeTxt, $format);
if (!File::put($filepath, file_get_contents($url))) {
return false;
}
return $fullPath ? $filepath : $filename;
}
}
And use:
use App\Helpers\Image;
$filePath = Image::image(
storage_path('app' . DIRECTORY_SEPARATOR . 'public' . DIRECTORY_SEPARATOR . 'images'),
/** width: */ 640,
/** height: */ 480,
/** randomizeColors: */ false,
/** randomizeTxt: */ false,
/** format: */ 'jpg',
/** fullPath: */ false
);
Upvotes: 2
Reputation: 19
I answer to myself. The solution that I have found so far is to modify your image file inside vendor in the path vendor\fakerphp\faker\src\Faker\Provider\Image.php adding the lines that I have below since the creator of via is giving problems in receiving the data via url, to which we can always use the method either imageUrl or simply the image method I leave you my modification below and its possible faker its dying :(
public const BASE_URL = 'https://placehold.jp'; // change the url
Once this file is opened, we will search the lines approx 114 and add the following code, let's take the existing code as a reference
curl_setopt($ch, CURLOPT_FILE, $fp); //existing line
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//new line
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//new line
$success = curl_exec($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;//existing line
Upvotes: 0
Reputation: 19
ok unfortunately I couldn't correct the faker error but nevertheless I was able to generate the image on the site that faker is using as default that is the via.placeholder what I did was base myself on the structure of the site through the url it receives to generate the image by creating it through the values of the url creator of the library, to which the following code that I will share creates the generated url valid in the database when entering the field through faker to the table you only copy the url of the table, paste in the browser, download the image in the folder you are using and remove the url from the database and replace it with the name of the image plus the .png of course. I share my code since it was the only way I could get the image, the path and store it.
My Image.php code:
<?php
namespace Faker\Provider;
/**
* Depends on image generation from http://lorempixel.com/
*/
class Image extends Base
{
/**
* @var string
*/
public const BASE_URL = 'https://via.placeholder.com';
/**
* @var array
*
* @deprecated Categories are no longer used as a list in the placeholder API but referenced as string instead
*/
protected static $categories = [
'abstract', 'animals', 'business', 'cats', 'city', 'food', 'nightlife',
'fashion', 'people', 'nature', 'sports', 'technics', 'transport',
];
/**
* Generate the URL that will return a random image
*
* Set randomize to false to remove the random GET parameter at the end of the url.
*
* @example 'http://via.placeholder.com/640x480.png/CCCCCC?text=well+hi+there'
*
* @param int $width
* @param int $height
* @param string|null $category
* @param bool $randomize
* @param string|null $word
* @param bool $gray
*
* @return string
*/
public static function imageUrl(
$width = 640,
$height = 480,
$category = null,
$randomize = true,
$word = null,
$gray = false
) {
$size = sprintf('%dx%d.png', '640', '480');
$imageParts = [];
if ($category !== null) {
$imageParts[] = $category;
}
if ($word !== null) {
$imageParts[] = $word;
}
if ($randomize === true) {
$imageParts[] = Lorem::word();
}
$backgroundColor = $gray === true ? 'CCCCCC' : str_replace('#', '', Color::safeHexColor());
return sprintf(
'%s/%s/%s%s',
self::BASE_URL,
$size,
$backgroundColor,
count($imageParts) > 0 ? '?text=' . Lorem::word().'+'.Lorem::word() : ''
);
}
/**
* Download a remote random image to disk and return its location
*
* Requires curl, or allow_url_fopen to be on in php.ini.
*
* @example '/path/to/dir/13b73edae8443990be1aa8f1a483bc27.png'
*
* @return bool|string
*/
public static function image(
$dir = null,
$width = 640,
$height = 480,
$category = null,
$fullPath = true,
$randomize = true,
$word = null,
$gray = false
) {
$dir = null === $dir ? sys_get_temp_dir() : $dir; // GNU/Linux / OS X / Windows compatible
// Validate directory path
if (!is_dir($dir) || !is_writable($dir)) {
throw new \InvalidArgumentException(sprintf('Cannot write to directory "%s"', $dir));
}
// Generate a random filename. Use the server address so that a file
// generated at the same time on a different server won't have a collision.
$name = md5(uniqid(empty($_SERVER['SERVER_ADDR']) ? '' : $_SERVER['SERVER_ADDR'], true));
$filename = $name . '.png';
$filepath = $dir . DIRECTORY_SEPARATOR . $filename;
$url = static::imageUrl($width, $height, $category, $randomize, $word, $gray);
// save file
if (function_exists('curl_exec')) {
// use cURL
$fp = fopen($filepath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$success = curl_exec($ch) && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
fclose($fp);
curl_close($ch);
if (!$success) {
unlink($filepath);
// could not contact the distant URL or HTTP error - fail silently.
return false;
}
} elseif (ini_get('allow_url_fopen')) {
// use remote fopen() via copy()
$success = copy($url, $filepath);
if (!$success) {
// could not contact the distant URL or HTTP error - fail silently.
return false;
}
} else {
return new \RuntimeException('The image formatter downloads an image from a remote HTTP server. Therefore, it requires that PHP can request remote hosts, either via cURL or fopen()');
}
return $fullPath ? $filepath : $filename;
}
}
Upvotes: 0
Reputation: 76
The service that $faker->image
depends on is down, so it won't work anymore - the URL that it uses is http://lorempixel.com
You can use imageUrl()
instead.
Upvotes: 1