Group By Condition in an Eloquent Query - laravel

I have an error when i try to make a Group By condition in my query , i get this exception :
Call to undefined method Illuminate\Database\Query\Builder::isEmpty()
Someone knows why i get this error ? It's because i didn't created a Scope in my Model ? Thanks a lot in advance friends .
Here my controller :
public function index(Request $request){
$compet = Compet::pluck('lb_compet' , 'id');
$structure = Structure::select('num_structure', 'nom_structure' , 'id')
->where('type_structure_id' , '1')
->orWhere('type_structure_id' , '2')
->orWhere('type_structure_id' , '3')
->get()
->mapWithKeys(function($i) {
return [$i->id => $i->num_structure.' - '.$i->nom_structure];
});
$catg_compet = CategorieCompet::pluck('lb_categorie_compet' , 'id');
$fonction = FonctionOfficiel::pluck('lb_fonction' , 'id');
$bareme = Bareme::pluck('lb_bareme' , 'id');
$licence = Licencies::select('lb_nom', 'num_licence', 'lb_prenom', 'id' , 'structure_id' , 'activite_licencie_id')
->where('type_licence_id' , '1')
->get()
->mapWithKeys(function($i) {
return [$i->id => $i->lb_nom.' - '.$i->lb_prenom.' - n°'.$i->num_licence.' - '.$i->activite_licencie->lb_activite.' - '.$i->structure->nom_structure];
});
$query = RencontreOfficiel::query()->orderBy('licencie_id');
$filters = [
'licencie_id' => 'licencie_id',
'compet_id' => 'compet_id',
'structure_id' => 'structure_id',
'catg_compet_id' => 'dt_rencontre',
'fonction_id' => 'dt_rencontre',
'bareme_id' => 'bareme_id',
'dt_min_rencontre' => 'dt_rencontre',
'dt_max_rencontre' => 'dt_rencontre',
];
$dt_min = $request->input('dt_rencontre_min');
$dt_max = $request->input('dt_rencontre_max');
foreach ($filters as $key => $column) {
$query->when($request->{$key}, function ($query, $value) use ($column , $dt_min , $dt_max) {
$query->where($column, $value)
->orWhereBetween('dt_rencontre' , [$dt_min , $dt_max]);
});
}
// group by licence
$designations = $query->groupBy('licencie_id');
return view('designations/index' , compact('licence' , 'designations' , 'compet' , 'structure' , 'catg_compet' , 'fonction' , 'bareme'));
}
Here my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Laravel\Scout\Searchable;
class Licencies extends Model
{
protected $table = 'licencies';
public $timestamps = true;
protected $fillable = array('lb_nom', 'lb_photo', 'lb_prenom', 'dt_naissance', 'cd_dept_naissance', 'lb_ville_naissance', 'adresse_email');
// use Searchable;
public function structure()
{
return $this->belongsTo('App\Structure');
}
public function club()
{
return $this->belongsTo('App\Club');
}
public function pays()
{
return $this->belongsTo('App\Pays' , 'pays_naissance_id');
}
public function activite_licencie()
{
return $this->belongsTo('App\ActiviteLicencie' , 'activite_licencie_id');
}
public function saison()
{
return $this->belongsTo('App\Saison' , 'saison_id');
}
public function statut_licence()
{
return $this->belongsTo('App\LicenceStatut');
}
public function nationalite()
{
return $this->belongsTo('App\Nationalite');
}
public function civilite()
{
return $this->belongsTo('App\Civilite');
}
public function categorie_age() {
return $this->belongsTo('App\CatgLicence' , 'catg_licence_id');
}
public function valide(){
return $this->belongsTo('App\LicenceValid' , 'valid_licence_id');
}
public function sanctions(){
return $this->hasMany('App\LicenceSanction' , 'licencie_id');
}
public function type_licence(){
return $this->belongsTo('App\Type_licence');
}
public function equipes(){
return $this->belongsToMany('App\Equipe');
}
public function selections(){
return $this->belongsToMany('App\SelectionLicence' , 'licencie_id');
}
public function getAgeAttribute()
{
return Carbon::parse($this->attributes['dt_naissance'])->diff(Carbon::now())->format('%y ans');
}
public function getSexeAttribute(){
return str_limit($this->civilite->lb_civilite, 1 , '');
}
public function getActiviteAttribute(){
return $this->activite_licencie->lb_activite;
}
//public function getNumLicencieAttribute() {
// $first = substr($this->num_licence, 0, 2); //from position 0, take 2 digits
// $second = substr($this->num_licence, 2, 2); //from position 2, take 2
// $third = substr($this->num_licence, 4); //from 4 take the rest.
// return $first . '-' . $second . '-' . $third;
// }
}

I think you are just missiong model class object here
// group by licence
$designations = $query->groupBy('licencie_id');
you need to use Licencies object of model like
// group by licence
$designations = Licencies::groupBy('licencie_id')->get();

Related

Attempt to read property "ref_department_id" on null in laravel 8

My problem is its hard to get the data from relationship field. There is no null value in table but the error shows attempt to read null value.The data connected with api.Its work when i put if and else but i cant figure out the correct solution for this problem.
Here is my function.php line
function getUnitClerk($unit_id){
$unit = Unit::where('id', $unit_id)->first();
$division = Division::where('id', $unit->ref_division_id)->first();
$department = Department::where('id', $division->ref_department_id)->first();
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Platform\Bpms;
use Session;
use Illuminate\Support\Facades\DB;
use App\User;
class AdminController extends Controller
{
public function __construct()
{
$this->middleware('guest');
}
public function dashboard()
{
if(!auth()->check())
{
return redirect('login')->with('message', 'Please log in!');
}else{
$roleOfUser = DB::table('role_of_user')->where('user_id','=',auth()->user()->id)->get();
$tasklist = Bpms::queryForTaskListByAssignee(auth()->user()->id);
$list_role = '';
if(count($roleOfUser) > 0){
foreach($roleOfUser AS $roleUser){
if($roleUser != ''){
$grouptasklist = Bpms::queryForTaskList($roleUser->role_name);
$tasklist = array_merge($tasklist, $grouptasklist);
$list_role .= $roleUser->role_name;
$list_role .= ",";
}else{
$tasklist = array();
}
}
}
if(count($tasklist) > 0){
foreach ($tasklist as $i => $task) {
$taskname = $task['taskDefinitionKey'];
$overdue = 'overdue';
if((stripos($taskname, $overdue) !== FALSE)){
$overdue_task2[] = 1;
}else{
$overdue_task2[] = 0;
}
}
$overdue_task = array_sum($overdue_task2);
}else{
$overdue_task = 0;
}
$new = DB::table('history')->where('history_status', '=', 2)->where('history_sender_id','=',auth()->user()->id)->get();
$newtask = count($new);
$inprogress = count($tasklist);
$closed = DB::table('history')
->whereRaw('(history_status = 6)')
->where('created_by','=',auth()->user()->id)
->get();
$closedtask = count($closed);
$lastlogin = DB::table('audit_trail')
->where('adt_action_name', '=', 1)
->where('adt_created_by','=',auth()->user()->id)
->orderBy('adt_created_date', 'desc')
->skip(1)
->take(1)
->first();
// echo '<pre>';
// print_r($tasklist);
// $historyCheck = DB::table('history')->where('history_taskid','=',88989)->exists();
// if($historyCheck)
// {
// $history = DB::table('history')->where('history_taskid','=',88989)->first();
// print_r($history);
// $recordrequest = DB::table('ddms_record_request')->where('ddms_request_id','=',$history->history_request_id)->first();
// print_r($recordrequest);
// exit;
// $requestnumber = DB::table('ddms_request')->where('id','=',$recordrequest->ddms_request_id)->first();
// } else {
// $history = array();
// $recordrequest = array();
// $requestnumber = array();
// }
return view('main.dashboard',compact('tasklist','newtask','inprogress','closedtask', 'overdue_task', 'lastlogin'));
}
}
}
?>
unit model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Unit extends Model
{
protected $table = 'ref_unit';
public function division() {
return $this->belongsTo(division::class,'ref_division_id','id');
}
public function section() {
return $this->hasMany(section::class,'ref_unit_id','id');
}
}
Division Model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Division extends Model
{
protected $table = 'ref_division';
public function department() {
return $this->belongsTo(department::class,'ref_department_id','id');
}
public function unit() {
return $this->hasMany(unit::class,'ref_division_id','id');
}
}
Department Model
namespace App\Models\References;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $table = 'ref_department';
public function tenant() {
return $this->belongsTo('App\Models\References\Tenant','ref_tenant_id','id');
}
public function departmentdetail() {
return $this->hasMany(departmentdetail::class,'ref_department_id','id');
}
public function division() {
return $this->hasMany(division::class,'ref_department_id','id');
}}

Laravel export Maatwebsite/Excel, restructuring the output

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;
}
}

Can I use a belongsTo method with name 'asset'?

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;
}
}

Inserting Data in Pivot Table

The two tables tbl_product_manager and tbl_tags with many to many relations. I used eloquent to to make a relations between the corresponding models. I am able to to insert the data in these two table but the problem is the pivot table is not updated correspondingly.
Controller.php:
public function addProduct()
{
$rules = array('product_name' => 'required',
'product_url' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Some fields are missing');
return View::make('admin.product.add');
}
else {
$productName = Input::get('product_name');
$productUrl = Input::get('product_url');
$productUrl = preg_replace('/[^A-Za-z0-9\-]/', '', $productUrl);
$productExist = ProductManagementModel::checkExist($productUrl);
if( count($productExist)!=0) {
$message = 'product <b>'.$productName.'</b> with url <b>'.$productUrl.'</b> is already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product.add');
}
else {
$imageFile = Input::file('userfile');
$destinationPath = 'uploads/products/';
$rEFileTypes = "/^\.(jpg|jpeg|gif|png){1}$/i";
$maximum_filesize = 1 * 1024 * 1024;
if($imageFile) {
$filename = $imageFile->getClientOriginalName();
$extension = strrchr($filename, '.');
$size = $imageFile->getSize();
$new_image_name = "products" . "_" . time();
if ($size <= $maximum_filesize && preg_match($rEFileTypes, $extension)) {
$attachment = $imageFile->move($destinationPath, $new_image_name.$extension);
} else if (preg_match($rEFileTypes, $extension) == false) {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Warning : Invalid Image File!');
return View::make('admin.product_management.add');
} else if ($size > $maximum_filesize) {
Session::flash('class', 'alert alert-error');
Session::flash('message', "Warning : The size of the image shouldn't be more than 1MB!");
return View::make('admin.product_management.add');
}
}
$logo = isset($attachment) ? $new_image_name . $extension : NULL;
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectTags = new TagModel;
$objectTags->size_id = Input::get('size_id');
$objectTags->brand_id = Input::get('brand_id');
$objectTags->color_id = Input::get('color_id');
$objectTags->food_id = Input::get('food_id');
$objectTags->save();
//$tag = new TagModel::all();
$objectProduct->save();
if(isset($request->tags)) {
$post->Tags()->sync($request->tags, false);
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
}
}
ProductManagementModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class ProductManagementModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'product_manager';
public function Tags(){
return $this->belongsToMany('TagModel', 'product_tag', 'product_id', 'tag_id');
}
public function Categories(){
return $this->hasOne('CategoriesModel', 'id');
}
public static function getAllProducts(){
return $products = ProductManagementModel::with('categories','tags')->get();
}
public static function checkExist($url)
{
return $products = DB::table('product_manager')
->where('is_deleted', 0)
->where('product_url', $url)
->first();
}
}
TagModel.php
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class TagModel extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'tag';
public function ProductManagents() {
return $this->belongsToMany('ProductManagentModel');
}
public function Color(){
return $this->hasOne('ColorModel', 'color_id');
}
public function Brand() {
return $this->hasOne('BrandproModel','brand_id');
}
public function size() {
return $this->hasOne('SizeModel','size_id');
}
public function food() {
return $this->hasOne('FoodModel','food_id');
}
}
During my research i found that using sync function will be appropriate to updated the pivot table. But I failed to use it.
I am expecting to resolve this problem or something new way to find out the solution.
Thanks in advance.
Look at attach, detach or synch method :
https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships
Note it's more easily if you respect the eloquent naming convention
http://www.rappasoft.com/articles/laravel-eloquent-naming-convention-guide/

Payment Shopping cart - Laravel different Objects

I try to add different objets to my shopping Cart view in laravel, but I get an exception when I try to add different objects to the view. I would like to know if someone knows a good practice to achieve this.
Here my Class to get item type number 1:
<?php
namespace App;
class CartCotisationStructure
{
public $items = null ;
public $totalQty = 0 ;
public $totalPrice = 0 ;
public function __construct($oldCart)
{
if ($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item , $id){
$storedItem = ['qty' => 0 , 'montant' => $item->montant , 'item' => $item];
if($this->items){
if(array_key_exists($id , $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->montant * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->montant;
}
}
here my item type number two :
<?php
namespace App;
class CartLicenceStructure
{
public $items = null ;
public $totalQty = 0 ;
public $totalPrice = 0 ;
public function __construct($oldCart)
{
if ($oldCart){
$this->items = $oldCart->items;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function add($item , $id){
$storedItem = ['qty' => 0 , 'mt_cotisation' => $item->activite_licencie->mt_cotisation , 'item' => $item];
if($this->items){
if(array_key_exists($id , $this->items)){
$storedItem = $this->items[$id];
}
}
$storedItem['qty']++;
$storedItem['price'] = $item->activite_licencie->mt_cotisation * $storedItem['qty'];
$this->items[$id] = $storedItem;
$this->totalQty++;
$this->totalPrice += $item->activite_licencie->mt_cotisation;
}
}
here my controller for LicenceStructure :
public function getAddToCart(Request $request , $id){
$licencie = LicencieStructure::find($id);
$oldCart = Session::has('CartLicenceStructure') ? Session::get('CartLicenceStructure') : null ;
$cart = new CartLicenceStructure($oldCart);
$cart->add($licencie , $licencie->id);
$request->session()->put('CartLicenceStructure' , $cart);
return redirect()->route('home')->with('status', 'Le licencié à bien été ajouté au panier');;
}
public function getCart()
{
if(!Session::has('CartLicenceStructure')){
return view('shop.panier');
}
$oldCart = Session::get('CartLicenceStructure');
$cart = new CartLicenceStructure($oldCart);
return view('shop.panier' , ['licencies' => $cart->items , 'totalPrice' => $cart->totalPrice]);
}
here my controller for Cotisations
public function getAddToCartCotisation(Request $request , $id){
$cotisation = CotisationStructure::find($id);
$oldCart = Session::has('CartLicenceStructure') ? Session::get('CartCotisationStructure') : null ;
$cart = new CartCotisationStructure($oldCart);
$cart->add($cotisation , $cotisation->id);
$request->session()->put('CartCotisationStructure' , $cart);
return redirect()->route('home')->with('status', 'La cotisation à bien été ajouté au panier');;
}
public function getCartCotisation()
{
if(!Session::has('CartCotisationStructure')){
return view('shop.panier');
}
$oldCart = Session::get('CartCotisationStructure');
$cart = new CartCotisationStructure($oldCart);
return view('shop.panier' , ['cotisations' => $cart->items , 'totalPrice' => $cart->totalPrice]);
}
And here my view ( who make an exception when i want to add two different items , "undefined variable "licences" )
#if(Session::has('CartLicenceStructure'))
#foreach($licencies as $licencie)
// display the items
#endforeach
#elseif(Session::has('CartCotisationStructure')
#foreach($cotisations as $cotisation)
// display the items
#endforeach

Resources