DavidPetrov

DavidPetrov

Member Since 6 Months Ago

Experience Points
8,570
Total
Experience

1,430 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
12
Lessons
Completed
Best Reply Awards
11
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
8,570 XP
Sep
19
1 month ago
Activity icon

Replied to Array Column In Mysql Database

Best one you can do is JSON conversion of the arrays, but it depends on what they're gonna be containing. You may consider restructuring your datatables according to your needs, but if you don't get more precise we couldn't assist further!

Sep
18
1 month ago
Activity icon

Replied to Deploy Migrations For Test Env Only

You may want to refer to laravel factories for that matter. Look up the documentation! :)

Sep
17
1 month ago
Activity icon

Started a new Conversation Image From Link Doesn't Load On Mobile With Marzipano 360 Viewer

I didn't know where to properly categorize this topic, but I'm experiencing a very strange behaviour which I don't know whether it has to do with marzipano or laravel routing itself. Situation is as follows: I'm using marzipano to display an equirectangular 360 image in a proper 360 view. Since files are not public, but rather located in storage/app/files/order/{orderID}/, I can't access them directly via a link, so I've built a link on my website for authorised users only to see the images.

In web.php:

Route::get('/viewFile', '[email protected]');

And then in HomeController.php:

public function viewFile(Request $req)
{

    $name = basename($req->rel_path);
    header("Content-Disposition: filename=$name");

    if($req->is360)
        return view('display_360_image', ['path' => $req->rel_path]);

    return response()->file(Storage::disk('files')->url(urldecode($req->rel_path)));
}

Respectively, 360 images are marked and the user can choose whether to see the original image or the 360 version, which is the query parameter $req->is360. $req->rel_path is respectively the relative path of the file to the files disk.

Now, when a user wants to see the 360 variant of an image, I return the following view to him. display_360_image.blade.php

<!DOCTYPE html>
<html lang = "en">
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta charset="utf-8">
        <script type="text/javascript" src="{{asset('js/jquery-3.3.1.min.js')}}" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script type="text/javascript" src="{{asset('js/jquery-migrate-3.0.0.min.js')}}"></script>

        <style rel="{{asset("css/marzipano/header_style.css")}}"></style>
        <title>Company CRM 360 Displayer</title>

    </head>

    <body>
        <div id="pano"></div>

        <script>
            window.sourceURL = "viewFile?rel_path={{urldecode($path)}}";
        </script>
        <script src="{{asset('js/marzipano/rAF.js')}}"></script>
        <script src="{{asset('js/marzipano/es5-shim-master/es5-shim.min.js')}}"></script>
        
        <script src="{{asset('js/marzipano/marzipano.js')}}"></script>
        <script src="{{asset('js/marzipano/display_page.js')}}"></script>
        <style>
            * {
                -webkit-box-sizing: border-box;
                -moz-box-sizing: border-box;
                box-sizing: border-box;
                -moz-user-select: none;
                -webkit-user-select: none;
                -ms-user-select: none;
                -webkit-user-drag: none;
                -webkit-touch-callout: none;
                -ms-content-zooming: none;
            }

            html, body {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
                overflow: hidden;
            }

            #pano {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
            }
        </style>
    </body>
</html>

The .js file containing the displaying logic is the following display_page.js:

$(function () {
    var viewer = new Marzipano.Viewer(document.getElementById('pano'));

    // Create source.
    var source = Marzipano.ImageUrlSource.fromString(window.sourceURL); //tha's the variable I'm setting in the blade view

    // Create geometry.
    var geometry = new Marzipano.EquirectGeometry([{ width: 4000 }]);

    // Create view.
    var limiter = Marzipano.RectilinearView.limit.traditional(1024, 100*Math.PI/180);
    var view = new Marzipano.RectilinearView({ yaw: Math.PI }, limiter);

    // Create scene.
    var scene = viewer.createScene({
      source: source,
      geometry: geometry,
      view: view,
      pinFirstLevel: true
    });

    // Display scene.
    scene.switchTo();
});
        

Nothing more than a simplistic basic usage of marzipano.

So basically, marzipano wants to load the picture from a link in order for it to be provided as a source to the plugin and then be displayed. Everything works fine on PC browsers, but on mobile browsers the pictures simply don't appear when requested in a 360 variant. I've managed to come to the conclusion however, that if one does directly access a public picture on the marzipano plugin, then it shows on mobile as well! But I can't make my order files public, so I need then displayed from the storage folder.

Basically, the user is able to see the file under https://domain.com/viewFile?rel_path=order%2F5943%2FSAM_100_0043.jpg and the image renders, but when requested as https://domain.com/viewFile?rel_path=order%2F5943%2FSAM_100_0043.jpg&is360=1 only a blank page is displayed.

However, if the image is located in let's say public/images/order/{orderID}/, then it loads with no problem as well as in 360!

Does anybody have an idea whether the problem lies within marzipano or is it a general laravel concern with mobile browsers and resource security? If any further details are required, I'm here to provide a thorough cooperation! Thanks a lot in advance!

Sep
13
1 month ago
Activity icon

Replied to Pivot Table Data

Could you provide a more thorough description of your relationship structure, I couldn't really get the issue here.

Sep
06
1 month ago
Activity icon

Replied to Page 'Locked' Functionality...

You won't actually need to set a number of minutes, you can work with event handlers. When the edit page is opened, you simply put the page route (or however you'd like to identify your pages) related to the user editing it into a global cache which then you can check for other users via a middleware. Afterwards, when the edit is finished, you simply erase the entry from your cache. That's it, if I've understood correctly. :)

Aug
18
2 months ago
Activity icon

Replied to Storing Data From 1 Table To Another Tables

Are you familiar with the concepts of table models? This is a fairly easy task using these, take a look at the documentation: https://laravel.com/docs/5.8/eloquent#introduction.

Your sample code would look something like:

$lead = Lead::create($request->all());

$opportunity = Opportunity::create(['title' => $lead->title, 'description' => $lead->description]);

$company = Company::create(['name' => $lead->company_name, /*etc...*/]);

You'll get the point, it's easy and enjoyable!

Activity icon

Replied to Scope By Custom Attribute Or Excluding Data By Scope

If I have understood correctly, you want to skip all the models with relationship with a level citizen. If so, you were close enough. What you need is:

scopeNoCitizens($query) {
    $query->whereDoesntHave('relationships', function($query) {
        $query->where('relationship_level', 'Citizen');
    });
}

This literally translates to: Get all the instances that don't have a relationship with a level citizen.

Aug
16
2 months ago
Activity icon

Replied to [email protected] With A Call To $this->anotherAction() Isn't Working?

You'll be suprised if I told you you're missing something obvious in general OOP programming. :D You are calling $this->show($category), but that only yields a view inside your blog() method, which you'll eventually have to return. So simply change $this->show($category); to return $this->show($category); and things shall be fine if it works otherwise. ^^

Aug
09
2 months ago
Activity icon

Replied to How To Get Count Order

The query you've written is definitely wrong. The question is: what are you exactly trying to achieve? Elaborate on that so we can provide proper advice.

Aug
07
2 months ago
Activity icon

Replied to Relation Between Same Users Table

Provided that you have a coach_id field on your users table, this must do the job.

User model:

//when a runner
public function coach()
{
    return $this->belongsTo('App\User', 'coach_id');
}

//when a coach
public function runners()
{
    return $this->hasMany('App\User', 'coach_id');
}
Aug
01
2 months ago
Activity icon

Replied to Optimize For Loop Query

Didn't get what you said. Could be that I've misunderstood your exact needs, but regarding the queries that's your solution for one instead of 30 queries. You can then modify the collection however it suits your needs.

Activity icon

Replied to Optimize For Loop Query

You're creating 60 queries where you can have two. I'll demonstrate how to shorten the query for the first collection:

$dataOneMonth = Claim::whereBetween('created_at', [today(), today()->subMonth()]) //get all records in that timespan
    ->groupBy(DB::raw('DATE(created_at)')) //unify the day they've been created on as a date, so that we can group
    ->orderBy('created_at') //order by creation
    ->get() //retrieve the collection of claims, at this point we're having a collection of 'date' => $claims
    ->map(function($claims){
        return $claims->count(); //for each collection of claims for a given day, return its count
    });

So now $dataOneMonth should be like 'date' => $count. Not tested, improvised, may need a redaction here or there, but you get the point.

Jul
29
2 months ago
Activity icon

Replied to Where To Save List Data

If the data is constant and readonly (modified thus only by developers), then a config file is the right solution. If, however, you'd like to modify the data through your app and interact with it in more ways, a DB table is the way to go.

Jul
26
2 months ago
Activity icon

Replied to How To Show Records Only Which Have At Least One Relationship

$users = App\User::has('groups')->get(); //fetches all users having at least one group.
Jul
18
3 months ago
Activity icon

Replied to Where Are You All From?

Stara Zagora, Bulgaria. About to study abroad in Karlsruhe, Germany!

Jul
17
3 months ago
Activity icon

Replied to Method Illuminate\Mail\Mailer::from Does Not Exist.

I think you're supposed to use the Mail facade instead of the Mail\Mailer class. Double check if Mail is referencing to Illuminate\Support\Facades\Mail, it should be a common alias, but at the place where you're using your code this might be overriden.

Activity icon

Replied to Pivot Table For 3 Models?

That's of course an approach but it's already an infrastructural matter and depens on how similar exactly Gear and Motor are in their role as Product for the application and hence how unifiable they are. If they require extendedly different functuality as separate classes, then that won't suit up that good. Otherwise your suggesstion is definitely worth a thought as an option! But yet again, we can't know how things look within the bigger picture, so it's up to the OP.

Activity icon

Replied to Pivot Table For 3 Models?

Then that's exactly what you need! Your pivot table (preferably named product_supplier) will then look like this:

product_type
product_id
supplier_id
price

Accordingly, the Models. You will find it all there!

Activity icon

Replied to Pivot Table For 3 Models?

Is there an unique combination of motor and gear you need the price of? If so, three sided pivot table is the way to go. But if you need either a motor or a gear to have a price from a given supplier, then you need a polymorphic many to many relationship: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many-polymorphic-relations Everything is described in thorough detail there, if you need further assistance anyway, you can always ask here! Happy coding!

Jul
16
3 months ago
Activity icon

Replied to Is There A Without Relationship?

Yes, if you have for example protected $with = ['author', 'store']; you can avoid loading the author by using the without() method:

Book::without('author')->get(); //loads  the books without retrieving the authors
Jul
15
3 months ago
Activity icon

Replied to Placeholder In String

$placeHolders = ['name', 'date']; //let's presume you know all the keys you're going to be replacing
$name = "George"; //whether a variable or a key in array, you can access that value in your foreach loop
$date = "yesterday";
$sentence = 'Hello :name, we have not seen you since :date.'; //I'd advise to use the ':key' syntax since things tend to get quite messy with curly brackets in strings.

foreach($placeHolders as $ph)
{
    $sentence = str_replace(":$ph", ${$ph}, $sentence); //replace ":key" with $key in your string.
}

echo $sentence; //Output: "Hello George, we have not seen you since yesterday."
Jul
14
3 months ago
Activity icon

Replied to How Can I Sort Storage File

Check this out: https://stackoverflow.com/questions/40384545/sort-files-by-date-added-laravel-php

Also, there are plenty of solutions out there. Try to look better!

Activity icon

Replied to Relationship BelongsTo Two Columns

There's a ready conception for that purpose, you don't need that third model. What you need is a two sided many to many relationship with a pivot table attribute. The third table results you have shown is exactly 1:1 the pivot table of the file-field many to many relationship. Check out the documentation: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many you'll find examples. But in general what you'd need is: File.php

public function fields()
{
    return $this->belongsToMany(Field::class)->withPivot('content');
}

Field.php

public function files()
{
    return $this->belongsToMany(File::class)->withPivot('content');
}

whereas the pivot table (conventionally named field_file) must contain the following columns as you've shown:

id | file_id | field_id | content
1  | 1       | 1        | #1234
2  | 2       | 1        | #8888
Jul
11
3 months ago
Activity icon

Replied to Get Full Key From Multidimensional Array

That's a classical recursion taks. I've explained everything, hope it's clear:

public function lookUpArray($arr, $desiredKey, $carry = null)
{
    $fullKeys = []; //that's the initial array we'll be returning
    foreach($arr as $key => $val) //begin looping first level of array
    {
        if($key == $desiredKey) //if that's our desired key, add it to the carry (in case it's present) and save in te array
        {
            $fullKeys[] = $carry ? "$carry.$key" : $key;
            continue;
        }
        else if(is_array($val)) //else we'll do recursion
        {   
            //our function returns an array, so we'll merge the results with the results previously gathered in our $fullKeys array
            //our new array to search is the $val array, so we put that in
            //if we had a carry as the key from a previous iteration, just concat it with the current key (add a dot if needed) and that's our new carry!
            $fullKeys = array_merge($fullKeys, $this->lookUpArray($val, $desiredKey,  $carry ? "$carry.$key" : $key));
        }
    }

    return $fullKeys;
}

What you then simply need is:

$arr = [
    'a' => [
        'b' => [
            'c' => 1,
            'd' => 2,
        ],
        'e' => [
            'f' => 3,
            'g' => 4
        ],
        'h' => [
            'i' => [
                'j' => 5
            ],
        ],
        'j' => [
            'k' => 2
        ]
    ]
];

$fullKeys = $this->lookUpArray($arr, 'j'); //or whenever you define it, call it accordingly

Otput is:

["a.h.i.j","a.j"]
Jul
10
3 months ago
Activity icon

Replied to Doubt On How To Define Model For Team-Athletes-Sports Relationsships

What you need is a three-sided many to many relationship, meaning you'll have a team_athlete_sport table containing the three id colums at once. Then you can define a many to many relationship between each two of them that you need and use a custom pivot model TeamAthleteSportPivot. You can refer to the documentation on that matter. Now every time you retrieve the relation of player A playing sport B, you can then retrieve the sport C on that db entry via the custom pivot model's relationships (you'll need respectively three of them).

Jul
09
3 months ago
Activity icon

Replied to Function Is Not Defined Showing In Console But Function Is Exists In File

Your function must be defined in the global scope and I doubt it is since I'm noticing a little }); closing tag under its definition, which suggests to me that it's been defined inside a $(function(){}); body.

Jul
08
3 months ago
Activity icon

Replied to Sum Of Model Attributes With Same ID

Let's presume your chosen ids are stored in a collection:

$chosenIDs = collect([2, 3, 5, 3, 9, 10, 10]);

Then you must retrieve a corresponding volume_flow for each of those IDs to further sum, so you'll still need

$systems = System::whereIn('id', $chosenIDs->unique())->pluck('volume_flow', 'id');

which will be equivalent to a collection like collect([$id1 => $flow1, $id2 => $flow2])//etc...

For your sum you can then optimally do like:

$sum = $chosenIDs->reduce(function ($sum, $id) use ($systems){
    return $sum + $systems->get($id);
});

or alternatively:

$sum = $chosenIDs->map(function ($id) use ($systems){
    return $systems->get($id);
})->sum();

That's the most laravel-ish way I can think of for sure :D

Jul
07
3 months ago
Activity icon

Replied to Complex Query Performance

Yeah, my mistake, I got mislead by what was provided. In order to obtain the last completed status you can instead use ->latest()->take(1) for the query. Haven't tested, but should fit into the concept.

Jul
06
3 months ago
Activity icon

Replied to Laravel Maintenance Mode Troubles

Well, for some reason the --allow parameter was not present in my version. After I upgraded to 5.8 it was working fine, closing the thread!

Activity icon

Replied to Problems To Modify Table Attribute In Migrations, Laravel 5.5

Execute the command php artisan make:migration alter_email_on_users_table --table=users

Then a migration will be loaded with your table already set up. Inside the table() function you may alter columns using the ->change() method at the end of your call. Basically what you need is to specify all the characteristics of your columns as if it were a new one but just call change() at the end of the chain. Like this: $table->string('mail')->after('other_example_column')->nullable()->change()

But be careful - if the new data type does not match the old one, you might loose data. In addition, there is a module that needed to be included to laravel in order to modify columns, but it was a long time ago when I last had to enable that functionality so I forgot the details... but there was something exceptional!

Hope that narrows it down for you.

Activity icon

Replied to Complex Query Performance

Firstly, your lastCompletedStatus() is not conventional and does not return a relationship, but a retrieved model instead. In order to increase efficiency, you need the conventional approach:

public function lastCompletedStatus()
{
    return $this->statuses()->wherePivot('completed_at', '!=', null)->latest()->take(1);
}

Then, you might simply query your orders by last completed status using Eloquent's whereHas() method:

$orders = $user->orders()->whereHas('lastCompletedStatus', function($query){
    $query->where('name', 'given_status_name'); //or however you define a certain status
})->get();

This will retrieve all of the user's orders having their last completed status's 'name' column match the given value (in this case 'given_status_name'). You can change that accordingly.

Hope that answers your question!

Jun
28
3 months ago
Activity icon

Replied to Javascript: Adding A Single Function To Multiple Events

Can't you just specify your function as a variable and then register a listener for your events inside of a foreach loop using that function?

Activity icon

Replied to Query Scope Based On Multiple Conditions

If I understood correctly - if there's a discount_id, you want discounted price, if not - the normal price. If you didn't know, there's an inbound whereBetween method for laravel's query builder, which makes it a bit easier ^^

$query->whereHas('price', function($q) use ($min, $max){
    $q->where(function($q) use ($min, $max){
        $q->has('discount')->whereBetween('category_discounted_price', [$min, $max])
    })->orWhere(function($q) use ($min, $max){
        $q->doesntHave('discount')->whereBetween('price', [$min, $max]);
    });
})

P.S. Not tested, but should produce the needed query.

Jun
27
3 months ago
Activity icon

Replied to Custom Pivot Table Not Being Respected?

@JOHNNYW2001 - It's not in the docs regarding the custom pivot model, but it is stated right in the chapter above. As shown, the using() method is an extension to the belongsToMany() method, where the specification of the intermediate table's name belongs.

Activity icon

Replied to Custom Pivot Table Not Being Respected?

The table is actually not to be specified in the custom pivot model, but rather as a second argument on the belongsToMany() method. Refer to the documentation: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

Activity icon

Replied to Getting User's Coordinates Using A Map In A Form

Definitely Google Maps' API, I've been using it for years and it works flawlessly and is incredibly easy accessible. I don't know to what extent it's free though, you'll have to check the conditions out. If I'm not mistaken though, I think JavaScript provides a native module function to prompt your browser to ask the user for their location, it might be sufficient for your needs.

Jun
20
4 months ago
Activity icon

Replied to Count The Number Of Entries For A Period Of Time

Provided that you have a model class Registration with start_date and end_date column attributes, you can easily query your count:

$todayRegCount = Registration::whereDay('start_date', today())->count();
if($todayRegCount > $maxCount)
{
    //max number of registrations for the day has been exceeded, do whatever you need
}
Jun
17
4 months ago
Activity icon

Replied to User Relationships

@EVERGREENWEBSYSTEMS - Yeah, everything's fine except I'm not sure about the id columns' type. bigIncrements does indeed generate an unsigned incrementing big integer, but again, idk if that's not going to cause any integrity trouble depending on how picky your DB engine is (InnoDB is quite picky in that regard :D). If it works, then it's fine, but I suspect the difference in length will be a problem.

Jun
16
4 months ago
Activity icon

Replied to User Relationships

Yes, your migrations seem just about right. I can only share a couple of notes from my experience:

  1. a tricky problem you might encounter depending on your database engine: initially the foreign keys and the primary keys must be of the exact same type and length for the foreign key constraints to work and not throw an error. So you'll want the ids on your users and projects table to also be unsignedIntegers.

  2. Another thing you might want to consider is the default naming convention of the pivot tables: project_user, which can spare you a couple of table name specifications.

  3. in order to use a custom pivot model, as far as I recall, you need to give the pivot records an id column, so that eloquent can treat them as a model

Then all you'll need in your User model would be a method like the following:

public function projects()
{
    return $this->belongsToMany(App\Project::class)->withPivot('id', 'role_id')->using(App\ProjectUser::class);
}

For more details on the custom pivots, refer to the documentation: https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models

Cheers and happy coding! ^^

Activity icon

Replied to User Relationships

I would personally prefer the single pivot table way since it would be faster to query and easier to access. Laravel provides an easy way to access custom pivot attributes, so you can put your role there, for example as a string access_level or something like that. If you would like to introduce custom role models to furthermore complicate your logic, then you can use a custom pivot model and bind a relationship method to it. If you need some examples, I can provide some, but you can find all you need in the laravel documentation here: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

Jun
14
4 months ago
Activity icon

Replied to Eloquent Query Error

@LEONVR - I suspect that json encoding invitation as a property of inlogdata somehow just converts it into a simple object and not an instance of the model class, which then kills the embedded laravel model functionality. Since I don't see the class either when you dump the invitation, I'm quite sure that's the case. Which refers back to my question above.

Activity icon

Replied to Eloquent Query Error

Seems right, weird... Is $invitation an instance of the right class then?

Activity icon

Replied to Eloquent Query Error

Seems like your $invitation variable is pointing to a stdClass instead of an instance of App\Invitation, can you show us how you retrieve that certain variable in context?

Jun
10
4 months ago
Activity icon

Replied to WhereHas In Advanced LeftJoin

@FTIERSCH - Sorry for the late response, but you answer was actually what I needed! This is how my query looks now and it's working, although it's unimaginably slow (taking ~30s to load)...

$query->leftJoin('documents', function($j){ 
                return $j->on('orders.id', '=', 'documents.order_id')
                        ->where('documents.is_paid', true)
                        ->leftJoin('document_categories', 'documents.document_category_id', '=', 'document_categories.id')
                        ->where('document_categories.type', 'revenue');
                })
                ->havingRaw('price_to_customer - sum(documents.price) > ?', [1])
                ->groupby('orders.id');

I suppose the slowing is comnig from the fact that the documents table contains ~10k records, whereas the orders table contains an additional ~6k, thus things are getting complicated when looping keys...

Regarding functionality though it's all fine. Any optimization ideas are welcome! Thanks a lot!

Jun
09
4 months ago
Activity icon

Replied to How To Get A Value In Js From Laravel Datatable Cell ?

Classical operation - you can either use an ajax request to fetch your data from the server, or you can use a link to a route, which then reloads the page with the given value, if you want to avoid ajax and make it more consistant as performance.

Jun
07
4 months ago
Activity icon

Replied to Method To Sync ManyToMany Relationship From Model With Custom Pivot Columns

Just for an additional disclaimer: I've found a temporary solution for now, which unfortunately includes editing the vendor files... After I've taken a closer look at the relationship's class I've achieved exactly what I need by simply adding a public customPivotAttributes = [] after the protected pivotColumns = []; attribute in the BelongsToMany class and then modifying the withPivot() method in the InteractsWithPivot trait:

    public function withPivot($columns)
    {
        $columns = is_array($columns) ? $columns : func_get_args();

        $this->pivotColumns = array_merge(
            $this->pivotColumns, $columns
        );
        
        $this->customPivotColumns = $columns;

        return $this;
    }

But I really don't like having to edit vendor files since we're planing on migrating to a higher than the current 5.4 version of laravel.

Edit: So basically my solution for now looks as follows:

$manyToManyRelationMethods = ['imposts', 'accessoryTypes', 'dimensions', 'otvarqemosti'];
foreach($manyToManyRelationMethods as $method)
{
    $columns = $scheme->$method()->customPivotColumns;
    $syncablePivotArray = $scheme->$method->mapWithKeys(function($relModel) use ($columns){
        return [$relModel->id => collect($columns)->mapWithKeys(function($col) use ($relModel){
            return [$col => $relModel->pivot->$col];
        })->all()];
    })->all();
    //dump($syncablePivotArray);
}

It's working exactly as I wished. Remaining is just to get rid of the vendor modification!

Activity icon

Replied to WhereIn Clouse Not Working After Using Dynamic Variable.

Seems like a basic php misconception. You're using [$arr_contry_exp], which means you're creating a multidimensional array since you're inputing your original array into another bracket pair. Just remove the square brackets and it shall work if the array is correct: $query->whereIn('country_exp', $arr_country_exp);

Activity icon

Started a new Conversation Method To Sync ManyToMany Relationship From Model With Custom Pivot Columns

I'm building a massive layer to copy a lot of models with a lot of such relationships so I really need this optimization. A basic example: I've got a model Scheme with the following relationship:

    public function imposts()
    {
        //notice the custom attributes on the pivot
        return $this->belongsToMany('App\Impost')->withTimestamps()->withPivot('count');
    }

I want to copy that scheme. Since it can't be achieved automatically with relationship cloning as well, I'm writing a method to do it in the same class:

    public function copy()
    {
        $copy = $this->replicate(); //replicated the model with it's columns and a new id, quite useful

        //here I want to sync the copy's imposts with the original scheme's imposts BUT with the custom fields listed in the relationship definition. Is it possible? Something like:
        //$copy->imposts()->sync($this->imposts()->toSyncableArray()); //I'd imagine such a method, would be quite useful
        
    //a lot of relationships to clone here... incoming

        $copy->save();
        
        return $copy;
    }

What I want that method to do is simply the following that I'm managing to achieve using this mapping:

$syncableImpostsArray = $scheme->imposts->mapWithKeys(function($imp){
    return [$imp->id => ['count' => $imp->pivot->count]];
})->all();

This produces exactly the array I need for the sync method on a scheme with 5 imposts with respective counts:

[ 
  1 =>  [ "count" => 0 ]
  2 =>  [ "count" => 0 ]
  3 =>  [ "count" => 4 ]
  4 =>  [ "count" => 0 ]
  5 =>  [ "count" => 4 ]
]

As mentioned above, I need this for a lot of models with quite a lot of attributes (refactoring a project with copying functionality). Any ideas as to how to achieve this in a slightly more automatic way?

Thanks in advance for all suggestions!

Edit: Even if there isn't a method to automatically convert that to an array, a way to just get a list of customly added attributes to the relationship definition method would be sufficient as I can use the same function as above. I just need a way to retrieve an array like ['count', 'other_attribute', 'another_customly_set_attribute_to_pivot'] etc. Thanks again!

Activity icon

Replied to Call To Undefined Method

In the code provided you're not calling the mentioned method anywhere, so something else is causing the error. You're somehow trying to call a static TotalPrice method which you haven't defined anywhere. Furthermore, you can use aggregate methods and don't have to retrieve the whole collection and iterate it manually. I would go as follows:

public function scopeTotalbillyear($query)
    {
        return $query->whereYear('created_at', date('Y'))->where('status', 'payd');
    }

    public static function getTotalPayd() //since it's a sum of all paid bills, we need a static method which we'll call on the class
    {
        return Payment::Totalbillyear()->sum('amount_payd');
    }

Afterwards you can use your method by simply calling $sum = Payment::getTotalPayd(); which will in turn return the sum of paid amount of all paid bills this year.

Jun
05
4 months ago
Activity icon

Replied to Two Range Of Number For Data Seeding

What don't you like about this approach? If you need it for a single use once, it's okay, otherwise for integrity's sake it's better to use the attach() method on your models' classes to maintain the relationships. But again, this way should be quick and handy enough for the purpose to attaching the relationships. What's the problem?