I have to export excel by joining two tables but I can't understand the way to complete this I'll attach the screenshot of my tables and codes. Please help me to solve these issues.
Table One: Decoration
Table Two: Decoration Price
Sample Data
Decoration.php Model Page
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Decoration extends Model
{
protected $table='decoration';
protected $fillable=['deco_print_type','deco_prod_code','deco_supp_code','deco_name','deco_logo_setup_charge','deco_main_type','deco_is_main_type','deco_weight_for_sorting','deco_priority','deco_is_shown_to_clients'];
public static function getDecoration()
{
$Decoration = DB::table('decoration')
->select('deco_print_type','deco_name','deco_prod_code','deco_priority','deco_rank','deco_logo_setup_charge','deco_is_shown_to_clients')
->where('deco_flag','=','1')->orderBy('deco_print_type','ASC')->get()->toArray();
foreach ($Decoration as $deco)
{
$decoPrice = DB::table('decoration_price')
->select('decp_quantity','decp_quantity')
->where('decp_print_type','=',$deco->deco_print_type)
->orderBy('decp_qty_break_leve','ASC')->get()->toArray();
//$Decoration[$i]=$decoPrice;
}
return $Decoration;
}
}
Exports/DecorationExport.php Page code
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Illuminate\Support\Facades\DB;
use App\Decoration;
use App\Decoration_Price;
class DecorationExport implements FromCollection,WithHeadings
{
public function headings(): array
{
// TODO: Implement headings() method.
return [
"Decoration code",
"Decoration name",
"Main decoration",
"Priority",
"Rank",
"Setup Charge",
"Shown_to_clients",
"A2",
"B2",
"A3",
"B3",
"A4",
"B4",
"A5",
"B5",
"A6",
"B6",
"A7",
"B7",
"A8",
"B8",
"A9",
"B9",
];
}
/**
* #return \Illuminate\Support\Collection
*/
public function collection()
{
return collect(Decoration::getDecoration());
}
}
Decoration Route Function for download
public function DecoBulkExport()
{
$decoration = new DecorationExport;
return Excel::download($decoration,'Decoration.csv');
}
When I click the export button data file should become like this.
Please Help me or advise me on how to do this
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 use DTO from Spatie in Laravel.
The DTO model looks like:
<?php
namespace Domain\Subscriber\DataTransferObjects;
use Spatie\LaravelData\Data;
class Rating {
public int $rateid;
public int $rate;
}
class RateData extends Data
{
public Rating $rating = array();
public function __construct() {
}
}
I fetch the request inside controller:
{"rating": [{"rateid": 1, "rate": 4}]}
How to fill the DTO by this request?
Controller is:
class RateController extends Controller
{
public function index(Request $request)
{
$RateData = new RateData()
$service->setRate();
}
I see no point in wrapping Rating in RateData, as it is just simple data.
class Rating extends Data
{
public int $rateid;
public int $rate;
}
In your controller.
foreach ($request->get('rating') as $ratingData) {
$rating = Rating::from(
[
'rateid' => $ratingData['rateid'],
'rate' => $ratingData['rate'],
]
);
}
Just a general tip, keep consistent with naming, that is gonna help you in the long run.
Pascal case is used for $RateData and the DTO, uses all lowercase on $rateid;. PHP property for an example should be camel cased. $rateId or $rateData.
I am fixing an existing Symfony 5.4 website running on PHP 8.0.18. The back office is handled by EasyAdmin 3.4.
I can't figure out what's wrong. Like the title says, when I go to edit an "Event" entity, the save buttons won't work at all unless I re-upload a different event picture. No amount of editing the other fields will work, and I can use the save buttons on other entities even if I have made no modification to the entity. I've looked though my configuration and entity setup but so far, I don't get it.
Edit: other entities with ImageField also refuse to be updated unless I've re-uploaded something. I found a temporaty fix by using setRequired(false) in the event crud conf, but an image is definitely required in this case, so I'm just setting myself up for a different kind of failure if I'm not mistaken. Is this really the only way?
Event entity:
<?php
namespace App\Entity;
use App\Repository\EventRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=EventRepository::class)
*/
class Event
{
// ...
/**
* #ORM\Column(type="string", length=255)
*/
private $src;
// ...
public function getSrc(): ?string
{
return $this->src;
}
public function setSrc(string $src): self
{
$this->src = $src;
return $this;
}
// ...
}
Event crud controller:
<?php
namespace App\Controller\Admin;
use App\Entity\Event;
use App\Entity\TranslationString;
use App\Entity\TranslationText;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IntegerField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
class EventCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Event::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setSearchFields([
'date',
'end',
'title.fr',
'title.en',
'body.fr',
'body.en',
'alt.fr',
'alt.en',
])
->setDefaultSort(['archived' => 'ASC','date' => 'DESC',]);
}
public function configureFields(string $pageName): iterable
{
return [
DateField::new('date'),
DateField::new('end'),
TextField::new('titleFr'),
TextField::new('titleEn')->hideOnIndex(),
BooleanField::new('isShow'),
BooleanField::new('archived'),
TextareaField::new('bodyFr'),
TextareaField::new('bodyEn')->hideOnIndex(),
ImageField::new('src')
->setBasePath('img/events')
->setUploadDir('www/img/events'),
TextareaField::new('altFr')->hideOnIndex(),
TextareaField::new('altEn')->hideOnIndex(),
];
}
public function createEntity(string $Fqcn): Event
{
return (new Event)
->setAlt(new TranslationText)
->setTitle(new TranslationString)
->setBody(new TranslationText);
}
}
I had the same problem and I think that the following code will help
public function configureFields(string $pageName): iterable {
$imageField = ImageField::new('image', 'Image')->setUploadDir('public/uploads/images/')->setBasePath('uploads/images/');
if ($pageName != 'new') {
$imageField->setRequired(false);
}
return [
TextField::new('title'),
$imageField,
TextEditorField::new('description')->setNumOfRows(20),
UrlField::new('ticketOfficeLink'),
AssociationField::new('eventStates')
];
}
I have a model named 'Poll'. Inside Poll model I defined a boot method like follows:
public static function boot()
{
parent::boot();
self::created(function($model){
// dd($model);
$speakers = $model->speakers()->get();
// dd($speakers);
// What I want to do here is: create poll options relation from speakers as follows
// $poll->poll_options()->create([
// 'option' => $speaker->name,
// ]);
}
}
I am adding the speakers relation and it is working perfect.
But inside this boot method, inside self::created if I tried to get the speakers relation, it is always empty (dd($speakers) line). Is it because of the boot method runs just after the model is saved into DB and the relations not at all saved?
I am getting newly created model in the line: dd($model) mentioned in the code.
UPDATE
I tried with events also.
My Poll Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
use Cookie;
use App\Events\PollCreated;
class Poll extends Model
{
........
protected $events = [
'created' => PollCreated::class,
];
.......
public function speakers()
{
return $this->belongsToMany('App\Models\Speaker','poll_speaker','poll_id','speaker_id');
}
}
app/Events/PollCreated.php:
namespace App\Events;
use App\Models\Poll;
use Illuminate\Queue\SerializesModels;
class PollCreated
{
use SerializesModels;
public $poll;
/**
* Create a new event instance.
*
* #param Poll $poll
* #return void
*/
public function __construct(Poll $poll)
{
// $this->poll = $poll;
$event = $poll->event()->first();
// dd($event);
// dd($poll->speakers()->get());
// dd($poll->load('speakers'));
}
}
Here also I am not getting speakers, in the line: dd($poll->speakers()->get());
my Speaker model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\CrudTrait;
class Speaker extends Model
{
use CrudTrait;
……..
public function polls()
{
return $this->belongsToMany('App\Models\Poll');
}
……..
}
The problem is with timing as models must always be created before they can be set in a many-to-many relationship. So there is no possible way that in a many-to-many relationship during the created event the relationship is already set as the created events are always raised before the relationships.
Anyone looking for a solution can probably experiment with the chelout/laravel-relationship-events package as this adds relationship events to models.
To be sure, I tested this out with a simple application of users and computers.
User.php
class User extends Model
{
use HasBelongsToManyEvents;
public static function boot() {
parent::boot();
self::created(function($model){
Log::info('user::created');
});
static::belongsToManyAttaching(function ($relation, $parent, $ids) {
$ids = implode(' & ', $ids);
Log::info("Attaching {$relation} {$ids} to user.");
});
static::belongsToManyAttached(function ($relation, $parent, $ids) {
$ids = implode(' & ', $ids);
Log::info("Computers {$ids} have been attached to user.");
});
}
public function computers() {
return $this->belongsToMany(Computer::class, 'user_computers');
}
}
Computer class is the same in reverse. And for the following code:
$user = User::create();
$user->computers()->attach([
Computer::create()->id,
Computer::create()->id
]);
This was the outcome:
user::created
computer::created
computer::created
Attaching computers 69 & 70 to user.
Computers 69 & 70 have been attached to user.
So, I am using Laravel 5 and Fractal to add presentation and transformation layer for my data output and was wondering what I am doing below is correct or overkill.
I have Users table and Favourites table and I want my JSON to be outputted like below:
Note: Pay close attention to profile_id and id in the nested data. I basically want my favourites and within those the user's details (from Users table) that I have favourited.
Below, I have favourited profile_id 404 and his details (from users table) is nested too.
"data": [
{
"id": 15,
"user_id": 231,
"profile_id": 404, <------------------------ HERE
"created_date": "2013-04-10 21:35:28",
"user": {
"data": {
"id": 404, <------------------------ HERE
"username": "hugeheart12",
"has_photo": 1
}
}
},
{
"id": 64,
"user_id": 231,
"profile_id": 1085, <------------------------ HERE
"created_date": "2013-06-17 08:14:02",
"user": {
"data": {
"id": 1085, <------------------------ HERE
"username": "snowbird37",
"has_photo": 1
}
}
}
Users
id (PK)
name
username
email
created_date
Favourites
id
user_id
profile_id
created_date
Users Model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Support\Facades\DB;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
public function favourites()
{
return $this->hasMany('App\Favourites', 'profile_id', 'id');
}
public function photos()
{
return $this->hasMany('App\Photos', 'user_id', 'id');
}
Favourite Models
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Favourites extends Model {
protected $table = 'favourite';
public function user()
{
return $this->belongsTo('App\User', 'from', 'id');
}
}
This is what I have in my controller:
$favourites = Favourites::with('user')->where('profile_id', '=', 231)->get();
$resource = new Fractal\Resource\Collection($favourites , new FavouriteTransformer());
return $this->respond(
$this->fractal->createData($resource)->toArray()
);
FavouriteTransformer
<?php
namespace App\Mmh\Transformer;
use App\Favourites;
use League\Fractal;
class FavouriteTransformer extends Fractal\TransformerAbstract
{
protected $defaultIncludes = [
'user'
];
public function transform(Favourites $favourites)
{
return [
'id' => (int)$favourites->id,
'user_id' => (int)$favourites->user_id,
'profile_id' => (int)$favourites->profile_id,
'created_date' => $favourites->created_date,
];
}
public function includeUser( Favourites $favourites )
{
return $this->item(
$favourites->user->find($favourites->profile_id), new UserTransformer
);
}
}
Look at the last return return $this->item( $favourites->user->find($favourites->profile_id), new UserTransformer );
All that code above gives me the JSON above but is there any way of doing this a better way or the way I am doing it is correct? Something tells me there must be a better way of doing this than querying the database for every item but I don't know how.
Thank you for reading.
You already eager-load the user in the controller, so i don't think you need to call user for each favourites again in the FavouriteTransformer.
You can simply use this to include the user
return $this->item(
$favourites->user, new UserTransformer
);
Fractal will see that, the user is already exist, so it won't call db query to grab the data.