In the code how can I give a new line down. I want to have days on a row and have to load every day.
Click here! for solution.
Set your value, with your tab "\r" or "\r\n" then
$sheet->getStyle('C1')->getAlignment()->setWrapText(true);
OR
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class InvoicesExport implements WithStyles
{
public function styles(Worksheet $sheet)
{
$sheet->getStyle('B2')->getAlignment()->setWrapText(true);
}
}
Just like...
use Maatwebsite\Excel\Concerns\WithMapping;
class ExampleExport implements WithMapping
{
public function map($row): array
{
$row = [];
$dates = explode("", $row->dates);
if(count($dates)){
$row = [
"col1",
"col2",
"date",
]
foreach($dates as $d){
$row[] = [
'',
'',
$d
];
}
} else {
$row = [
"col1",
"col2",
"date",
]
}
return $row;
}
}
Related
Could somebody tell me how to reformat the excel output, so that i get two excel columns. Right now it gives me two arrays in A1 and B1. like two fields with [1,24,5,3.3] and [3,4,5,6], but I want two columns with the numbers.
Route
Route::get('/exporttable/{id}', [TableExportController::class, 'export']);
TableExportController
use Illuminate\Http\Request;
use App\Exports\TablesExport;
use Maatwebsite\Excel\Facades\Excel;
class TableExportController extends Controller
{
public function export(Request $request){
return Excel::download(new TablesExport($request->id), 'tables.xlsx');
}
}
TableExport.php
use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromCollection;
class TablesExport implements FromCollection
{
/**
* #return \Illuminate\Support\Collection
*/
function __construct($id) {
$this->id = $id;
}
public function collection()
{
$tabula = Tabula::select('soll', 'haben')->where('id', '=', $this->id)->get();
return $tabula;
}
}
It works with the code of Natvarsinh Parmar - bapu , if you edit the map-function like this
public function map($tabula): array
{
//unformatieren
$soll = $tabula->soll;
//vom string Randwerte abschneiden: [ und ]
$soll = substr($soll, 1, -1);
// in Array umwandeln
$soll = explode( ',', $soll);
//das gleiche mit soll
$haben = $tabula->haben;
$haben = substr($haben, 1, -1);
$haben = explode( ',', $haben);
// als ersten Wert den Header soll/haben einfügen ins Array
array_unshift($haben, "haben");
array_unshift($soll, "soll");
return [
$soll,
$haben
];
}
So now it works, thanks! Each array covers a row in excel now.
Make changes as per below in TableExport.php and check
<?php
namespace App\Exports;
use App\Models\Tabula;
use Maatwebsite\Excel\Concerns\FromArray;
class TablesExport implements FromArray
{
protected $soll;
protected $haben;
protected $export_data;
public function __construct($id)
{
$this->id = $id;
}
public function array(): array
{
$results = Tabula::select('id', 'soll', 'haben')
->where('id', $this->id)
->get();
$this->export_data = [];
$results->each(function($result) {
preg_match_all('!\d+!', $result->soll, $matches_soll);
preg_match_all('!\d+!', $result->haben, $matches_haben);
$this->soll = [];
$this->haben = [];
if(isset($matches_soll[0]))
{
$this->soll = collect($matches_soll[0]);
}
if(isset($matches_haben[0]))
{
$this->haben = collect($matches_haben[0]);
}
if(count($this->soll) > count($this->haben)) {
foreach($this->soll as $key => $val){
$temp = [];
$temp = [
$val,
(isset($this->haben[$key])) ? $this->haben[$key] : ''
];
$this->export_data[] = $temp;
}
} else {
foreach($this->haben as $key => $val){
$temp = [];
$temp = [
(isset($this->soll[$key])) ? $this->soll[$key] : '',
$val
];
$this->export_data[] = $temp;
}
}
});
return $this->export_data;
}
}
I try to give to a column the ID of that row, witch is autoincremental. Right now are random values .
//From Factory
return [
//code...
'register_id' => $faker->unique()->numberBetween($min = 1, $max = 100),
//code...
];
//From Seeder
public function run()
{
factory(App\Person::class, 100)->create();
}
I found an answer, here , and I edited for my case.
$autoIncrement = autoIncrement();
$factory->define(Person::class, function (Faker $faker) use ($autoIncrement) {
$autoIncrement->next();
//code
return [
'register_id' => $autoIncrement->current(),
]
});
function autoIncrement()
{
for ($i = 0; $i < 1000; $i++) {
yield $i;
}
}
i want to add the url image in value to array
public function show(){
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','halls.hall_adress','halls.hall_details','price_hours','price_int','halls.hall_name','imagas.image_path')->where('halls.id',157)
->get();
$results=[];
foreach ($halls as $hall) {
$array=json_decode($hall->image_path,true);
if (is_array($array))
{
$hall->image_path = $array;
}
array_push($results, $hall);
}
return response()->json($results);
}
output like this
{
"id": 157,
"hall_name": "ali",
"hall_adress": "st-50",
"hall_details": null,
"price_hours": "3000",
"price_int": "500",
"image_path": [
"1579635535.jpg",
"1579635536.jpg",
"1579635537.png",
"1579635538.png"
]
}
but i need pass string path url to array and show output like this
{
"id": 157,
"hall_name": "ali",
"hall_adress": "st-50",
"hall_details": null,
"price_hours": "3000",
"price_int": "500",
"image_path": [
"http://127.0.0.1:8000/images_ravs/1579635535.jpg",
"http://127.0.0.1:8000/images_ravs/1579635536.jpg",
"http://127.0.0.1:8000/images_ravs/1579635537.png",
"http://127.0.0.1:8000/images_ravs/1579635538.png"
]
}
Iterate through the image array and add the rest of the URL.
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
foreach($array as $index => $image) {
$array[$index] = "http://127.0.0.1:8000/images_ravs/" . $image;
}
$hall->image_path = $array;
}
}
Hope this helps you.
I need to get the fist item an array from select database using loop for but when i do't my outfit display all the value for array
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($hall as $halls ) {
$array=$halls->image_path ;
for ($i=0; $i<$array; $i++) {
$halls=$array[0];
}
array_push($results, $halls);
}
return response()->json($results);
}
JSON Output
[
{ "id": 159,
"hall_name": "asdad",
"image_path": "[\"1579635948.jpg\",\"1579635948.jpg\",\"1579635948.png\",\"1579635948.png\"]"
},
{
"id": 160,
"hall_name": "dsfdsf",
"image_path": "[\"1579636069.jpg\",\"1579636069.png\",\"1579636069.png\",\"1579636069.png\"]"
},
]
I want to display the first value from all image_pathlike this
[ {
"id": 160,
"hall_name": "dsfdsf",
"image_path": "["1579636069.jpg"]"
},
]
You may use decode your $hall->image_path string before loop through it
public function index() {
$halls = DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results =[];
foreach ($halls as $hall) {
$array = json_decode($hall->image_path, true);
if (is_array($array)) {
$hall->image_path = reset($array) ?? NULL;
array_push($results, $hall);
}
}
return response()->json($results);
}
If I understand you correctly, you want the whole collection data but with modified image_path column, so it contains only the first path, right?
Here is the code using map helper function to output the collection as you desire:
public function index() {
$hall=DB::table('halls')
->join('imagas','halls.id','=','imagas.id_Halls')
->select('halls.id','halls.hall_name','imagas.image_path')
->get();
$results = $hall->map(function ($item, $key) {
is_array($item->image_path) ? [head($item->image_path)] : [$item->image_path];
return $item;
});
return response()->json($results);
// [ { "id": 159, "hall_name": "asdad", "image_path": "["1579635948.jpg"]" },
// { "id": 160, "hall_name": "dsfdsf", "image_path": "["1579636069.png"]" }]
}
I have a model "SalesContract" which has a "belongsTo" relationship with a class called "Asset". However, it does not work (I cannot set or get).
Could it be an issue with the "asset()" helper method?
If I change the name of my method to something like "related_asset()", then it works.
This does NOT work:
public function asset()
{
return $this->belongsTo(Asset::class);
}
This DOES work:
public function related_asset()
{
return $this->belongsTo(Asset::class);
}
Full model:
class SalesContract extends Model
{
use SoftDeletes;
use Commentable;
const icon_class = 'far fa-file-signature';
const default_buyer_fee = 100;
const default_carproof_fee = 36.45;
protected $fillable = [
'number', 'asset_id', 'seller_id', 'buyer_id', 'buyer_representative', 'sale_date', 'sale_price',
'apply_sales_taxes_to_sale_price', 'buyer_fee', 'carproof_fee', 'deposit'
];
protected $casts = [
'sale_date' => 'datetime',
'sale_price' => 'float',
'carproof_fee' => 'float',
'buyer_fee' => 'float',
'deposit' => 'float',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime'
];
protected $appends = [
'subtotal', 'taxable_amount', 'sales_taxes', 'total', 'balance'
];
protected static function boot()
{
parent::boot();
static::addGlobalScope('order', function (Builder $builder) {
$builder->orderBy('created_at', 'desc');
});
static::saving(function($table) {
if (empty($table->id)) {
if ($current_user = Auth::user()) {
$table->created_by_user_id = $current_user->id;
}
}
});
}
public function __construct(array $attributes = [])
{
if (empty($this->sale_date)) {
$this->sale_date = Carbon::today()->format('Y-m-d');
}
if (empty($this->id)) {
if (empty($this->number)) {
if ($asset = $this->asset) {
$this->number = $asset->external_file_number ?? $asset->internal_file_number;
}
}
$this->buyer_fee = $this->buyer_fee ?? self::default_buyer_fee;
$this->carproof_fee = $this->carproof_fee ?? self::default_carproof_fee;
$this->apply_sales_taxes_to_sale_price = $this->apply_sales_taxes_to_sale_price ?? 1;
}
parent::__construct($attributes);
}
public function __toString()
{
return __('sales_contracts.item_label', ['number' => $this->number ?? $this->id]);
}
public function scopeFilter($query, $filters)
{
$filters = is_array($filters) ? array_filter($filters) : [];
return $query->where($filters);
}
public function asset()
{
return $this->belongsTo(Asset::class);
}
public function seller()
{
return $this->belongsTo(Contact::class);
}
public function buyer()
{
return $this->belongsTo(Contact::class);
}
public function created_by_user()
{
return $this->belongsTo(User::class);
}
public function getSubtotalAttribute()
{
return $this->sale_price + $this->carproof_fee + $this->buyer_fee;
}
public function getTaxableAmountAttribute()
{
if ($this->apply_sales_taxes_to_sale_price) {
return $this->subtotal;
} else {
return $this->subtotal - $this->sale_price;
}
}
public function getSalesTaxesAttribute()
{
$sales_taxes = [];
if ($seller = $this->seller) {
foreach ($seller->sales_tax_numbers as $tax_number) {
if ($tax_number->use) {
if ($sales_tax = $tax_number->sales_tax) {
$sales_taxes[] = [
'sales_tax' => $sales_tax,
'name' => $sales_tax->name,
'rate' => $sales_tax->rate,
'label' => $sales_tax->label,
'number' => $tax_number->number,
'amount' => round($this->taxable_amount * $sales_tax->rate, 2)
];
}
}
}
}
return $sales_taxes;
}
public function getSalesTaxesTotalAttribute()
{
$total = 0;
foreach ($this->sales_taxes as $sales_tax) {
$total += $sales_tax['amount'];
}
return $total;
}
public function getTotalAttribute()
{
return $this->subtotal + $this->sales_taxes_total;
}
public function getBalanceAttribute()
{
return $this->total - $this->deposit;
}
}
From controller:
$sales_contract = new SalesContract;
if ($request->has('sales_contract')) {
$sales_contract->fill($request->input('sales_contract'));
}
Result of dd($request->input()):
array:1 [▼
"sales_contract" => array:1 [▼
"asset_id" => "11754"
]
]
(Yes, Asset with ID 11754 does exist.)
by default Name of relation is depended on 'foreign_key'
if you want to set different name of relation than foreign key just provide foreign key and other_key along with relation declaration
public function asset()
{
return $this->belongsTo(Asset::class,related_asset,id);
}
Problem solved.
I had to remove the following code from my __construct() method as it was breaking the relationship somehow:
if (empty($this->number)) {
if ($asset = $this->asset) {
$this->number = $asset->external_file_number ?? $asset->internal_file_number;
}
}