Payment Shopping cart - Laravel different Objects - laravel

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

Related

Laravel Session is not storing new items but it's overwriting

I was trying to add new items to a session container, and if old items are available then I'll just push the new items to the container. Now whenever I'm adding new items it's storing the current item by replacing the previous item, where is the issue?
In Controller my function to add new items
public function addToCart($id)
{
$product = Product::findOrFail($id);
$oldCart = Session::has("cart") ? Session::get("cart") : null;
$cart = new Cart($oldCart);
$cart->addNewItem($id, $product);
Session::put("cart", $cart);
dd(Session::get("cart"));
}
In Class
class Cart
{
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 addNewItem($id, $item)
{
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
$this->items[$id] = $storeNewItem;
}
}
In Cart Class
public function addNewItem($id,$item) {
$storeNewItem["product_id"] = $item->id;
$storeNewItem["product_name"] = $item->product_name;
$storeNewItem["product_price"] = $item->product_price;
$this->totalQty++;
$this->totalPrice += $item->product_price;
return [
'totalQty', => $this->totalQty,
'totalPrice', => $this->totalPrice,
'items[$id]', => $storeNewItem,
]
}
In Controller addToCart Function
$newCart = $cart->addNewItem($id,$product);
Session::put("cart",$newCart );

Trying to get property 'model_name' of non-object

So I get this error when I'm trying to use the voyager themes, I want to use the voyager's theme since the page is on the admin side so I want to make it uniform.
I realized that I also need to to extend the views so I create this controller
<?php
namespace App\Http\Controllers\Admin;
use App\Models\Toko;
use App\Models\SubOrder;
use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use RealRashid\SweetAlert\Facades\Alert;
use Illuminate\Database\Eloquent\SoftDeletes;
use TCG\Voyager\Database\Schema\SchemaManager;
use TCG\Voyager\Http\Controllers\VoyagerBaseController;
class OrderController extends VoyagerBaseController
{
//***************************************
// ____
// | _ \
// | |_) |
// | _ <
// | |_) |
// |____/
//
// Browse our Data Type (B)READ
//
//****************************************
public function index(Request $request)
{
// GET THE SLUG, ex. 'posts', 'pages', etc.
$slug = $this->getSlug($request);
// GET THE DataType based on the slug
$dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();
// Check permission
$this->authorize('browse', app($dataType->model_name));
$getter = $dataType->server_side ? 'paginate' : 'get';
$search = (object) ['value' => $request->get('s'), 'key' => $request->get('key'), 'filter' => $request->get('filter')];
$searchNames = [];
if ($dataType->server_side) {
$searchable = SchemaManager::describeTable(app($dataType->model_name)->getTable())->pluck('name')->toArray();
$dataRow = Voyager::model('DataRow')->whereDataTypeId($dataType->id)->get();
foreach ($searchable as $key => $value) {
$field = $dataRow->where('field', $value)->first();
$displayName = ucwords(str_replace('_', ' ', $value));
if ($field !== null) {
$displayName = $field->getTranslatedAttribute('display_name');
}
$searchNames[$value] = $displayName;
}
}
$orderBy = $request->get('order_by', $dataType->order_column);
$sortOrder = $request->get('sort_order', $dataType->order_direction);
$usesSoftDeletes = false;
$showSoftDeleted = false;
// Next Get or Paginate the actual content from the MODEL that corresponds to the slug DataType
if (strlen($dataType->model_name) != 0) {
$model = app($dataType->model_name);
if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
$query = $model->{$dataType->scope}();
} else {
$query = $model::select('*');
}
// Query menampilkan hanya toko pedagang
if(auth()->user()->hasRole('pedagang')) {
$query->where('user_id', auth()->id());
}
// Use withTrashed() if model uses SoftDeletes and if toggle is selected
if ($model && in_array(SoftDeletes::class, class_uses_recursive($model)) && Auth::user()->can('delete', app($dataType->model_name))) {
$usesSoftDeletes = true;
if ($request->get('showSoftDeleted')) {
$showSoftDeleted = true;
$query = $query->withTrashed();
}
}
// If a column has a relationship associated with it, we do not want to show that field
$this->removeRelationshipField($dataType, 'browse');
if ($search->value != '' && $search->key && $search->filter) {
$search_filter = ($search->filter == 'equals') ? '=' : 'LIKE';
$search_value = ($search->filter == 'equals') ? $search->value : '%'.$search->value.'%';
$query->where($search->key, $search_filter, $search_value);
}
if ($orderBy && in_array($orderBy, $dataType->fields())) {
$querySortOrder = (!empty($sortOrder)) ? $sortOrder : 'desc';
$dataTypeContent = call_user_func([
$query->orderBy($orderBy, $querySortOrder),
$getter,
]);
} elseif ($model->timestamps) {
$dataTypeContent = call_user_func([$query->latest($model::CREATED_AT), $getter]);
} else {
$dataTypeContent = call_user_func([$query->orderBy($model->getKeyName(), 'DESC'), $getter]);
}
// Replace relationships' keys for labels and create READ links if a slug is provided.
$dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType);
} else {
// If Model doesn't exist, get data from table name
$dataTypeContent = call_user_func([DB::table($dataType->name), $getter]);
$model = false;
}
// Check if BREAD is Translatable
$isModelTranslatable = is_bread_translatable($model);
// Eagerload Relations
$this->eagerLoadRelations($dataTypeContent, $dataType, 'browse', $isModelTranslatable);
// Check if server side pagination is enabled
$isServerSide = isset($dataType->server_side) && $dataType->server_side;
// Check if a default search key is set
$defaultSearchKey = $dataType->default_search_key ?? null;
// Actions
$actions = [];
if (!empty($dataTypeContent->first())) {
foreach (Voyager::actions() as $action) {
$action = new $action($dataType, $dataTypeContent->first());
if ($action->shouldActionDisplayOnDataType()) {
$actions[] = $action;
}
}
}
// Define showCheckboxColumn
$showCheckboxColumn = false;
if (Auth::user()->can('delete', app($dataType->model_name))) {
$showCheckboxColumn = true;
} else {
foreach ($actions as $action) {
if (method_exists($action, 'massAction')) {
$showCheckboxColumn = true;
}
}
}
// Define orderColumn
$orderColumn = [];
if ($orderBy) {
$index = $dataType->browseRows->where('field', $orderBy)->keys()->first() + ($showCheckboxColumn ? 1 : 0);
$orderColumn = [[$index, $sortOrder ?? 'desc']];
}
$view = 'voyager::bread.browse';
if (view()->exists("voyager::$slug.browse")) {
$view = "voyager::$slug.browse";
}
// $order = SubOrder::class;
// $items = $order->items;
$tokoId = Toko::select('id')->firstWhere('user_id', auth()->id())->id;
// $orders = SubOrder::where('toko_id', $tokoId)->orderBy('created_at', 'desc')->get();
$orders = SubOrder::with('items')->where('toko_id', $tokoId)->orderBy('created_at', 'desc')->get();
return view('sellers.order.index', compact(
// 'items',
'orders',
'actions',
'dataType',
'dataTypeContent',
'isModelTranslatable',
'search',
'orderBy',
'orderColumn',
'sortOrder',
'searchNames',
'isServerSide',
'defaultSearchKey',
'usesSoftDeletes',
'showSoftDeleted',
'showCheckboxColumn'
));
}
// public function show(SubOrder $order)
// {
// $items = $order->items;
// return view('sellers.order.show', compact('items'));
// }
public function markTolak(SubOrder $suborder)
{
$suborder->status = 'gagal';
$suborder->save();
Alert::info('Order di Proses!', 'Order ditandai proses!');
return redirect('/seller/orders')->withMessage('Order ditandai proses');
}
public function markProses(SubOrder $suborder)
{
$suborder->status = 'proses';
$suborder->save();
Alert::info('Order di Proses!', 'Order ditandai proses!');
return redirect('/seller/orders')->withMessage('Order ditandai proses');
}
public function markDelivered(SubOrder $suborder)
{
$suborder->status = 'selesai';
$suborder->save();
// Check all sub order complete
$pendingSubOrders = $suborder->order->subOrders()->where('status','!=', 'selesai')->count();
if($pendingSubOrders == 0) {
$suborder->order()->update(['status'=>'selesai']);
}
Alert::success('Order Selesai!', 'Order ditandai selesai!');
return redirect('/seller/orders')->withMessage('Order ditandai selesai');
}
}
it shows that the error is from the line 42 where it checks the permission and couldn't find the "model_name". please help
Or maybe if there's another way to use the template?

Undefined property: App\Cart::$totalPrice

Hello I am making a cart but when I click on add to cart link then it says:
Undefined property: App\Cart::$totalPrice
Error: https://ibb.co/ysB5CfG
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request, $qty= null)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product, $qty);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
routes:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
// Add to cart
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');
You should use get() methods in cart() function in controller file.
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::get('cart');
return view('product.cart', compact('cart'));
}

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/

Group By Condition in an Eloquent Query

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();

Resources