Dotrying to export my daanswerdata through laravel excel. https://docs.laravel-excel.com/3.1/getting-started/- this is the documentation I used for reference. At first, it is running successfully, but when I open the exported file, it exports the path of the image instead of exporting the actual images. Is there a way to export the image(the png file)?
This is exported file
this is the local path folder where the image saved
this is how its look like in my database .
here is my code:
1.Export.php
<?php
namespace App\Exports;
use App\Models\signature;
use Maatwebsite\Excel\Concerns\FromCollection;
//frow laravel excel drawing(image export)
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return signature::all();
}
public function drawings()
{
$drawing = new Drawing();
$drawing->setName('signature');
$drawing->setDescription('This is my signatuer');
$drawing->setPath(public_path('/uploads/signatures'));
$drawing->setHeight(90);
$drawing->setCoordinates('D1');
return $drawing;
}
public function headings(): array
{
return [
'id',
'name',
'description',
'signature',
'created_at',
'updated_at',
];
}
public function columnWidths(): array
{
return [
'A' => 30,
'B' => 30,
'C' => 30,
'D' => 30,
'E' => 30,
];
}
}
2.Export Controller
public function exportexcel()
{
return Excel::download(new SignatureExport, 'signaturelist.xlsx');
}
Do I miss anything? any answer is appreciated.
problem solved with the answers that are being accepted .
but ther is new problem came out
instead of 3 image , only 1 image exported sucessfully
<?php
namespace App\Exports;
use App\Models\signature;
use Maatwebsite\Excel\Concerns\FromCollection;
//frow laravel excel drawing(image export)
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use Maatwebsite\Excel\Concerns\WithDrawings;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths, WithDrawings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return signature::all();
}
public function drawings()
{
$drawing = new Drawing();
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setName('signature');
$drawing->setDescription('This is my signatuer');
$drawing->setPath(public_path('/uploads/signatures/62ac8a575af1a.png'));
$drawing->setHeight(90);
$drawing->setCoordinates('D1');
return $drawing;
}
public function headings(): array
{
return [
'id',
'name',
'description',
'signature',
'created_at',
'updated_at',
];
}
public function columnWidths(): array
{
return [
'A' => 30,
'B' => 30,
'C' => 30,
'D' => 30,
'E' => 30,
];
}
}
what should i do to get all image being exported?
In your SignatureExport class file you are missing the WithDrawings implements
class SignatureExport implements WithDrawings //like this
So your SignatureExport class should look something like this
class SignatureExport implements FromCollection, WithHeadings, WithColumnWidths, WithDrawings
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
This import is just to instance $drawing = new Drawing(); object.
For the export file to work you will need to add withDrawing concerns like you are adding WithHeadings and others
Related
I'm trying to export a csv file with Maatwebsite\Excel and Laravel 9.
As a response, I get my datas and headings in console > network , but no download occurs.
Here's my code :
Exports
namespace App\Exports;
use App\Models\Data;
use Illuminate\Support\Facades\Schema;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
class DataExport implements FromCollection, WithHeadings
{
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return Data::all();
}
public function headings():array{
return[
Schema::getColumnListing('data')
];
}
}
And my controller (1st try) :
public function download_file_csv()
{
Excel::store(new DataExport, 'dataTemplate.csv');
Excel::download(new DataExport,'dataTemplate.csv',\Maatwebsite\Excel\Excel::CSV, [
'Content-Type' => 'text/csv',
]);
}
and 2nd try
public function download_file_csv()
{
Excel::store(new DataExport, 'dataTemplate.csv');
return Excel::download(new DataExport,'dataTemplate.csv');
}
The file with datas and headings is properly stored in my public folder...
Thanks in advance,
I'm using the laravel-excel package and want to import excel into an array, it works well for the main code (without validation), but when I tried to add validation/rule, the validation not working properly (I mean, like the validation is just skipped, so if I upload a file that doesn't fit the format, the array output still comes out), here's my import code
<?php
namespace App\Imports;
use App\Models\Request;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Illuminate\Validation\Rule;
class RequestImport implements ToModel, WithValidation, WithHeadingRow
{
use Importable;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Request([
'no' => $row[0],
'username' => $row[1],
'name' => $row[2],
]);
}
// create validation by heading row
public function rules(): array
{
return [
'no' => 'required',
'username' => 'required',
'name' => 'required',
];
}
}
and here's my controller code when I call the RequestImport class
$file = request()->file('fileExcel');
// save file
if (isset($request->upload)) {
$this->saveFile($file);
}
// return excel import into array
$data = (new RequestImport)->toArray($file); //here I call the RequestImport
return response()->json([
'status' => 'success',
'message' => 'success,
'data' => $data[0],
]);
Is something wrong with my code? or I missed something?
it's not official but I found a workaround.
first, I added importable concern,
then defined a class attribute $data.
this will store rows once all validations are satisfied.
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToArray;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class ImportData implements ToArray, WithValidation, WithHeadingRow
{
use Importable;
public $data;
public function array(array $rows)
{
$this->data = $rows;
}
public function rules(): array
{
return [
// validation rules
];
}
}
in my controller
$import = new ImportData;
Excel::import($import, request()->file('file'));
return response()->json($import->data);
I have a database with two columns, brands and shops. Each brand can owe several shops, and I want to seed my database via Fakers using Laravel.
So after setting up the migrations and the relationships in the models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
/**
* Get the shops for the brand.
*/
public function shops()
{
return $this->hasMany('App\Shop','sh_brand_id');
}
}
And:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
public function user() {
return $this->belongsTo('App\Brand','sh_brand_id');
}
}
I want to use a Factory to seed the database.
<?php
use Faker\Generator as Faker;
$factory->define(App\Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
];
});
And
use Faker\Generator as Faker;
$factory->define(App\Brand::class, function (Faker $faker) {
return [
'name' => $faker->company,
'logo_url' => $faker->imageUrl(640, 480),
'website' => $faker->url,
'description' => $faker->text(500),
'telephone_number' =>'31'. $faker->randomNumber(8),
'principal_address' => $faker->address,
'email' => $faker->unique()->safeEmail,
];
});
And finally I need to seed the database using those Factories. There are documentation in the website and many examples for do it, but each solution I've found let me generate only one shop for each brand, and I want to generate many shops for each brands.
What is the best way to do this?
Put it directly in your factory. I use a helper method getInstanceOf to pick a random instance of another model.
use Faker\Generator as Faker;
use App\Brand;
use App\Shop;
function getInstanceOf($class, $returnIdOnly = true) {
$instance = $class::inRandomOrder()->first() ?? factory($class)->create();
return $returnIdOnly ? $instance->id : $instance;
}
$factory->define(Shop::class, function (Faker $faker) {
return [
'name' => $faker->company,
'address' => $faker->address,
'sh_brand_id' => getInstanceOf(Brand::class)
];
});
Then when seeding,
factory(App\Brand::class, 10);
factory(App\Shop::class, 50);
I've found this workaround that works for me:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run() {
factory(App\Brand::class, 50)->create()
->each(
function ($br) {
factory(App\Shop::class, 10)->create()
->each(
function($sh) use (&$br) {
$br->shops()->save($sh)->make();
}
);
}
);
}
}
I am using model factories in NewsTableSeeder, but I get this error when I entered db:seed.
I want to know why I can't use create() in my seeder.
Here is my News model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class News extends Model
{
protected $table = 'news';
protected $primaryKey = 'id';
public function home_news_lists() {
return $this->select('id', 'news_title', 'news_update')
->orderBy('news_update', 'DESC')
->limit(5)
->get();
}
public function lists() {
return News::all();
}
}
Model Factories:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = $faker->create('zh_TW');
return [
'news_title' => $faker->sentence(),
'news_content' => $faker->paragraph(),
'news_author' => $faker->name(),
'news_pageviews' => $faker->numberBetween(1, 100),
'news_file' => ' ',
'news_img' => $faker->imageUrl($width, $height, 'business'),
'created_at' => $faker->dateTimeBetween('2012', 'now', 'zh_TW'),
'updated_at' => $faker->dateTimeBetween('2015', 'now', 'zh_TW')
];
});
NewsTableSeeder :
<?php
use Illuminate\Database\Seeder;
class NewsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Models\News::class, 50)->create();
}
}
I can't tell 100% without seeing exactly the error you got, but I do believe there is no create() method on the $faker object.
I believe what you mean to do is:
$factory->define(App\Models\News::class, function (Faker\Generator $faker)
{
static $password;
$faker = \Faker\Factory::create('zh_TW'); // change to this
return [
...
];
}
I would just create a new faker generator (\Faker\Generator) that gets returned from calling \Faker\Factory::create($locale) and use that instead. Otherwise, I believe your next best option is to override wherever Laravel instantiates the \Faker\Generator $faker object that gets passed into the callback, but that may get hacky if Laravel doesn't provide a clean way to do it.
The create() method is a static call on the \Faker\Factory method. It accepts a locale as the parameter and uses en_US as the default locale.
$faker = $faker->create('zh_TW');
The error message said this code is wrong.
What is your purpose to use this code?
Struggling using parseIncludes in https://github.com/thephpleague/fractal.
I have two tables, Property and Weeks. Each property has many weeks. Using Fractal I can return my property item with a collection of weeks. What I want to do is use parseIncludes, so that the return of weeks is optional.
PropertyTransformer.php
<?php
namespace App\Transformer;
use App\Models\Property;
use League\Fractal\TransformerAbstract;
class PropertyTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'week'
];
public function transform(Property $property)
{
return [
'id' => (int) $property['PropertyID'],
'PropertyName' => $property['PropertyName'],
'ExactBeds' => (int) $property['ExactBeds'],
'weeks' => $property->week
];
}
/**
* Include Week
*
* #return League\Fractal\ItemResource
*/
public function includeWeek( Property $property )
{
$week = $property->week;
return $this->item($week, new WeekTransformer);
}
}
WeekTransformer.php
<?php
namespace App\Transformer;
use App\Models\Week;
use League\Fractal;
class WeekTransformer extends Fractal\TransformerAbstract
{
public function transform(Week $week)
{
return [
'Week' => $week['week'],
'Available' => $week['available'],
'Price' => (int) $week['price'],
];
}
}
My PropertyController.php
<?php namespace App\Http\Controllers\Api\v1;
use App\Http\Requests;
use App\Models\Week;
use Illuminate\Support\Facades\Response;
use App\Models\Property;
use League\Fractal;
use League\Fractal\Manager;
use League\Fractal\Resource\Collection as Collection;
use League\Fractal\Resource\Item as Item;
use App\Transformer\PropertyTransformer;
class PropertyController extends \App\Http\Controllers\Controller {
public function show($id)
{
$property = Property::with('bedroom')->with('week')->find($id);
$fractal = new Fractal\Manager();
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
$resource = new Fractal\Resource\Item($property, new PropertyTransformer);
//$resource = new Fractal\Resource\Collection($properies, new PropertyTransformer);
return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();
}
I get the following error on the parseIncludes:-
Method 'parseIncludes' not found in class \League\Fractal\Scope
I'm following the guide here on transformers - http://fractal.thephpleague.com/transformers/
I think I am going wrong somewhere here where it says:-
These includes will be available but can never be requested unless the Manager::parseIncludes() method is called:
<?php
use League\Fractal;
$fractal = new Fractal\Manager();
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
If I remove the parseIncludes, I don't get an error, I also get my property data with my collection of weeks, but ?include=week doesn't work to optionally get it.
Your problem is in this line:
return $fractal->createData( $resource )->parseIncludes('weeks')->toJson();
createData() returns \League\Fractal\Scope and it has no parseInlcudes method.
You've already called parseIncludes here:
if (isset($_GET['include'])) {
$fractal->parseIncludes($_GET['include']);
}
So just remove the second call to it in the return statement:
return $fractal->createData($resource)->toJson();