Can I with fzaninotto/Faker generate doc / xls files? - faker

Reading docs for laravel 9 site at
https://github.com/fzaninotto/Faker
I did not find if there is a way to generate doc(microsoft word) / xls(microsoft excel) files with this library ?
Maybe some other library ?
Thanks in advance!

Faker is using to generate simple data like sentences, email, phone etc. But you can use, for example maatwebsite/excel to make xlsx filling it with faker.
The simplest way to create doc file is to make html file with doc extension.
Update:
Keep in mind that maatwebsite/excel was built for Laravel framework, but there are other packages witch can be used independent from frameworks, for example XLSWriter
maatwebsite/excel
Laravel's factory to make User model
class UserFactory extends Factory
{
protected $model = User::class;
public function definition()
{
return [
'login' => '0'.$this->faker->numberBetween(70000000000, 80000000000),
'email' => $this->faker->unique()->safeEmail,
'lastname' => $this->faker->lastName,
'firstname' => $this->faker->firstNameMale,
'phone' => $this->faker->phoneNumber,
];
}
}
maatwebsite's export class (this one uses a collection as source)
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
private $collection;
public function __construct($collection)
{
$this->collection = $collection;
}
public function collection()
{
return $this->collection;
}
}
Make xlsx file with 10 users uses laravel's seeder
class XlsSeeder extends Seeder
{
public function run()
{
$users = User::factory()
->count(10)
->make();
Excel::store(new UsersExport($users), 'users.xlsx');
}
}
XLSWriter
Wherever you need to create xlsx, you can write something like:
for($i = 0; $i < 10; $i++) {
$users[] = [
$faker->numberBetween(70000000000, 80000000000),
$faker->unique()->safeEmail,
$faker->lastName,
$faker->firstName,
$faker->phoneNumber,
];
}
$fileObject = new \Vtiful\Kernel\Excel([
'path' => './tests'
]);
$file = $fileObject->fileName('users.xlsx', 'sheet_one')
->header(['login', 'email', 'lastname', 'firstname', 'phone'])
->data($users);
$file->output();

Related

Laravel change profile api gives null value

I am making change profile picture api in laravel .I want to update profile image in users table but not inserting or updating my images .Belew are my code please help me how to update user table .
fileUploadController.php
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Detail;
use App\Profile;
use Illuminate\Support\Facades\DB;
use Session;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
class FileUploadController extends Controller
{
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($file = $request->hasFile('image')) {
$file = $request->file('image');
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/files/' ;
$file->move($destinationPath,$fileName);
$updateuser->image = '/files/'.$fileName;
}
$updateuser->save();
return $updateuser;
}
}
public function changeProfile(Request $request,$id){
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$updateuser = User::find($id);
if($request->hasFile('image'))
{
$filewithext = $request->file('image')->getClientOriginalName();
$ext = $request->file('image')->getClientOriginalExtension();
$fileToStrore = $filewithext;
$path = $request->file('image')->storeAs('public/files',$fileToStrore);
$updateuser->image = $fileToStrore;
}
$updateuser->save();
return $updateuser;
}
This code works for me. I hope it will work for you too...
Good Luck..
This code is working for me.....
fileUploadController.php
public function changeProfile(Request $request,$id){
$updateuser = User::find($id);
if ($request->hasFile('image')) {
$images = $request->file('image');
$destinationPath = public_path('files');
$imageName = time().'.'.$images->getClientOriginalExtension();
$images->move($destinationPath, $imageName);
$updateuser->image= $imageName;
}else{
$updateuser->image= '';
}
$updateuser->update();
return ['message' => 'Image Uploaded Successfully'];
}

Use Mapper.Initialize() for multiple mappings

I use AutoMapper V.6.1.1 as a mapper in my ASP.Net project.
Before I had configuration as below:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<A, B>();
cfg.CreateMap<C, D>().ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
});
var mapper = config.CreateMapper();
var var1= mapper.Map<B>(request);
var var2= mapper.Map<List<C>, List<D>>(result);
Now, I want to refactor the code, using Mapper.Initialize(). So I used:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<A, B>();
cfg.CreateMap<C, D>().ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
});
var var1= Mapper.Map<B>(request);
var var2= Mapper.Map<List<C>, List<D>>(result);
I have an run time error:
Missing type map configuration or unsupported mapping. Mapping types: A-> B
Is there any problem with using multiple configurations in Mapper.Initialize? There is no error in the case that has one mapping in Initialize() body. How should I fix the error?
Maybe you have more than one Mapper.Initialize in your project while you should not have multiple Mapper.Initialize in your project else it will become override and you lost previous mapping configurations that you set by Mapper.Initialize. Now It is possible to get the error (Missing type map configuration or unsupported mapping.)
I recommend you to use AutoMapper.Profile. You can warp your mapping configurations in the form of grouped (in separated Profiles) then register all of theme by Mapper.Initialize at once ;)
Look at this example:
public class AB_Profile : Profile {
protected override void Configure() {
CreateMap<A, B>();
// CreateMap<A, B1>();
// CreateMap<A, B2>();
}
}
public class CD_Profile : Profile {
protected override void Configure() {
CreateMap<C, D>()
.ForMember(dest => dest.CityDesc, opt => opt.MapFrom(src => src.City));
}
}
Then initialize the Mapper using above Profiles:
Mapper.Initialize(cfg => {
cfg.AddProfile<AB_Profile >();
cfg.AddProfile<CD_Profile >();
});
Starting version 5 use this, as mentioned on their website...
public class OrganizationProfile : Profile
{
public OrganizationProfile()
{
CreateMap<Foo, FooDto>();
// Use CreateMap... Etc.. here (Profile methods are the same as configuration methods)
}
}
// How it was done in 4.x - as of 5.0 this is obsolete:
// public class OrganizationProfile : Profile
// {
// protected override void Configure()
// {
// CreateMap<Foo, FooDto>();
// }
// }
See Doc
Then initialize the mapping as...
Mapper.Initialize(cfg => {
cfg.CreateMap<Foo, Bar>();
cfg.AddProfile<OrganizationProfile>();
});

How to save Arabic language as encoded format into database in Laravel

I want to save my Arabic language field as encoded format into database. now it showing like تي بتب into that database. I want the format like à´¨àµà´¯àµ‚à´¡à´²àµâ€à´¹à´¿: പാകൠഅധീന à´•à´¶àµà´®àµ€à´°à´¿à´²àµâ€ ഇനàµà´¤àµà´¯ നടതàµà´¤à´¿à.
The collation and charset i set like charset=>'utf8' collation=>'utf8_unicode_ci' and my table fields also utf8_unicode_ci.
This is my model -
namespace App;
use Illuminate\Database\Eloquent\Model;
class FillingCategory extends Model
{
protected $fillable=['category','category_arabic'];
}
This is insertion code that i used in this project. Only two fields are there. The field name called category_arabic is a text field that text want to show like à´•à´¶àµà´®àµ€à´ inside the database.
public function store(Request $request) {
$this->validate($request, [
'category' => 'required',
'category_arabic' => 'required'
]);
$fillingCategory = new FillingCategory(['category'=>$request->category,'category_arabic'=>$request->category_arabic]);
$status = $fillingCategory -> save();
if ($status) {
$statusLabel = "success";
$statusMsg = "Filling category added successfully.";
} else {
$statusLabel = "danger";
$statusMsg = "Some thing went wrong! Please try again.";
}
flash_status($statusLabel, $statusMsg);
return redirect('admin/filling_category');
}

How to translate $url_handlers?

I have a situation where I need to translate the following $url_handlers for different countries.
So on an english site the URL looks like this: http://website.com/gyms/boston/group-training
I need to be able to translate the "group-training" part of the URL. I have translated the rest of the site using the _t() method throughout.
My current setup:
class GymLocationPage_Controller extends Page_Controller {
private static $allowed_actions = array(
'currentSpecials',
'sevenDayFreeTrial',
'groupTraining'
);
private static $url_handlers = array(
'current-specials' => 'currentSpecials',
'trial' => 'sevenDayFreeTrial',
'group-training' => 'groupTraining'
);
}
How would one achieve this?
You could update the config inside the controller's init() function, doing something like this:
public function init() {
parent::init();
// Define your translated actions.
$translatedCurrentSpecials = _t('Actions.CURRENT_SPECIALS', 'aktuella-kampanjer');
$translatedSevenDayFreeTrial = _t('Actions.SEVEN_DAY_TRIAL', 'sjudagars-prova-pa-period');
// Define your url handlers.
$urlHandlers = $this->config()->url_handlers;
$translatedUrlHandlers = [
$translatedCurrentSpecials => 'currentSpecials',
$translatedSevenDayFreeTrial => 'sevenDayFreeTrial'
];
// Update the config.
Config::inst()->update(
$this->class,
'url_handlers',
$translatedUrlHandlers + $urlHandlers // Important to prepend and not append.
);
}

Symfony 2 Sonata admin list views do not display subclasses

Currently I cant get subclasses to appear in a list view using sonta admin bundle for symfony 2
I can get it working for create forms as per the advanced config page (http://sonata-project.org/bundles/admin/2-1/doc/reference/advance.html) but how can you do this with the list view?
If i pass the subclass in the url - list?subclass=MySubClassName
and set the object in my listAction
$object = $this->admin->getNewInstance();
$this->admin->setSubject($object);
I can get the subject and configure the correct fields with configureListFields()
if ($subject instanceof MySubClassName) {
$listMapper->add('MySubClassNameID');
$listMapper->add('MySubClassNameKey');
$listMapper->add('MySubClassNameStatus','text');
}
but the end results table is always blank and the symfony debug toolbar seems to show that the db queries are looking for the parent class. Anyone got this to work?
I'm not sure what you mean with those "subclasses" in the list view, but if you want to add a field form another entity (connected through a foreign key with yours) you can do it lie this:
$listMapper
->addIdentifier('id')
->addIdentifier('title')
->add('name')
->add('entity1.customField1')
->add('entity2.customField2');
Incase anyone else faces this I found out how to do this.
To make it work in a way similar to the edit page you would pass the subclass in the url
...list?subclass=MySubClass
set the subject of your listAction in your custom admin crud controller
public function listAction()
{
if (false === $this->admin->isGranted('LIST')) {
throw new AccessDeniedException();
}
if ($listMode = $this->getRequest()->get('_list_mode')) {
$this->admin->setListMode($listMode);
}
$this->admin->setSubject($this->admin->getNewInstance());
$datagrid = $this->admin->getDatagrid();
$formView = $datagrid->getForm()->createView();
// set the theme for the current Admin Form
$this->get('twig')->getExtension('form')->renderer->setTheme($formView, $this->admin->getFilterTheme());
return $this->render($this->admin->getTemplate('list'), array(
'action' => 'list',
'form' => $formView,
'datagrid' => $datagrid,
'csrf_token' => $this->getCsrfToken('sonata.batch'),
));
}
and then over-ride the createQuery method in your Admin class
public function createQuery($context = 'list')
{
$cName = get_class($this->getSubject());
$query = $this->getModelManager()->createQuery($cName);
foreach ($this->extensions as $extension) {
$extension->configureQuery($this, $query, $context);
}
return $query;
}
If you pass anything with url parameters you should also override getPersistentParameters to add your url request to Pager, FilterForm and the form for batchActions (or others that appear on the list view)
<?php
class YourAdmin extends Admin
{
public function getPersistentParameters()
{
if (!$this->getRequest()) {
return array();
}
return array(
'subclass' => $this->getRequest()->get('subclass'),
);
}
}

Resources