farshadf

farshadf

Member Since 8 Months Ago

Experience Points
4,910
Total
Experience

90 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
5
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
4,910 XP
Dec
16
4 hours ago
Activity icon

Replied to How To Test 50k Users In Laravel Application

@martal i will check it out on my project thanks for the guide

Activity icon

Replied to How To Test 50k Users In Laravel Application

when my application Hosts 50k users it gets slow i want to find the bottle necks and fix them to increase the capacity to like 100k and thats it i want to see which part has problem i am sorry if ive not been clear enough :)

Activity icon

Replied to How To Test 50k Users In Laravel Application

thanks bro but i didnt get it how can it be possible to test whole application , is it like this to make factories for every single model and run them like 50k times ??

Activity icon

Started a new Conversation How To Test 50k Users In Laravel Application

hi , i have an application and i want to test to see if it can handle 50k users or not , how can i test it is there any good tool for laravel to test application capacity ?? thanks

Dec
05
1 week ago
Activity icon

Replied to How To Write A Package For Laravel

Thanks man .

Dec
04
1 week ago
Activity icon

Replied to How To Write A Package For Laravel

Thanks @bobbybouwmann that helped alot , you saved me a day :)are there any resources upon writing a package standards too or no you should get that by experience ??

Activity icon

Started a new Conversation How To Write A Package For Laravel

i wanted to write some kind of package for laravel like telescope or any thing else but i dont know how to start to write package for laravel and publish that in github . is there any offical resource to teach the structure you need to write a package for laravel and include it with composer ???

Dec
02
2 weeks ago
Activity icon

Started a new Conversation How To Push Values Of An Array Into Thier Own Item Of Object In Laravel

i have an object to return like below : (the dd result)

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▼
          #fillable: array:19 [▶]
          #connection: "mysql"
          #table: "room_pricing_histories"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:26 [▶]
          #original: array:26 [▼
            "id" => 4132
            "accommodation_room_id" => 3943
            "net_price" => null
            "board_price" => null
            "foreign_board_price" => null
            "sales_price" => 4200000
            "extra_bed_price" => null
            "half_charge_price" => null
            "half_board_price" => null
            "full_board_price" => null
            "foreign_net_price" => null
            "foreign_sales_price" => null
            "foreign_extra_bed_price" => null
            "foreign_half_charge_price" => null
            "foreign_half_board_price" => null
            "foreign_full_board_price" => null
            "operator_id" => 11
            "commission_percent" => null
            "foreign_commission_percent" => null
            "discount_percent" => 10.0
            "foreign_discount_percent" => null
            "from_date" => "2019-05-25 00:00:00"
            "to_date" => "2029-08-30 23:59:59"
            "is_deleted" => 0
            "created_at" => "2019-05-25 13:30:00"
            "updated_at" => "2019-05-25 13:30:00"
          ]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: array:1 [▶]
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
          #enableLoggingModelsEvents: true
          #oldAttributes: []
        }
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▶}
  ]
}

and i have some mapped data like below :

Collection {#1422 ▼
  #items: array:2 [▼
    3943 => 8400000
    3944 => 400
  ]
}

now what i want to do is to return the mapped data which is the sum of price according to the id they have so the result of each item has the sum of price in it like below :

{
//room pricing history
 id:923
room_id:3943
sum_of_prices :8400000
},
{
//room pricing history
 id:924
room_id:3944
sum_of_prices :600
}

note : i am currently using resource but i dont know how to push the data in thier own object for example with this condition that they have the same id or something .

Activity icon

Replied to How To Sum A Collection After GroupBy Laravel

@nakov is there any way to push the values back to models and return them in json ?? or i should clear that in another question ??

Activity icon

Started a new Conversation How To Sum A Collection After GroupBy Laravel

i have a collection named detailed as below :

Collection {#1421 ▼
  #items: array:2 [▼
    3943 => Collection {#1419 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#923 ▶}
        1 => RoomPricingHistory {#1042 ▶}
      ]
    }
    3944 => Collection {#1420 ▼
      #items: array:2 [▼
        0 => RoomPricingHistory {#1153 ▶}
        1 => RoomPricingHistory {#1264 ▶}
      ]
    }
  ]
}

now i want to get the sum of RoomPricingHistory for 3943 item and 3944 ofc it can be more of 2 item so i want to get the sum of each collection how can i achieve that ??

Activity icon

Replied to How To Detect Some Items Of An Object With Same Value In Relation In Laravel

@christophharms thanks i think i have to Change my Approach to it because it Again Returns the Result of Sum of all rooms price for all dates which i dont want i want to get the sum of price for each room for the period .

Activity icon

Replied to How To Get The Sum Of 2 Array With The Same Id In A Collection

i got there with another approach of getting the same collection i didnt think that would be spam sorry :)

Activity icon

Started a new Conversation How To Get The Sum Of 2 Array With The Same Id In A Collection

i have an array of collections with some same occurrences like below :

array:6 [▼
  0 => Collection {#926 ▶}
  1 => Collection {#926 ▶}
  2 => Collection {#1045 ▶}
  3 => Collection {#1045 ▶}
  4 => Collection {#1156 ▶}
  5 => Collection {#1156 ▶}
]

now what i want to do is to is to get the sum of those who repeated like 926 so i would have 2 prices to sum because 926 occurred 2 times . how can i achieve that thanks !

Activity icon

Replied to How To Detect Some Items Of An Object With Same Value In Relation In Laravel

sorry for being unclear i paste my whole method here now :

 $from_date = $request->get('from_date');
        $to_date = $request->get('to_date');
        $acc_id = $request->get('acc_id');
        $room_price = [];
        $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
        $room_ids = AccommodationRoom::where('accommodation_id',$acc_id)->pluck('id')->toArray();
//        dd($room_ids);
        for ($f = 0; $f < count($room_ids); $f++) {

            for ($i = 0; $i < count($dates); $i++) {

                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price[] = RoomPricingHistory::with('accommodationRoom', 'accommodationRoom.roomCapacityHistoryLast')
                    ->where('accommodation_room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortBy('created_at')
                    ->take(1);
                $test[] = $room_price[$f];
            }
        }
        $room = collect($room_price);
        $room_collection= $room->flatten();
        // $pricings is the collection from your original post
        $pricingsForRoomId = $room_collection->filter(function ($pricing) use ($room_ids) {
            return $pricing->accommodationRoom->id == $room_ids;
        });

        $pricingSum = $pricingsForRoomId->sum(function ($pricing) {
            return $pricing->sales_price; // or whatever it is called in your model
        });

        return $pricingSum;

as you see i have some id of rooms like 3-4 ids that i want to for each room to get the sum price for each day .

Activity icon

Replied to How To Detect Some Items Of An Object With Same Value In Relation In Laravel

Thanks @christophharms but what if i want to send like 3 room ids should i place that snippet in a for loop ??

Activity icon

Started a new Conversation I Have An Array Of Collections With Some Same Occurrences Like Below : ``` Array:6 [▼ 0 => Collection {#926 ▶} 1 => Collection {#926 ▶} 2 => Collection {#1045 ▶} 3 => Collection {#1045 ▶} 4 => Collection {#1156 ▶} 5 => Collection {#1156 ▶} ] `

i have an array of collections with some same occurrences like below :

array:6 [▼
  0 => Collection {#926 ▶}
  1 => Collection {#926 ▶}
  2 => Collection {#1045 ▶}
  3 => Collection {#1045 ▶}
  4 => Collection {#1156 ▶}
  5 => Collection {#1156 ▶}
]

now what i want to do is to is to get the sum of those who repeated like 926 so i would have 2 prices to sum because 926 occurred 2 times . how can i achieve that thanks !

Activity icon

Started a new Conversation How To Detect Some Items Of An Object With Same Value In Relation In Laravel

I have a collection of objects like below :

Collection {#1314 ▼
  #items: array:4 [▼
    0 => RoomPricing {#923 ▶}
    1 => RoomPricing {#1042 ▶}
    2 => RoomPricing {#1198 ▶}
    3 => RoomPricing {#1309 ▶}
  ]
}

now each item has a room model as relation in it like below :

 #relations: array:1 [▼
        "room" => Room {#969 ▶}
      ]

now what i want to do is to get the models with the same value in relation for example if item number 0 and 3 has the value of room with id of 120 as relation , i want to get the items and sum the number of price in them . how can i achieve that in laravel ??

Nov
16
1 month ago
Activity icon

Replied to Change Api Output From Object To Array

idk if i get you right or not but i am using dingo api package and that throws error in browser just like above as i copied for you

Activity icon

Replied to Change Api Output From Object To Array

i get this error when i use collection for it :

message: "Call to a member function first() on array",
status_code: 500
Activity icon

Replied to Change Api Output From Object To Array

when i use collect i get this error

message: "Call to undefined method App\Http\Resources\RoomDetailResource::collect()",

and when i use

return RoomDetailResource::collecttion($result);

i get this error :

message: "Call to a member function first() on array",
status_code: 500
Activity icon

Started a new Conversation Change Api Output From Object To Array

i have an api that returns an object as wrapper data in result like below :

{
data: {
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
}

but i want it to be an array like below :

{
data: [
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
]
}

or maybe even like below :

{
data: [ 
{
totalSalesPrice: 0,
totalDiscount: 0,
finalPrice: 0
}
]
}

how can i achive that ?? and here is my method :

 public function getPriceDetails($bookingId)
    {
        $booking = AccommodationBooking::where('id', $bookingId)->with('accommodationRoom')->first();
        $roomsOfBook = DB::table('accommodation_booking_accommodation_room')->where('accommodation_booking_id', $bookingId)->get();

        $result = [];
        foreach ($roomsOfBook as $room) {
            $roomPricingHistory = RoomPricingHistory::where('accommodation_room_id', $room->accommodation_room_id)
                ->whereDate('from_date', '<=', $booking->from_date)
                ->whereDate('to_date', '>=', $booking->to_date)
                ->orderBy('created_at', 'desc')
                ->first();
            $result[] = $roomPricingHistory;
        }

        $totalSalesPrice = collect($result)->sum('sales_price');
        $totalDiscount = 0;
        $finalPrice = $totalSalesPrice;

        $result['totalSalesPrice'] = $totalSalesPrice;
        $result['totalDiscount'] = $totalDiscount;
        $result['finalPrice'] = $finalPrice;
        return new RoomDetailResource($result);
    }
Nov
13
1 month ago
Activity icon

Started a new Conversation How To Filter The Relationship Attributes In Laravel

hi i have a model called room and another model called roomAttribute in room attribute i have price and size fields now i want to filter the rooms by price and when i send price i just want to show the attributes in price range but when i use whereHas or with it boths brings me all attributes when the condition comes true so here is what i tried and i want :

   return $query->with([
            'attributes' => function (Builder $q) use ($start_price,$end_price) {
            $q->where('price', '>=',$start_price);
            $q->where('price', '<=',$end_price);
            }
        ]);

and another try was

     return $query->whereHas('attributes', function (Builder $q) use ($start_price,$end_price) {
            $q->select('price');
            $q->where('price', '>=',$start_price);
           $q->where('price', '<=',$end_price);
        });

so in my db consider i have 3 rows :

"id": 1,
            "name": "test",
            "description": "test",
            "Attributes": [
                {
                    "id": 1,
                    "room_id": 1,
                    "size": 20,
                    "price": 200,
                },
                {
                    "id": 2,
                    "room_id": 1,
                    "size": 20,
                    "price": 200,
                },
                {
                    "id": 3,
                    "room_id": 1,
                    "size": 55,
                    "price": 25000,
                  
                }
            ]

so when i send price to this api with start_price of 100 and end price of 200 i just want to show the first 2 items of attributes and not the third one how can i achieve that ??

Nov
08
1 month ago
Activity icon

Replied to How To Access The Property Inside A Collection Inside An Array In Laravel

@nakov no its not i saw that it has data i just pasted this part for shortness of question

Activity icon

Started a new Conversation How To Change The Format Of A Array To Collection As Each Item In Laravel

i have an array of collections like below :

array:9 [▼
  0 => Collection {#990 ▶}
  1 => Collection {#1109 ▶}
  2 => Collection {#1221 ▶}
  3 => Collection {#1331 ▶}
  4 => Collection {#1442 ▶}
  5 => Collection {#1554 ▶}
  6 => Collection {#1664 ▶}
  7 => Collection {#1775 ▶}
  8 => Collection {#1887 ▶}
]

i want to make this a single collection and make each collection as 1 item of that collection now what i tried is collect($f) but i get the result as below :

Collection {#1443 ▼
  #items: array:9 [▼
    0 => Collection {#990 ▶}
    1 => Collection {#1109 ▶}
    2 => Collection {#1221 ▶}
    3 => Collection {#1331 ▶}
    4 => Collection {#1442 ▶}
    5 => Collection {#1554 ▶}
    6 => Collection {#1664 ▶}
    7 => Collection {#1775 ▶}
    8 => Collection {#1887 ▶}
  ]
}

now i want to know how can i make this 1 collection and make all those 8 collection as items of that collection like below :

Collection {#990 ▼
  #items: array:1 [▼
    0 => RoomPricingHistory {#971 ▶}
    1 => RoomPricingHistory {#971 ▶}
    2 => RoomPricingHistory {#971 ▶}
    3 => RoomPricingHistory {#971 ▶}
    4 => RoomPricingHistory {#971 ▶}

  ]
}

thanks

Activity icon

Started a new Conversation How To Access The Property Inside A Collection Inside An Array In Laravel

i have a collection which has an array in it as item and i want to know how can i access it in my code here is the dd of the collection :

Collection {#990
  #items: array:1 [
    0 => RoomPricingHistory {#971
      #fillable: array:19 [
        0 => "accommodation_room_id"
        1 => "net_price"
        2 => "sales_price"
        3 => "extra_bed_price"
        4 => "half_charge_price"
        5 => "half_board_price"
        6 => "full_board_price"
        7 => "foreign_net_price"
        8 => "foreign_sales_price"
        9 => "foreign_extra_bed_price"
        10 => "foreign_half_charge_price"
        11 => "foreign_half_board_price"
        12 => "foreign_full_board_price"
        13 => "operator_id"
        14 => "commission_percent"
        15 => "discount_percent"
        16 => "from_date"
        17 => "to_date"
        18 => "is_deleted"
      ]
      #connection: "mysql"
      #table: "room_pricing_histories"
      #primaryKey: "id"

and here is my try for code :

 $sum_price[] = $room_price[$i]->sales_price;

its inside a for loop but i get this error :

    "message": "Property [sales_price] does not exist on this collection instance.",

Nov
07
1 month ago
Activity icon

Replied to How To Store Data In A Variable Using Elequent In A For Loop Laravel

You right i know its wrong but here is a deadend i have no other way just to use the query inside this loops

Activity icon

Started a new Conversation How To Store Data In A Variable Using Elequent In A For Loop Laravel

i have a for loop that i am using a query in it , but when i try to get the data it only shows me the last time that query have been running like below :

 for ($i = 0; $i < count($dates); $i++) {

            for ($f = 0; $f < count($room_ids); $f++) {

                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price = RoomPrice::with('Room')
                    ->where('room_id', $room_ids[$f])
                    ->whereDate('from_date', '<=', $dates[$i])
                    ->whereDate('to_date', '>=', $dates[$i])
                    ->get()->sortBy('created_at');
}
}

how can i store $room_price so i can have all the data that every time query runned will be stored in a collection or something . thanks

Activity icon

Started a new Conversation Is It Wise To Call Your Own Application Api In Your Controller In Loop ??

i have an application that in a controller i am trying to send some room id and some date for each day i want to loop and for each room now the problem is when i run this query below :

  $from_date = $request->get('from_date');
        $to_date = $request->get('to_date');
        $room_ids[] = $request->get('room_ids');

        $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();

        for ($i = 0; $i < count($dates); $i++) {

            for ($f = 0; $f < count($room_ids); $f++) {

                /****************************************
                 * Looping for the Number of Rooms User Given
                 *****************************************/
                $room_price = RoomPricingHistory::with('accommodationRoom', 'accommodationRoom.roomCapacityHistoryLast')
                    ->where('accommodation_room_id', $room_ids[$i])
                    ->whereDate('from_date', '<=', $dates[$f])
                    ->whereDate('to_date', '>=', $dates[$f])
                    ->get()->sortBy('created_at');
                var_dump('time');

                $data_array[] = $room_price[$i];
                $data_collection = collect($data_array);

                $sum_price[] = $room_price[$i]->sales_price;
                $sum_half_board[] = $room_price[$i]->half_charge_price;
                $sum_full_board[] = $room_price[$i]->full_board_price;
            }
        }
        foreach ($room_price as $item) {
            if ($item->accommodationRoom->roomCapacityHistoryLast->capacity > 10 ?? null) {
                $check_capacity = 0;
            } else {
                $check_capacity = 1;
            }
        }
        $night_count = count($dates);
        $sum = array_sum($sum_price);
        $sum_half = array_sum($sum_half_board);
        $sum_full = array_sum($sum_full_board);

        $alldata = $sum . ',' . $sum_half . ',' . $sum_full . ',' . $night_count . ',' . $check_capacity;
        return RoomDetailResource::collection($data_collection)->sum($alldata);

i get this error :

  "message": "Undefined offset: 1",
    "status_code": 500,

i think its because 1 loop runs more than once now my question is call i make 1 for and make an api from it and then in another function call that api whithin a loop and get the result ?? is it wise to do such or we sould not call our own api in our own project ?? or if there is any way to solve this error above ??

Activity icon

Replied to Using Laravel With Vuejs , Api Based Or Traditional Way

thanks thats a good idea i see most of them like bagisto they did it modular base i mean each part is a component that works seperatly and files are seperated is that the right thing to do in laravel ?? are there any good packages or ways for this ?? and they mostly did in traditional way

Nov
06
1 month ago
Activity icon

Replied to Using Laravel With Vuejs , Api Based Or Traditional Way

yes thats good point but i can do as traditional way and yet make api to send data to third party client . what confused me is that i dont know which approach would be more efficient and better approach for some kind a big projects

Activity icon

Started a new Conversation Using Laravel With Vuejs , Api Based Or Traditional Way

i want to write a shop , i am using laravel and for my front end i will surely pick vuejs now my question is should i fully use laravel api and call them in another vuejs project or is it better to use traditional way to send variable and data to a vuejs component which is implemented in laravel , i wanna know the cons and pros and if there is any possible way to use the vue js implemented in laravel to call apis and use api in there or any best practice or any good tutorial about using vuejs with laravel through api . thanks

Nov
04
1 month ago
Activity icon

Started a new Conversation Send Multiple Data And Show Them In Resource Api Laravel

i have 2 variables that i want to send them to resource and show them in api like below :

        return new RoomDetailResource($data_array,$sum);

and the resource i have written is like below :

class RoomDetailResource extends JsonResource
{
    /**
     * @var
     */
    public $sum;

    /**
     * Create a new resource instance.
     *
     * @param  mixed  $resource
     * @return void
     */
    public function __construct($resource, $sum)
    {
        // Ensure you call the parent constructor
        parent::__construct($resource);
        $this->resource = $resource;

        $this->sum = $sum;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'sum' => $this->sum
        ];
    }
}

now what i get is the error :

   "message": "Trying to get property 'id' of non-object",
    "status_code": 500,

but if i want to show sum its shows without any problem now here is how i want my api :

{
id:1,
sum:200
},
{
id:2,
sum:200
}

note that sum is the same for all and i just want to repeat it in objects or show them in the end of api as a property . thanks

Activity icon

Started a new Conversation How To Get Sum Of The Numbers In For Loop Laravel

i am having a loop that each step i get the price of the day now i want to get the sum of all days and show them to user here is my attempt below :

 for ($f = 0; $f < count($room_ids); $f++) {
                $data = Price::
                     whereIn('id',$room_ids)
                    ->whereDate('from_date', '<', $from_date)
                    ->whereDate('to_date', '>   ', $to_date)
                    ->orderBy('created_at', 'asc')
                    ->take(1)
                    ->get();
//                $sum_price += array_sum($data[$f]->sales_price)
//or this one 
//               $sum_price += $data[$f];
                $data_array[] = $data[$f]->sales_price.'======'.$dates[$i].'==============' ;
            }

but each time i get the price for 1 day and dont get the sum of all days . how can i achive that ?? thanks

Nov
02
1 month ago
Activity icon

Started a new Conversation How To Query Database For Each Day In An Array Of Days Laravel

i have an array of days that i want to query my model for each date that i have in that array , that could be possible with a for loop and index but as thumbs rules i dont want to query inside a loop so is there any other possibility to check the date in my model so my tried with for loop is like below :

     $period = CarbonPeriod::create($from_date, $to_date);
        $dates = $period->toArray();
// and here l am looping the days :
for ($t = 0; $t < count($dates); $t++) {
                   $room_capacity = Capacity::with('Hotel')
                    ->where('room_id', $room_ids[$i])
                    ->whereDate('from_date', '<=', $dates[$t])
                    ->whereDate('to_date', '>=', $dates[$t])
                    ->get()->sortBy('created_at');
}

i want to know if there is any way to potimize the above code not to write it inside a loop . thanks

Activity icon

Started a new Conversation How To Use ->unique() On A Paginated Object To Remove All Duplicates In Laravel

i have a paginated collection in my laravel like below:

$data = QueryBuilder::for(Accommodation::class)
    ->allowedFilters([
        AllowedFilter::scope('bed_count'),
        AllowedFilter::scope('filter_price'),
        AllowedFilter::scope('filter_date'),
        AllowedFilter::scope('discounts'),
        AllowedFilter::scope('name'),
        AllowedFilter::exact('grade_stars'),
        AllowedFilter::exact('city_id'),
        AllowedFilter::exact('is_recommended'),
        AllowedFilter::exact('accommodation_type_id'),
        AllowedFilter::scope('accommodation_facility')
//                'name',
    ])
    ->allowedAppends(['cheapestroom'])
    ->allowedIncludes(['gallery','city','accommodationRooms','accommodationRooms.roomPricingHistorySearch','discounts','prices'])
    ->allowedSorts([
        AllowedSort::custom('discount', new DiscountSort() ,'amount'),
        AllowedSort::custom('price', new PriceSort() ,'price'),
    ])
    ->paginate(10);

now if i use ->unique on my $data it will only return me the 10 first result on dont show the other results i dont want to remove paginate from my collection because it would be so heavy object to call like 5k records and i dont want to use join as long as it cause other problems for me , so my question is that : is it possible to unique a paginated object in laravel or in resource maybe ??

Nov
01
1 month ago
Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

@aurawindsurfing thanks man i think i have to stop coding for some days and just think about changing the flow or the way of doing this i will update this post when ever i come up with a good solution thanks to all of you guys

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

thanks for your good example but if i want to do this if you take a look at the example i gave you it would be some endless conditions and i cant sort the parent by the child relation i looked a lot in documentation that is not possible at least untill laravel 6 idk about that

Oct
31
1 month ago
Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

@jlrdw yes you are right but first i have to make it work then i should go for refactor i think . for you and other guys to understand better consider the link below from booking.com i paste below and i want to write all the filters it has in left sidebar :

https://www.booking.com/searchresults.en-us.html?label=gen173nr-1FCAEoggI46AdIM1gEaDuIAQGYATG4ARfIAQzYAQHoAQH4AQKIAgGoAgO4Aomd7O0FwAIB&sid=5ffe0f643656aea38463e107aa753c96&sb=1&src=index&src_elem=sb&error_url=https%3A%2F%2Fwww.booking.com%2Findex.html%3Flabel%3Dgen173nr-1FCAEoggI46AdIM1gEaDuIAQGYATG4ARfIAQzYAQHoAQH4AQKIAgGoAgO4Aomd7O0FwAIB%3Bsid%3D5ffe0f643656aea38463e107aa753c96%3Bsb_price_type%3Dtotal%26%3B&ss=New+York%2C+New+York+State%2C+USA&is_ski_area=&checkin_year=2019&checkin_month=11&checkin_monthday=8&checkout_year=2019&checkout_month=11&checkout_monthday=17&group_adults=2&group_children=0&no_rooms=1&b_h4u_keep_filters=&from_sf=1&ss_raw=ne&ac_position=0&ac_langcode=en&ac_click_type=b&dest_id=20088325&dest_type=city&iata=NYC&place_id_lat=40.768074&place_id_lon=-73.981895&search_pageview_id=3c4675448c6f0113&search_selected=true&search_pageview_id=3c4675448c6f0113&ac_suggestion_list_length=5&ac_suggestion_theme_list_length=0

that makes it a bit large query and really hard i think to implement . because of that i used spatie laravel query builder which is specified for filters i think and it was the best one around

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

yes @jlrdw i have no other option this query filters all the data that user wants to see and involves to many tables in my database

Oct
30
1 month ago
Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

my problem is not sorting i am sorting them my problem is groupby and the duplicate results that i get

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

yet the same result i have duplicate data in it .

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

yes sir here you go

select `dr`.`sales_price`, `accommodations`.* from `accommodations` inner join `accommodation_rooms` as `ar` on `ar`.`id` = `accommodations`.`id` inner join `room_pricing_histories` on `room_pricing_histories`.`id` = `ar`.`id` inner join `accommodation_rooms` as `br` on `br`.`id` = `accommodations`.`id` inner join `room_capacity_histories` on `room_capacity_histories`.`id` = `br`.`id` inner join `accommodation_rooms` as `cr` on `accommodations`.`id` = `cr`.`accommodation_id` inner join `room_pricing_histories` as `dr` on `cr`.`id` = `dr`.`accommodation_room_id` where `room_pricing_histories`.`sales_price` > ? and `room_pricing_histories`.`sales_price` < ? and date(`room_capacity_histories`.`from_date`) > ? and date(`room_capacity_histories`.`to_date`) < ? group by `dr`.`sales_price`, `accommodations`.`id` order by `dr`.`sales_price` desc
Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

i double checked that and fixed the orders but yet not working maybe because its combining with others join in spatie laravel query builder huh ?

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

@sinnbeck hi dea sinnbeck :) no it wont give any error it just order them and dont group by the result so i would have duplicate results

Activity icon

Replied to Group-by Not Working With Order By Laravel Elequent

@jlrdw yes but no matter the order where ever i use it wont work

Activity icon

Started a new Conversation Group-by Not Working With Order By Laravel Elequent

i have a join query in laravel that i want to group by and orderby together but always just one of them working and groupby is not working with orderby any advice ?? my code is like below :

 $data = $query->join('accommodation_rooms as cr', 'accommodations.id', '=', 'cr.accommodation_id')

            ->join('room_pricing_histories as dr','cr.id', '=', 'dr.accommodation_room_id')
//          ->select('cr.id')
           ->groupBy('dr.sales_price','accommodations.id')
           ->orderBy('dr.sales_price', 'desc')
           ->select('dr.sales_price', 'accommodations.*');


        return $data;
Activity icon

Replied to How To Remove Duplicates From 2 Joins In Laravel

i used distinct every where but yet no luck with it sir

Activity icon

Started a new Conversation How To Remove Duplicates From 2 Joins In Laravel

hi , i am using spatie laravel query builder to make some filters for my project and i have the code as below :

public function scopeFilter()
    {
        $data = QueryBuilder::for(Accommodation::class)
            ->allowedFilters([
                AllowedFilter::scope('bed_count'),
                AllowedFilter::scope('filter_price'),
                AllowedFilter::scope('filter_date'),
                AllowedFilter::scope('discounts'),
                AllowedFilter::scope('name'),
                AllowedFilter::exact('grade_stars'),
                AllowedFilter::exact('city_id'),
                AllowedFilter::exact('is_recommended'),
                AllowedFilter::exact('accommodation_type_id'),
                AllowedFilter::scope('accommodation_facility')
//                'name',
            ])
            ->allowedAppends(['cheapestroom'])
            ->allowedIncludes(['gallery','city','accommodationRooms','accommodationRooms.roomPricingHistorySearch','discounts','prices'])
            ->allowedSorts([
                AllowedSort::custom('discount', new DiscountSort() ,'amount'),
                AllowedSort::custom('price', new PriceSort() ,'price'),
            ])
            ->paginate(12);
        return FilterResource::collection($data);

now i have 1 sort and 2 filters which is so important for me here is the code for them

sort

  $data = $query->join('accommodation_rooms as cr', 'accommodations.id', '=', 'cr.accommodation_id')
            ->join('room_pricing_histories as dr','cr.id', '=', 'room_pricing_histories.accommodation_room_id')
//            ->select('cr.id')
            ->orderBy('dr.sales_price', 'desc')
            ->select('dr.sales_price', 'accommodations.*')
            ->groupBy('dr.sales_price','accommodations.id');
        $direction = $descending ? 'DESC' : 'ASC';

        return $data;

first filter which is wrriten as scope

 public function scopeFilterPrice(Builder $query, $start_price, $end_price): Builder
    {
        $data = $query->leftjoin('accommodation_rooms as ar','ar.id','=','accommodations.id')
            ->leftjoin('room_pricing_histories','room_pricing_histories.id','=','ar.id')
            ->select('accommodations.*')
            ->where('room_pricing_histories.sales_price', '>', $start_price)
            ->where('room_pricing_histories.sales_price', '<', $end_price);
        return $data;
    }

#secound filter as scope too

public function scopeFilterDate(Builder $query,$from_date,$to_date): Builder{

        $data = $query->leftjoin('accommodation_rooms as br','br.id','=','accommodations.id')
            ->Join('room_capacity_histories','room_capacity_histories.id','=','br.id')
            ->select('accommodations.*')
            ->whereDate('room_capacity_histories.from_date', '>', $from_date)
            ->whereDate('room_capacity_histories.to_date', '<', $to_date);

        return $data;

but this will bring me duplicate data no matter what groupby or other thing i use i want to know if there is any possibilty for me to remove duplicates on resource or some where else.

NOTE

i did use ->unique() but it wont have the structure of pagination any more which cause me a problem so i want the structure of pagination first . here is the raw query :

"select `dr`.`sales_price`, `accommodations`.* from `accommodations` left join `accommodation_rooms` as `ar` on `ar`.`id` = `accommodations`.`id` left join `room_pricing_histories` on `room_pricing_histories`.`id` = `ar`.`id` left join `accommodation_rooms` as `br` on `br`.`id` = `accommodations`.`id` inner join `room_capacity_histories` on `room_capacity_histories`.`id` = `br`.`id` inner join `accommodation_rooms` as `cr` on `accommodations`.`id` = `cr`.`accommodation_id` inner join `room_pricing_histories` as `dr` on `cr`.`id` = `room_pricing_histories`.`accommodation_room_id` where `room_pricing_histories`.`sales_price` > ? and `room_pricing_histories`.`sales_price` < ? and date(`room_capacity_histories`.`from_date`) > ? and date(`room_capacity_histories`.`to_date`) < ? group by `dr`.`sales_price`, `accommodations`.`id` order by `dr`.`sales_price` desc"

thanks