farshadf

farshadf

Member Since 10 Months Ago

Experience Points
5,890
Total
Experience

4,110 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
6
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 2
5,890 XP
Feb
19
20 hours ago
Activity icon

Replied to When To Use No Sql Databases In Laravel Projects

not rough but complete idea of that :) so i will just put some models on scout and elastic that i want to full search them and i will leave comments on sql for now and look for better solutions . thanks that was so complete answer and great <3

Activity icon

Started a new Conversation When To Use No Sql Databases In Laravel Projects

i have a laravel application that i want to optimize . now i was thinking to move some parts to no sql for reading heavy data now my question is which part does usually people use for no sql i mean can i move my comments to nosql or its just for full text search or some thing like that . thanks

Feb
13
6 days ago
Activity icon

Started a new Conversation Compact(): Undefined Variable

hi i have a laravel applcation that works properly on local but not working on server and here is the part and the error it throws :

compact(): Undefined variable: 00558852 // the number is what user have inserted 

and here is the code :

 public function sendSms(Request $request)
    {
        $cellphone = $request->mobile;

        //        sending sms
        $token = rand('11111', '99999');
        $client = new Client(); //GuzzleHttp\Client
        $key = '4C77664C384B376F6A59376A3737496F31533954556D717353574A416249314A376B4E4C4B7A4A466C70343D';
        $result = $client->post('https://api.kavenegar.com/v1/' . $key . '/verify/lookup.json
', [
            'form_params' => [
                'receptor' => $request->mobile,
                'token' => $token,
                'template' => 'Register',
            ]
        ]);
        $temp = Temp::where('cellphone', $request->mobile);
        if ($temp) {
            $temp->delete();
        }
        $created = Temp::create([
            'cellphone' => $request->mobile,
            'code' => $token,
        ]);
        return view('shop::customers.signup.verify-sms', compact('cellphone', $cellphone));

first i thought it would be because of php version i downgraded to 7.2 but it yet throws the same error .

Feb
12
1 week ago
Activity icon

Started a new Conversation Lunch 2 Laravel Projects On Nginx

i have an enginx and i want to run 2 laravels in it as http://94.182.191.81/project1 and http://94.182.191.81/project2 how can i achive this because for 1 project every thing is working fine my config is like below :

###
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;
 access_log /var/log/nginx/laravel-access.log;
         error_log /var/log/nginx/laravel-error.log;
        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /home/wishato/public;

        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                                 try_files $uri $uri/ /index.php?$query_string;
        }
        location /wishato {
        root /home/wishato-master/public;
                    try_files $uri $uri/ /index.php?$query_string;

        }


# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php7.0-cgi alone:
        #       fastcgi_pass 127.0.0.1:9000;
        #       # With php7.0-fpm:
  try_files $uri =404;
                 fastcgi_split_path_info ^(.+\.php)(/.+)$;
               #  fastcgi_pass unix:/run/php/php7.2-fpm.sock;
                 fastcgi_index index.php;
                 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                 include fastcgi_params;
                fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        location ~ /\.ht {
                deny all;
        }
}
# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
                                                                                                                                                                                                 84,1          Bot



Activity icon

Replied to Can Other Pages Function Effect Performance Of Home Page

Yes i am using it but i dont know if other codes effect home page or not

Activity icon

Started a new Conversation Can Other Pages Function Effect Performance Of Home Page

i have a laravel application that i want to optimize . now my question is for every page and function should i just look at that page code and for example another route with another code which is not called can effect performance of the application ??? thanks

Feb
05
2 weeks ago
Activity icon

Replied to How To Reset Cache After Each Update In Laravel Cache

@ahmeddabak thanks for your answer can you please tell me what this block of code does ?? will it monitor the key and when fulfilled_wish changes for example if user changes it it will remove the old cache and cache it again ?? thanks for your time

Activity icon

Started a new Conversation How To Reset Cache After Each Update In Laravel Cache

i have a model that i used cache on it like below :

   public function fulfilledWish()
    {
        return Cache::remember('fulfilled_wish', 5, function () {
            return Model::with(['media', 'slug'])
                ->where('type_id', 2)
                ->take(4)
                ->get();
        });

now i want the cache to be updated after each update or create happens on model like scout in laravel . so is there any solution for that ???

Activity icon

Started a new Conversation Simple Create Test With Logged In User In Laravel 5

i want to write a test for my comment model but for making that the user must be logged in i want to know how people write create tests in laravel because when i make it with the below method :

   $file = UploadedFile::fake()->create('image.jpg');

        $data = [
            'title' => $this->faker->word,
            'link' => $this->faker->url,
            'image' => $file,
        ];
      
        $employee = factory(User::class)->create();
      
        $this
            ->actingAs($employee, 'admin')
            ->post(route('admin.carousel.store'), $data)
            ->assertStatus(302)
            ->assertRedirect(route('admin.carousel.index'))
            ->assertSessionHas('message', 'Create carousel successful!');

and when i make it with the below command i cant understand really if its created or not :

  $this->actingAs($user);
        $this->createMock(Comment::class);

so i really want to know how to check the creation of the model in laravel .

Jan
31
2 weeks ago
Activity icon

Replied to Stop Laravel Config Cache

Thanks I got that that helped

Activity icon

Started a new Conversation Stop Laravel Config Cache

i am working on a laravel application and it has caches routes config and other things so every thing that i change i have to run config:cache or route:cache to clear the cache . is there any way to tell laravel to clear cache and stop caching ???

Jan
27
3 weeks ago
Activity icon

Started a new Conversation Group The Number Of Models By The Time They Created

i want to make graph from my models and i want to see for example how many posts where created in each month in my application for example it would be the number of models created and the mounth in api like below :

{
count:22,
month:1-1-2020
},
{
count:18,
month:1-2-2020
}

is there any way to do this ??

Jan
23
3 weeks ago
Activity icon

Replied to Simple Test In Laravel In Create Method

This is the result of dump but i have the factory for it i am sure

) Tests\Feature\ModelTest::it_test_insert_model InvalidArgumentException: Unable to locate factory with name [default] [Tests\Feature\Model].

Activity icon

Replied to Simple Test In Laravel In Create Method

yes it is do you mean is that the problem with making the model ???

Activity icon

Replied to Simple Test In Laravel In Create Method

now it gives me this error

Failed asserting that 0 matches expected 1.

if i change it to 0 it works well

Activity icon

Started a new Conversation Simple Test In Laravel In Create Method

i want to simply test my model to see if it can be created or not here is what i tried :

    public function it_test_insert_model(){
//        $this->actingAs(User::class);
        $wish = factory(Model::class)->create();
        $this->post('/model/create',$wish->toArray());
        $this->assertEquals(1,Model::all()->count());
    }

now my problem is every time it fails because it should equal the the numbers of models i have in my table . is there any way to just create one and test if it was created and then remove it ??? because now every time it remains in database . i just want to test if the model is able to be created or not . thanks

Jan
21
4 weeks ago
Activity icon

Started a new Conversation Add Slick Slider In Vue Component For Laravel

i am trying to add slick slider to my laravel project in vue component like below this is my slider.vue component:


<template>
    <div class="home-slider">
        <slick ref="slick" :options="slickOptions">
            <a href="http://placehold.it/320x120">
                <img src="http://placehold.it/320x120" alt="">
            </a>
            ...
            <a href="http://placehold.it/420x220">
                <img src="http://placehold.it/420x220" alt="">
            </a>
        </slick>
        <i @click="slideLeft()" class="icon icon-chevron-down"></i>
    </div>
</template>

<script>
    import Slick from 'vue-slick'
    new Vue({
        components: { Slick },
        data() {
            return {
                slickOptions: {
                    //options can be used from the plugin documentation
                    slidesToShow: 4,
                    infinite: true,
                    accessibility: true,
                    adaptiveHeight: false,
                    arrows: true,
                    dots: true,
                    draggable: true,
                    edgeFriction: 0.30,
                    swipe: true
                }
            }
        },
        // All slick methods can be used too, example here
        methods: {
            next() {
                this.$refs.slick.next()
            },
            prev() {
                this.$refs.slick.prev()
            },
            reInit() {
                // Helpful if you have to deal with v-for to update dynamic lists
                this.$refs.slick.reSlick()
            }
        }
    })
</script>

and in my blade file i have some thing like below :

.
.
.
.
            <home-slider url="/api/home/newpost"></home-slider>
.
.
.
.

but nothing is showing up in my app btw when i run the command as below :

npm install --no-optional vue-slick

i get the message as below :

├── [email protected]  extraneous
├── [email protected] 
└── [email protected]  extraneous

does it mean that the packages have been installed or not ?? and i would be so happy if you guys can help me import this slick vue in my laravel project . thanks

Jan
20
4 weeks ago
Activity icon

Started a new Conversation Check To Remove Expired Posts Laravel

i have a post model that will be boosted by user for some certain time and now i have a crone job to be lunched every 15 mins to run a special script to see if post is boosted or finished . but the problem is that every time it loops all the posts and it takes some certain amount of time i wanted to know if there is any alternative and better ways to do this ?? here is my code below :

$boosted = POST::whereIn('status_id', [4, 5, 6])->where('boosted',1)->get();
        foreach ($boosted as $index => $item) {
            if ($item->boosted_until < Carbon::now()) {
                $wish = Wish::find($item->id);
                $wish->boosted = 0;
                $wish->save();
            }
Jan
18
1 month ago
Activity icon

Started a new Conversation Merge 2 Collection Into Another With One Same Value In Both Laravel

hi i have 2 objects in laravel like below :

{
user_id: 34993,
price: "20000.00"
},
{
user_id: 35153,
price: "20000.00"
},
{
user_id: 35168,
price: "20000.00"
},

and the secound one is the user object :

[
{
id: 34993,
uuid: "8f8f2ba3-0d51-4fdb-83cd-6e13a0f2cc13",
fullname: "َUsersName",
email: null,
created_at: "2020-01-15 14:42:45",
updated_at: "2020-01-15 14:43:58",
email_verified_at: null,
gender: 2,
title: null
},
{
id: 35153,
uuid: "8f8f2ba3-0d51-4fdb-83cd-6e13a0f2cc13",
fullname: "َUsersName",
email: null,
created_at: "2020-01-15 14:42:45",
updated_at: "2020-01-15 14:43:58",
email_verified_at: null,
gender: 2,
title: null
},
{
id: 35168,
uuid: "8f8f2ba3-0d51-4fdb-83cd-6e13a0f2cc13",
fullname: "َUsersName",
email: null,
created_at: "2020-01-15 14:42:45",
updated_at: "2020-01-15 14:43:58",
email_verified_at: null,
gender: 2,
title: null
},

so now how can i add the price into the user object in second object or some how merge them with the key of user_id in first object and id of secound object because they are the same ?? my code is like below :

    {

        $data = DB::table('users_tracker')->where('user_id','>','34676')->where('action','LIKE','%gatewayResponse%')
            ->leftJoin('gateway_transactions',function($join){
                $join->on('gateway_transactions.ip','=','users_tracker.ip');
            })
            ->where('gateway_transactions.status','=','SUCCEED')
            ->select('user_id','price')
            ->distinct()
            ->get();
//        return $data;

       $user_id = $data->pluck('user_id');
        $users = User::whereIn('id',$user_id)->get();
        return $users;
    }
Jan
16
1 month ago
Activity icon

Started a new Conversation How To Find Out How Much Hardware You Need Per User

hi i have an application in laravel that i want to know is there any way to understand how much resource in server we need peruser for nomal visit of site home page‌??? thanks

Activity icon

Replied to How Much Is The Ram Usage Shown In Debugbar

@bugsysha thanks can you tell me how to do that with php storm or any link or guide or something ??

Activity icon

Started a new Conversation How Much Is The Ram Usage Shown In Debugbar

i have a laravel application that i use debug bar on it and i have 3 question about that : 1- when it shows 20mb of ram on homepage does it mean that if 2 user visit my site it would need 40mb of ram??? 2-why its usage is different on server and on local for ex home page is 8mb on local and 18 mb on server is that normal ?? 3- is 20mb alot for home page of laravel application ?? thanks in advance

Activity icon

Started a new Conversation Laravel 500 Error Sorry, Too Many Clients Already

hi i am using laravel with pgsql and suddenly i get the below error and 500 from users :

[2020-01-15 16:45:08] producton.ERROR: SQLSTATE[08006] [7] FATAL:  sorry, too many clients already (SQL: select * from "sessions" where "id" = so6Mt2EAqYB1DmzLDZ3OrFyI2tYS0MPSl7pdARpJ limit 1) {"exception":"[object] (Illuminate\Database\QueryException(code: 7): SQLSTATE[08006] [7] FATAL:  sorry, too many clients already (SQL: select * from \"sessions\" where \"id\" = so6Mt2EAqYB1DmzLDZ3OrFyI2tYS0MPSl7pdARpJ limit 1) at /home//vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\DBAL\Driver\PDOException(code: 7): SQLSTATE[08006] [7] FATAL:  sorry, too many clients already at /home//vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:31, PDOException(code: 7): SQLSTATE[08006] [7] FATAL:  sorry, too many clients already at /home//vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:27)

now when i check my pgsql connection number it is 100 and it didnt even get to half i mean the max connection was 40 and now we get this error . any idea what can be done ???

Dec
31
1 month ago
Activity icon

Started a new Conversation Verify User By Sms Table Structure

hi , i want my user to be verified by sms after registration and if they dont verify thier phone number user wont be active , now what i have in mind is to make a table as temp table with 2 fields code and user_id and every time just insert the code in this temp table make a relation to users or just add a field to the users table like activation code and verify user from there i dont know which one is the right way and the optimized way to do this.

Dec
16
2 months 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
2 months ago
Activity icon

Replied to How To Write A Package For Laravel

Thanks man .

Dec
04
2 months 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 months 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
3 months 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
3 months 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
3 months 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.",