Seed fake images in laravel - laravel

I'm trying to generate a fake image to populate seeder data.
I created a seeder with this:
$this->faker->image(storage_path('app/public/products'), 500, 500)
When I try to access them through Laravel Nova to see them, I get this kind of URL: http://localhost/storage/var/www/html/storage/app/public/products/c8831002794cc55fe046c5e2b65794d4.png
In the DB it's saved as: /var/www/html/storage/app/public/products/c8831002794cc55fe046c5e2b65794d4.png
Any idea what I've done wrong?

See the method signature for image():
function image(
?string $dir = null,
int $width = 640,
int $height = 480,
?string $category = null,
bool $fullPath = true,
bool $randomize = true,
?string $word = null,
bool $gray = false,
string $format = 'png'
)
Setting $fullPath to false will fix your issue:
$this->faker->image(storage_path('app/public/products'), 500, 500, null, false)

Try this:
$this->faker->image('app/public/products',400,300, null, false)
if you have a view then:
<img src="/my/path/{{ $item->image}}" >

Related

How to create Barcode on PDF in Magento 2.3.x

I am trying to create Barcode in PDF file in Magento 2.3.x Version,
Below code was working in Magento 2.1.8
However this is throwing below error -
PHP Fatal error: Uncaught TypeError: Argument 1 passed to
Zend\Barcode\Renderer\Pdf::setResource() must be an instance of
ZendPdf\PdfDocument, instance of Zend\Barcode\Renderer\Pdf given,
called in /var/www/magento/app/code/MyCompany/Ups/Helper/Custom.php on
line 81
<?php
namespace Mycompany\Ups\Helper;
use Zend\Barcode\Barcode;
use Zend\Barcode\Renderer;
use Zend\Barcode\Renderer\Pdf;
class Custom extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $_logger;
protected $_fontPath;
protected $_pdf;
public function __construct(
\Psr\Log\LoggerInterface $logger,
\Magento\Framework\Module\Dir\Reader $configReader,
Pdf $pdf
)
{
$this->_logger = $logger;
$this->_fontPath = $configReader->getModuleDir('etc', 'Mycompany_Ups') . '/lib/fonts/';
$this->_pdf = $pdf;
}
public function getOrderConfirmationPdf($order)
{
try {
$pdf = new \Zend_Pdf();
$page = new \Zend_Pdf_Page(\Zend_Pdf_Page::SIZE_A4);
$color1 = new \Zend_Pdf_Color_GrayScale(0.0); // (float number). 0.0 (black) - 1.0 (white)
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font,40);
$page->setFillColor($color1)->drawText('ORDER CONFIRMATION', 60, 720);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font,30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 620);
$page->setFont($font,16.5);
$page->setFillColor($color1)->drawText('PLACE THIS INSIDE THE SHIPPING CARTON WITH THE', 75, 520);
$page->setFillColor($color1)->drawText('CONTROL BOARD', 220, 500);
$page->setFillColor($color1)->drawText('WRITE THE BELOW ORDER CONFIRMATION NUMBER ON', 65, 460);
$page->setFillColor($color1)->drawText('THE OUTSIDE OF THE SHIPPING CARTON', 125, 440);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font,15);
$page->setFillColor($color1)->drawText('(Order Confirmation Number: '.$order->getIncrementId().')', 145, 370);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font,30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 100);
$pdf->pages[] = $page;
/* \Zend_Barcode::setBarcodeFont($this->_fontPath.'helvetica-normal.ttf');
$barcodeOptions = array('text' => $order->getIncrementId(),'barHeight' => 100,'factor'=> 2.1,'drawText' => TRUE, 'withChecksum' => TRUE, 'stretchText' => TRUE, 'withChecksumInText' => TRUE, 'barThickWidth' => 2, 'barThinWidth' => 2);
$rendererOptions = array('topOffset' => 530,'leftOffset' => 185);
$pdfWithBarcode = \Zend_Barcode::factory('code128', 'pdf', $barcodeOptions, $rendererOptions)->setResource($pdf,0)->draw();*/
Barcode::setBarcodeFont($this->_fontPath.'helvetica-normal.ttf');
$barcodeOptions = array('text' => 'ZEND-FRAMEWORK');
$rendererOptions = array();
$renderer = Barcode::factory('code128', 'pdf', $barcodeOptions, $rendererOptions);
$renderer->setResource($pdf, $page)->draw();
$pdf_str = $pdf->render();
//$pdf->save("/var/www/html/magento2/mage2/pub/From_Helper_".$order->getIncrementId().".pdf");
unset($pdf);
return $pdf_str;
} catch(Exception $e) {
mail("rdambare#test.com","ORDER CONFIRMATION PDF ERROR: ".$order->getIncrementId(),$e->getMessage);
return FALSE;
}
}
}
I am using this code in Helper in my custom module.
Any help would be appreciated. Thanks in advance.
Below is sample of PDF I want to generate.
Try this code
<?php
namespace MyCompany\Ups\Helper;
include_once '/var/www/magento/fpdf181/fpdf.php';
use \Magento\Framework\App\Helper\AbstractHelper;
use \Magento\Framework\App\Filesystem\DirectoryList;
use Zend\Config\Config;
use Zend_Barcode;
// use Zend_Barcode;
class Data extends AbstractHelper {
const LABEL_FOLDER = 'media/sales/order/labels/';
const FONT_FOLDER = 'media/fonts/';
protected $_filePointer = NULL;
protected $_directoryList;
protected $_logger;
protected $_fontPath;
protected $_rootDirectory;
public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Psr\Log\LoggerInterface $custLogger, \Magento\Framework\Module\Dir\Reader $configReader, \Magento\Framework\Filesystem $filesystem, DirectoryList $directoryList) {
$this->_logger = $custLogger;
$this->_directoryList = $directoryList;
$this->_pubPath = $directoryList->getPath('pub');
$this->_rootDirectory = $filesystem->getDirectoryRead(DirectoryList::ROOT);
$this->_fontPath = $configReader->getModuleDir('etc', 'MyCompany_Ups') . '/lib/fonts/';
$this->_storeManager = $context->getStoreManager();
}
public function getOrderConfirmationPdf($order) {
try {
$pdf = new \Zend_Pdf();
$page = new \Zend_Pdf_Page(\Zend_Pdf_Page::SIZE_A4);
$color1 = new \Zend_Pdf_Color_GrayScale(0.0); // (float number). 0.0 (black) - 1.0 (white)
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font, 40);
$page->setFillColor($color1)->drawText('ORDER CONFIRMATION', 60, 720);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 620);
$page->setFont($font, 16.5);
$page->setFillColor($color1)->drawText('PLACE THIS INSIDE THE SHIPPING CARTON WITH THE', 75, 520);
$page->setFillColor($color1)->drawText('CONTROL BOARD', 220, 500);
$page->setFillColor($color1)->drawText('WRITE THE BELOW ORDER CONFIRMATION NUMBER ON', 65, 460);
$page->setFillColor($color1)->drawText('THE OUTSIDE OF THE SHIPPING CARTON', 125, 440);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA_BOLD);
$page->setFont($font, 15);
$page->setFillColor($color1)->drawText('(Order Confirmation Number: ' . $order->getIncrementId() . ')', 145, 370);
$font = \Zend_Pdf_Font::fontWithName(\Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 30.5);
$page->setFillColor($color1)->drawText('THIS IS NOT A SHIPPING LABEL', 60, 100);
$pdf->pages[] = $page;
Zend_Barcode::setBarcodeFont($this->_fontPath . 'helvetica-normal.ttf');
$barcodeConfig = array('text' => $order->getIncrementId(), 'barHeight' => 100, 'factor' => 2.1, 'drawText' => TRUE, 'withChecksum' => TRUE, 'stretchText' => TRUE, 'withChecksumInText' => TRUE, 'barThickWidth' => 2, 'barThinWidth' => 2);
$rendererConfig = array('topOffset' => 530, 'leftOffset' => 185);
$renderer = Zend_Barcode::factory('code128', 'pdf', $barcodeConfig, $rendererConfig)->setResource($pdf, 0);
$renderer->draw();
$pdf_str = $pdf->render();
$pdf->save("/var/www/magento/pub/media/sales/order/labels/From_Helper_" . $order->getIncrementId() . ".pdf");
unset($pdf);
return $pdf_str;
}
catch(Exception $e) {
mail("rdambare#test.com", "ORDER CONFIRMATION PDF ERROR: " . $order->getIncrementId(), $e->getMessage);
return FALSE;
}
}
Try https://github.com/picqer/php-barcode-generator
Install through composer:
composer require picqer/php-barcode-generator
Usage
Initiate the barcode generator for the output you want, then call the ->getBarcode() routine as many times as you want.
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
echo $generator->getBarcode('081231723897', $generator::TYPE_CODE_128);

How to retrieve current user session id from ci_sessions.?

I want to get current session id to use it in all pages. I want to pass session data in header. I can store my session in ci_sessions table. But how can I retreive current login username/sesson_id from ci_sessions.
here is my ci_sessions code.
CREATE TABLE IF NOT EXISTS `ci_sessions` (
`id` varchar(128) NOT NULL,
`ip_address` varchar(45) NOT NULL,
`timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
`data` blob NOT NULL,
KEY `ci_sessions_timestamp` (`timestamp`)
);
here is session setting code
if($this->form_validation->run())
{
$username = $this->input->post('login_username');
$password = $this->input->post('login_password');
// ip address
//$ip_address= $this->user_activity->get_client_ip();
//Retrieving session data and other data
//$captcha_code=$_SESSION['captcha'];
//$user_agent=$_SERVER['HTTP_USER_AGENT'];
//call the model for auth
$this->load->Model('Auth_model');
if($this->Auth_model->login($username, $password)){
$data = array(
'client_username' => $username,
'is_logged_in' => true
);
$this->session->set_userdata($data);
$this->load->view('include/header', $data);
//$this->session->set_flashdata('item', $datav['name']);
}
else{
echo'something went wrong';
}
I am using pop dailog for login and signup so here is my ajax.
<script>
$("input#login_btn").on('click',function(event){
event.preventDefault();
var x = document.forms["loginform"]["login_username"].value;
var x1 = document.forms["loginform"]["login_password"].value;
var y = document.getElementById('login-error');
var z = document.getElementById('password-error');
if (x == "") { y.style.display ='block'; }else{ y.style.display ='none'; }
if (x1 == "") { z.style.display ='block'; }else{ z.style.display ='none'; }
var d = document.forms["loginform"]["login_username"].value;
var d1 = document.forms["loginform"]["login_password"].value;
if(d != '' && d1 != ''){
var url = $(this).attr('action');
var method = $(this).attr('method');
var data = $(this).serialize();
$.ajax({
url:url,
type:method,
data:data
}).done(function(data){
if(data !=='')
{
if(d !== '' && d1 != '' ){
//$("#login_fail").show('fast');
//$("#login_fail").effect( "shake" );
$('#loginform')[0].reset();
//var url = $('#current_loginurl').val();
//window.location.href=url;
var url = $('#current_loginurl').val();
window.location.href=url;
}
}
else
{
var url = $('#current_loginurl').val();
window.location.href=url;
throw new Error('go');
}
});
$( "div" ).each(function( index ) {
var cl = $(this).attr('class');
if(cl =='')
{
$(this).hide();
}
});
}
});
</script>
Find current session from table like below.Get the records order by id in descending order having limit 1.
$this->db->order_by('id', 'DESC');
$this->db->limit(1);
$last_session = $this->db->get('ci_sessions')->row_array();
print_r($last_session['data']);//prints current session data
UPDATE
But the easiest way to get current user session id is make use of session library.Like this..
$this->load->library('session');
$id = $this->session->userdata('id');//id is session variable that you set
echo $id;

Receive function fails to get image

I am working on multiple file upload code is not showing any error
public function imagenewAction()
{
$form = new ImageNewForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
// die('checko');
if($request->isPost())
{
// die('checko');
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($data);
if ($form->isValid())
{
//New Code
$dataNew=array('','image','image1');
for($i=1;$i<=2;$i++)
{
$addressProof = $data[$dataNew[$i]]['name'];
$addressProofextension = pathinfo($addressProof, PATHINFO_EXTENSION);
// $addressProofimg = $addressProof . $i . "." . $addressProofextension;
$addressProofimg = $addressProof;
//$verificationdocuments->setdocphotocopy($addressProofimg);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
$adapter->addFilter(new \Zend\Filter\File\Rename(array(
'target' => 'public/img/upload',
'overwrite' => true
)), null, $addressProofimg);
if(!$adapter->receive($addressProofimg))
{
print_r ( $adapter->getMessages (), 1 );
}
else
{
echo "Image Uploaded";
}
}
}
}
return array('form' => $form);
}
It is giving blank error messages and not uploading images please help me to get away with this I am stuck from last 2 days

Laravel, Fetching image from public/uploads folder

Controller :
public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image_content = File::get("uploads/profiles/default.jpg");
$image = response($image_content, 200)->header('Content-Type', 'image/jpeg');
$size = getimagesize($image);
$aspectratio = $size[0]/$size[1];
$img_thumbnail = Image::make($image)->resize(50*$aspectratio,50);
$img_profile = Image::make($image)->resize(160*$aspectratio,160);
$imgname = \Auth::User()->id;
$img_thumbnail->save('uploads/thumbnails/'.$imgname.".jpeg");
$img_profile->save('uploads/profiles/'.$imgname.".jpeg");
}
Error : : failed to open stream: No such file or directory.
Actually, I want to fetch the default.jpg image and save it to two other folders with different extension.
if( !file_exists('uploads/thumbnails/'. $folder)){
#mkdir('uploads/thumbnails/'. $folder, 0755);
}
if( !file_exists('uploads/profiles/'. $folder)){
#mkdir('uploads/profiles/'. $folder, 0755);
}
$img = 'uploads/profiles/'. \Auth::User()->id. '.jpeg';
if ( !file_exists($img)){
$save_extension = '.jpeg';
Image::make($img)
->resize(50, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/thumbnails/' . \Auth::User()->id . $save_extension);
Image::make($img)
->resize(160, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/profiles/' . \Auth::User()->id . $save_extension);
}
http://image.intervention.io/api/resize
public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image = File::get("uploads/profiles/default.jpg");
return response($image)->header('Content-Type', 'image/jpeg');
}
Make sure you're have the right permission to uploads/profiles/
chmod -R 777 /uploads/profiles/

Laravel Pagination from merge()

I've merges 2 Collections:
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
...
$towni18n = TownI18n::where(...)->get();
$town = Town::where(...)->get();
$all = $towni18n->merge($town);
$perPage = 10;
$input = \Input::all();
if (isset($input['page']) && !empty($input['page'])) { $currentPage = $input['page']; } else { $currentPage = 1; }
$paginator = new Paginator($all, $all->count(), $perPage, $currentPage);
return $paginator;
The output is not following the pagation but returns all the results:
{
total: 547,
per_page: 10,
current_page: 1,
last_page: 55,
next_page_url: "/?page=2",
prev_page_url: null,
from: 1,
to: 547,
data: [
{
id: 1423550,
...
Any idea how to fix this ?
It seems that you have to slice manually. From the Laravel 5.1 doc:
"When manually creating a paginator instance, you should manually
"slice" the array of results you pass to the paginator."
So the answer is:
$arr = $all->toArray();
$offset = ($currentPage * $perPage) - $perPage;
$arr_splice = array_slice($arr, $offset, $perPage, true);
$paginator = new Paginator($arr_splice, count($arr), $perPage, $currentPage);

Resources