consil

Experience

12,520

0 Best Reply Awards

  • Member Since 2 Years Ago
  • 118 Lessons Completed
  • 4 Favorites

15th February, 2018

consil left a reply on How Properly Use The LockForUpdate() Method? • 2 days ago

It makes sense to wrap the lock in a transaction, since I assume you are locking a record to do several operations related to it, so they would be in the same transaction. It may work the same if the lock is done immediately before the transaction is started, but any other statements that follow it will (by default) auto-commit and your lock will be lost.

14th February, 2018

consil left a reply on Refresh And Locka A Model • 3 days ago

I think my solution will be to fetch a completely new instance $modelDummy, locking in the process. Ignore that instance from that point on. Its only purpose is to grab the lock.

Then fresh() the original $model, knowing that will then be refreshed from the database against a locked row that I know won't be changed until the transaction is released.

consil started a new conversation Refresh And Locka A Model • 3 days ago

I would like to refresh a model and lock it for updates at the same time. The reason is to make sure we have the latest model data in memory, and that nothing else can update it while we are working with it in the transaction.

The clincher is that I would like to avoid creating a new instance of the model, so that when we come out of the transaction, the model is up-to-date.

This will refresh a model and lock it by loading a new instance:

$model = $model->lockForUpdate()->find($model->id);

This will refresh a model without creating a new instance:

$model->fresh();

What I can't seem to see, is a way to mix the two together. I had hoped this would work, but it doesn't:

$model->lockForUpdate()->fresh();

I'm using this in a transaction like this:

echo $model->status; // NEW

DB::transaction(function () use ($model) {
    $model = $model->lockForUpdate()->find($model->id);
    
    // Do some transactional stuff here.
    
    $model->status = 'SUCCESS';
    $model->save();
});

echo $model->status; // NEW - we get the old model still

I would like at the end for $model to have the new status, but that status change was in a different instance. Any clues how I can fix that first line in the transaction?

8th February, 2018

consil left a reply on (Polymorphic) Many-to-many Relation To Multiple Models • 1 week ago

I'm looking to do much the same thing. I have notes against many models, and models with multiple notes. Given a note, I would like to fetch a collection of all model instances that a note links to, where there could be different model classes in that collection.

I think key to this is that the query for each model type must be run separately. You cannot fetch from multiple model tables in one query and hydrate multiple models from that. The one query you can run, and can sort and set a limit on (you will need to do this if you want to page the results) is the polymorphic relationship.

So for example, you may get the first 10 participant_id and participant_type rows, ordered by creation date. From this you can get a list of unique model classes (in participant_type). There may be one, there may be several.

Then you fetch an individual collection of models for each of those models. For 10 initial rows, you may fetch, say, 6 users, 3 teams and one participant.

Then those collections need to be merged together. The merge order you already have - it's in the results to the first query on the polymorphic relationship. The final merged collection will then be a mix of models related to the competition, and hopefully in a sensible order so paging can be used.

That's the logic behind what needs to be done, but I'm at a loss on how to make it work like a Laravel relationship and not just a helper function.

consil left a reply on Looking To Add Notes To Any Model • 1 week ago

Spot-on, thank you. I searched everywhere, but just didn't find the right terms to hit this one.

I started writing a package to do this last night, and it is very much along the same lines as this one, which is reassuring.

Just to expand a little on my use-case, the notes I am saving are mostly system-generated during some complex data processing tasks. I am wanting to use a many-to-many polymorphic relationship so that the context of each note can include the multiple models that are involved in the processing at each stage. The LaravelNotes package only has a one-to-many relationship, but it is easily extendable.

The many-to-many relationship is where the inverse relation comes into play. Given a single note on a model, being able to get a list of other instances of the same model that the note is also connected to, and other instances of other models that the note is connected to, will be very useful. I can't see how to do that that yet without hard-coding the relationships of the application models into the Note model. I'm sure there will be a way to declare the inverse relationships dynamically, or at least by configuration. Also, getting a collection of models connected to a Note, where different models entirely could be in the collection, is going to be interesting. But I guess polymorphic relationships will support that in Laravel without too much effort.

7th February, 2018

consil started a new conversation Looking To Add Notes To Any Model • 1 week ago

I'm wondering if anyone has any recommendations for a package that allows notes to be added to any model in an application. I'm guessing what I need is a polymorphic relationship, that can provide many child records for any other model, and probably a trait to add it to those models. It should be easy enough to write, but I am looking around to see if such a thing already exists so I can see it working practically.

Whether it just deals with the back end relationships, or has views and permissions for dealing with the front end too, I'm not too bothered about, just looking for an example.

29th January, 2018

consil left a reply on [L5] Class App\Console\Kernel Not Found • 2 weeks ago

Just to note, you should be able to change the application namespace to anything you like, and Laravel is very happy with you doing so (you could have multiple applications in once install, for example). However, there are many third-party packages, and just about every tutorial written ever, that make the assumption your root namespace will be App.

21st January, 2018

consil left a reply on Build Eloquent Structure Before Saving Everything At The End? • 3 weeks ago

Thanks all. I think in this case I needed to have a little more control over the database sessions. I'm saving error messages to the database while validating the data structure being imported, so I wouldn't want those messages to be rolled back. But I don't want any source data in the database if a single error is hit at any point.

I'm trying this out at the moment as an experiment: since I can't push unsaved child models into an unsaved parent model's relations, I'm instead pushing them into a custom property collection that I am calling "staging".

So I have the $post object, and populating its own properties as normal. Then I'm pushing a bunch of comment objects to its staging collection:

$post->stagingComments->push($comment);

The stagingComments property is a getter that provides access to a stagingComments property intialized to a collection. So I end up with a bunch of eloquent objects all structured into a tree, but not yet saved.

It is at this stage I need to do a dozen or so complex validation checks on the structure, and the nesting and collections provide some great tools for that.

Once the validation is successful, I can whizz through the structure from the root up, saving everything and linking the relationships (that's the easy bit since all the data is already in the form of eloquent objects). I'll do that in one transaction so I can be sure the whole lot goes into the database fully or not at all.

Naturally, it's late, it's experimental, and I might have to revise this in the morning after a good night's sleep. But it is looking promising.

consil left a reply on Build Eloquent Structure Before Saving Everything At The End? • 3 weeks ago

I've never used Doctine, but will give it a try to see if it makes things like this easier.

So the idea with eloquent is to write everything to the database in a transaction, and then only commit it if you want to at the end. If you don't want it stored permanently, then roll it back.

consil started a new conversation Build Eloquent Structure Before Saving Everything At The End? • 3 weeks ago

I am loading a text file which contains data that will be structured into four tables. I am currently loading the data into nested collections. When it comes to saving it, I loop over the collections and create models to save.

Now, it occurred to me I'm creating an extra step here - putting the data into one structure, then moving it to another. It makes sense to put the data directly into nested models (all in a with of one-to-many relationships). So is that possible? Can I create that structure before saving to the database?

So to note, I don't want to save anything to the database until I have the whole data structure in memory. If Laravel provides a way to save the whole structure in one go, great, but if not, it's not a problem - I can just loop over the model instances.

If a model is set as a child of another in memory, then when I come to save that child, does eloquent automatically know to add in its referential link to its parent? Or do I need to do that myself?

Thanks. Hope that makes sense.

18th January, 2018

consil left a reply on Form Validation: Custom Error Message With Input Value • 4 weeks ago

Just looked through the code (I was trying to find a version of :attribute that did not "nicify" the names of the attributes) and found :input. That placeholder will put the name you want into the error message.

I didn't find what I wanted, but discovered that :attribute, :Attribute and :ATTRIBUTE placeholders do some fun things with the letter case of the attribute name.

consil left a reply on Form Validation: Custom Error Message With Input Value • 4 weeks ago

Would be nice to see this. I'm using the validation rules to validate CSV files as they are imported, so logging the erroneous values within the message text is very useful. It's not like a form where the message can be placed next to the field in error, so it has context.

3rd January, 2018

consil left a reply on Best Practice For Handling "active" Menu Item In L5 • 1 month ago

@johnef_sh see step 1:

Create app/Http/Helpers/BasicViewHelper.php...

2nd January, 2018

consil left a reply on Best Practice For Queues • 1 month ago

It might depend on the API you are using. If the API can retrieve details of all five songs in one call, then it may make sense to handle them all as one job. But the uploading part of your application may push you the other direction.

In general, keep one job doing one thing that can happen independently of other things.

7th September, 2017

consil left a reply on [Package] L5 Package Skeleton • 5 months ago

The digital-baker git user seems to have been deleted or made private now. I just get a 404.

consil left a reply on Where Do I Raise Issues Or Provide PRs? • 5 months ago

Ah, thank you, got it now. The repository does not show up in my list of repositories on github. I actually need to know the URL, and know I'm logged in as the right user, to get to it.

6th September, 2017

consil left a reply on Just Launched My Spark App: ZoneWatcher • 5 months ago

Looks great. However, what do teams represent here? If I'm coming to your service from fresh, and am asked to create a team as the first step, I'd be pretty stumped as to what they mean, what they are, and what I would do with one.

consil started a new conversation Where Do I Raise Issues Or Provide PRs? • 5 months ago

Can't work it out for the life of me, but I'm finding bugs and issues as I go through installation and try to use Spark, but I cannot find any channel to feed this issues or solutions back to. What am I missing? I'm just so used to there being open repositories that I can raise issues on, check for updates, check past issues other people have been having, seeing what fixes other people are doing in their own branches etc. It is kind of frustrating.

consil left a reply on Spark Installation Errors • 5 months ago

I noticed on a recent install that Spark uses some OS tools such as make and a few other less common ones. I needed to manually install them on my server before it would install. This is just one of many dependencies that the install process does not check at the start, but ploughs on through partially installing, and can be very easy to miss in masses of log entries.

1st September, 2017

consil left a reply on Support For User Roles In Spark? • 5 months ago

Just to be clear, this is about the "role on a team" in Spark. Additional ACL roles can be added and applied to the users separately from Spark's roles.

One problem I have with the Spark roles implementation is that it supports just ONE role for each team member. To me, that's not a role; it's a user attribute that defines what a user is (within a team), and not what a user can do. If the team_users table did not have a unique compound index on the team_id and user_id columns, then support for multiple roles could be implemented. Not supporting multiple roles per user is a big oversight IMO when it comes to implementing applications to support real-world situations.

15th August, 2017

consil left a reply on Which Package Is Best For Roles & Permissions • 6 months ago

@daniel.schreij that looks interesting, and seems to be built on the latest 5.x built-in ACL, unlike most of the other solutions which bring most of the ACL functionality along with them. And the older packages are fine, but it always seems if Laravel is giving a pointer on a direction to go, and any package not going down that route will end up being harder to support as time goes on.

10th August, 2017

consil left a reply on Migrations: Configure A Default String Length? (utf8mb4) • 6 months ago

This SO post gets straight to the one-line solution in the AppServiceProvider boot method:

https://stackoverflow.com/questions/23786359/laravel-migration-unique-key-is-too-long-even-if-specified/23786522#23786522

16th June, 2017

consil left a reply on Setting Table Dynamically • 8 months ago

So, this works for pointing a model at a table.

Next step is using the configuration value in a migration. Is it as simple as accessing the same value from there?

15th June, 2017

consil left a reply on What Can A Package Bring To A Laravel Install? • 8 months ago

@Cronix I feel silly now. My head is still stuck firmly in the 5.1 documentation. All looks great - thanks.

consil started a new conversation What Can A Package Bring To A Laravel Install? • 8 months ago

I'm just curious as to what a package, installed through composer, can bring to an installation of Laravel. Obviously it can bring useful classes that can be used by custom code, but what else?

Config files can be provided by a package, that are installed into the config area. What about other assets? Can they be installed by a package too? If so, would they be like npm dependencies, or assets that go straight into the public area? Or would they need to be manually copied as a procedure to installing the package?

What about views and routes? Can a composer package bring those to a Laravel instance it is installed into? Or again, would manual copying of files be needed? I realise that an artisan command to install these files into the correct place may be needed, and if it is just the artisan command, that's great.

Or am I hoping Laravel does too much at this level, leaving a package as something that you need to glue in with custom code?

consil left a reply on So, Where To Start A New Project With A Baseline? • 8 months ago

Yes, https://github.com/jeremykenedy/laravel-auth seems to be well thought-out and has many things I needed right from the start.

One niggle is that each user can only be assigned one role, which is something I thought died out a decade ago - yes, one user can be a supplier and a customer - it's just the way the real world works. Still, it's better than a poke in the eye with a sharp stick, and is fine for our prototype.

consil left a reply on So, Where To Start A New Project With A Baseline? • 8 months ago

Okay, this is what I am trying now:

https://github.com/jeremykenedy/laravel-auth

Once the server was set up, and I understood how to install node and npm in my account, it all installs nicely and feels to be a great baseline.

consil left a reply on From Zero To Being Able To Being Able To Enter "npm" Commands • 8 months ago

Just found these instructions which got me up and running:

https://hostiso.com/how-to-install-setup-node-js/

This will install node and npm in your local account, so nothing needs to be installed globally on the server. node is a compiled binary, while npm is a JavaScipt script that runs with node as its interpreter.

The latest code is downloaded as an archive from here: https://nodejs.org/en/download/ then expanded to a directory in the account.

The binary node is copied from the extracted archive to the bin directory in the account. Now, I found that the bin directory (even though it did not exist until I created it) was already in my PATH. I guess that is a WHM or cPanel feature.

After copying the node binary, the npm script and a number of its required siblings and support scripts are symbolically linked into the bin directory. This means the extracted node archive must not be moved, so make sure it is in an appropriate page. I extracted it to nodejs/ in the home directory of the domain account.

And that was it. Both node and npm are then available as commands when I log in, and that is what Laravel needs to do its asset management, downloading, compiling, minimising, etc.

I have kept the description to just the concepts above, and left the detailed commands to the page I linked at the top. It's all pretty simple in the end, just four or five commands. Updating the commands will just involve repeating the same steps, which take just a couple of minutes.

consil started a new conversation From Zero To Being Able To Being Able To Enter "npm" Commands • 8 months ago

Got a WHM/cPanel server and am installing Laravel with all the trimmings in an account. Part of the install involves running npm commands. I am trying to understand what needs to be installed and where , in order to do this.

Searching for this, there are many mixed instructions on what to do. I have not been able to find any articles that explain just what is needed and how it interacts. For example:

  • What needs to be installed on the operating system globally, perhaps maintain by yum or whatever is used for OS package management?
  • What needs to be built from source, due to their now being any official packages for the OS?
  • What needs to be installed in the account where Laravel is being installed?

I'm not just looking for a series of commands to blindly run. I would like to understand what those commands are doing and where, so I know what needs to be maintained. I'm technically literate, so techy is fine :-)

consil left a reply on So, Where To Start A New Project With A Baseline? • 8 months ago

Aghh! Just typed up a long reply, did not realise this forum had expired tokens in the page, refused to post it, then discarded the post I have typed up. Firefox will remember what you typed on going back a page, unless the site tells it not to. This is an annoying bug that has caught me many times in the past, and really needs to go. Just don't throw my post away!

Anyway, found some stuff, did some stuff, looking good so far, and will come back later to fill in the details again.

13th June, 2017

consil left a reply on It Is Ok To Use LetsEncrypt Free SSL? • 8 months ago

No fret about it. Just use it from the start for all your pages. If a site needs more for any kind of verification reasons, then deal with that when it is needed. For now, just encrypt all connections, and what better way to do that than with a free SSL provider that, TBH, is respected greatly for what it has done for the industry.

consil left a reply on So, Where To Start A New Project With A Baseline? • 8 months ago

I am totally with you @jlrdw and understand what you are saying. I would say the same thing to anyone else starting out, including never underestimating the power of pencil and paper to flesh out an idea. I do that all the time.

I've been down this path a number of times, and have projects written in different versions of Laravel over the years, even going back as far as FuelPHP, which I feel set down some of the structural groundwork that Laravel followed.

Each project is still running today, doing its thing in its own legacy ways. Each followed the lessons of the day, was built on the packages of the moment that seemed popular and did things in a way that felt natural and right. They were all good, and are now all stuck in their own little walled legacy gardens with the occasional updates and bug fixes.

The trouble is, the user stuff - logging in, registering, managing the users at the back end, roles, privileges, ACLs, password recovery - all that stuff is kind of a little footnote in my current project. I just want it done and out the way; "[x] Users". Ticked. Done. Now I can move on to the real guts of the application and flesh it out. That's where the real business end is.

I guess I am looking to hit the ground running a little faster than I would be with a big box of loose LEGO bricks, to mix my metaphors. And I am sure many other people are right there too, and have found the perfect solutions that provide enough out of the box to provide the framework that does things the right way - the Laravel way - and is ready, excited and eager to accept custom modifications so it can shine brighter than it could ever have dreamed.

Sorry, got carried away there. I've looked at Spark. That seems to very much revolve around implementing one particular business model (reseller apps). So I was hoping someone here had hit just the right magical combination of packages, libraries, glue and customisations.

consil started a new conversation So, Where To Start A New Project With A Baseline? • 8 months ago

I bet thousands of people ask this question every day, search the web, find dozens of partial solutions, dozens of tutorials with half a solution, packages and projects that have been abandoned a year ago, or are not clear in what they do or do not do...so what is today's baseline that will give a new project its initial leg up?

I'm looking to start a new project, hopefully L5.4 or thereabouts. I would like user registration, backend user admin, roles, permissions, password reset, maybe social media auth. You know, all the usual stuff that has to be done, just kind of there and working.

I can install Wordpress, and all that is there in five minutes flat. That;s a great start, but then Wordpress is a MONSTER to try to develop in, leaving you banging your head against a brick wall more often than not. Laravel is an absolute pleasure to develop in. But I want to just get on with the application and now have to spend a week messing on with admin pages, password recovery, registration etc. before I can get close to the application functionality. I'm looking for a rapid but fully functioning prototype framework to build in.

So, am I asking too much? Or are there great solutions to this that I have not found? Or is all there already but I just can't see it?

Any recommendations?

22nd March, 2017

consil left a reply on Best Practice For Handling "active" Menu Item In L5 • 10 months ago

@mustard Yes, you can look at the URL path, but you must stay aware of what the implications of that are.

Paths are generally (and should always IMO) be defined in the routes.php map. Outside of that script, I don't believe views or controllers should be aware of what those paths are. Paths can easily change as an application develops and grows. The names of the paths however, can remain fixed since they define a business function.

But horses for courses - it's not wrong, just understand what its advantages and limitations are.

30th October, 2016

consil left a reply on Best Practice For Handling "active" Menu Item In L5 • 1 year ago

@awks If you specifically check for equality to zero, then you can make sure the route starts with the relevant string:

{{ strpos(Route::currentRouteName(), 'admin.dashboard') === 0 ? 'active' : '' }

That will match admin.dashboard.bar but not foo.admin.dashboard.bar. That may or may not be what you want, but it's something you can do.

I would also return and empty string instead of null, then there is no type-casting needed, since {{ ... }} will be expecting a string to be returned, or will need to cast whatever is returned to a string. Just start with a string and get it over with.

24th September, 2016

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

Hi @mr415

When I first started this I had the assumption that Vue would have its own data model mapped to the structure and would be used to draw the initial tree. That proved very difficult to implement, and TBH did not offer any benefits. So instead I just drawn up the structure using standard nested loops in blade, giving elements appropriate IDs, classes and other attributes, then use some pretty standard jQuery to point sortable at the dragable elements in the tree. That proved pretty simple in the end.

If there were a draggable tree plugin to Vue, that sat on top of Vue, then it may be a completely different matter. So, tried that route, then threw it away and went for simple jQuery and sortable.

18th September, 2016

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

The AJAX URL just identifies the node (in the path of the URL) and its new position (in GET parameters). Whether it is absolute or relative should make no difference - it is just what the route() function spits out.

Alternatively you could have one path that all the nodes share, with the node IDs being passed in also a GET parameters. Whatever is easiest for you really. The key things are:

  • It is a PUT action and not GET, so things don't get accidentally moved around by visiting URLs in the browser.
  • You are getting the data you need to implement the move in the database to a controller method. Whether that method has parameters mapped to the route path, or simply looks at POST parameters, makes no difference. You are just getting the new position data to the server so it can manipulate the database to reflect the drag-and-drop you did on the front end.

It's about keeping the front end and the database in sync. The sortable library lets you drag nodes around the tree structure, and that's great. Then each time a node moves, the server needs to be told what has just moved, and that is the AJAX call.

Of course, things can still get out of step, or out of order, because there is no guarantee the AJAX call will work. A node may have been deleted or moved by someone else, or an AJAX call may have failed, or was slow. A large, fancy JS framework may be able to handle what then happens reliably and consistently, but vue.js and jQuery with some simple AJAX is not going to cope with all eventualities. But just programme defensively, and if the user gets errors, they can just refresh the page and everything should be back in sync.

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

Using console.log(whatever) in your JS, and inspecting the console using Firebug or whatever equivalent your browser has, can give you a lot of information about what is happening. I tend not to look through the code too much - I find JS very difficult to get my head around being a mostly back-end developer, with it all being kind of mystery layers of dynamic context and scopes - but just inspecting what data it throws around is often all you need to know (i.e. what it does rather than how it does it).

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

Rather than littering the tree with JS fragments, I use jQuery to scan the DOM for draggable lists and apply the Sortable events to it. This is at the bottom of my tree page:

@push('ready-scripts')
    jQuery("#show-map .groups, #show-map .judges, #show-map .classes").each(function(i, el){
        Sortable.create(el, {
            handle: '.drag-handle',
            animation: 150,
            forceFallback: false,
            onUpdate: function (evt) {
                var url = evt.item.getAttribute('url');
                if (url) {
                    $.ajax({
                        method: "PUT",
                        url: url,
                        data: {position: evt.newIndex}
                    });
                }
            }
        });
    });
@endpush

The selector (#show-map .groups, #show-map .judges, #show-map .classes) selects each <ul> that has sortable child elements. The onUpdate event reads the URL on a <li> that has been dragged and PUTs it to the server along with its new position.

This at the bottom of our outermost page template, just before the closing </body>, renders this @push() section in the right place:

        <script>
            jQuery(document).ready(function() {
                @stack('ready-scripts')
            });
        </script>

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

Completely aside, instead of this:

<ul class="list-group" id= <?= '"section' . $section->id .'"'; ?>>

You can do this:

<ul class="list-group" id="section{{ $section->id }}">

That will keep much of the raw PHP out of the blade view.

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

The url included with each element is the route that you use to update the list?

Essentially yes:

<ul class="classes list-unstyled list-group in">
    <li class="class" url="http://example.com/admin/shows/14/groupjudges/43/position/newposition">
        <a title="A show class" href="http://example.com/admin/shows/14/groupjudges/336" title="Edit judge">Judge Dredd</a>
    </li>
    <li class="class" url="http://example.com/admin/shows/14/groupjudges/43/position/newposition">
    <li class="class" url="http://example.com/admin/shows/14/groupjudges/43/position/newposition">
    <li class="class" url="http://example.com/admin/shows/14/groupjudges/43/position/newposition">
</ul>

There are more levels than that, but it gives you an idea. Each of these would need additional data to identify just their ID, so when dragging to a new parent, you can identify that parent to notify the server.

This is all generated as plain HTML using loops in blade templates. I'm sure the tree could be generated on the client side through pure data bound to the HTML using vue.js. But that's a whole new ball-game for another day :-)

consil left a reply on Recommendations For Drag-and-drop Reordering • 1 year ago

@mniblett just in the last few days, the client has asked us if they could move the sessions between judges. Oh well :-)

The general approach I took, is that each draggable <li> element is given a URL attribute. When it is dragged, that URL is used to tell the server that this element has moved (using PUT). The URL contains enough for the server to identify which element in the list you are moving, and it also identifies that it is a movement taking place.

So for example, a judge in a show may have a "moving URL":

<li url="http://example.com/show/123/judge/456/position">Judge Dredd</li>

So that is the URL we PUT to in order to tell the server this node has been dragged. What we then need is additional data to tell the server where we have dragged it to. That is sent as GET parameters. The draggable front-end library I used has draggable events to tap in. In my case I was not worried about changes to parents, but simply the new position in the current branch the judge is in - so I send position=N in the PUT request. The server then works out what needs to be changed in the database to implement that (changing siblings in the nested set left/right values - but that really depends on how your data is managed).

You (and maybe me next week) will probably also need to send the parent ID with the drag-and-drop action. So adding another custom data attribute to the draggable elements will be needed - the ID of that node on the server, because the front end will need to know the parent of the node you have dragged the element onto, so it can tell the server.

I'm sure there are frameworks and libraries to kind of do all this stuff without having to worry about the details, but I'm not into big JS frameworks and so am putting together much smaller building blocks, so have to understand a little more about what is happening at a lower level.

24th August, 2016

consil left a reply on Laravel 5.1 - Same Form For Create And Edit Page • 1 year ago

Just to add to this, I see a lot of recommendations to use Form::open() for creating a new resource and Form::model() for modifying an existing resource. In my experience, it is more beneficial to use Form::model() in both cases, i.e. when creating and modifying.

When creating a resource, the controller can provide a blank model:

$model = new Model();
return view('model.create')
    ->with('model' => $model);

Why would you do that? For defaults. Default values can be set in the model, and those will feed through to the create form:

class Model extends LaravelModel {
    protected $attributes [
        'some_field' => 'my default',
    ];
    ...
}

Depending on the context, those defaults can also be set or overridden in the controller (create method):

$model = new Model(['some_field' => 'a different default']);

8th August, 2016

consil left a reply on Getting A Tree Of Models In The Correct Order • 1 year ago

Finally did it, but what a pain! I'll post the details later, but in summary the approach was to do a single select first to get all the IDs of A, B and C in the correct order (the order will change from one context to another, so it is arbitrary). Then I do a nested eager load of A, B and C, which generates three queries for the three-level tree. Each level is given the appropriate IDs from the first query for its own ordering using the MySQL FIELDS() function.

5th August, 2016

consil left a reply on Getting A Tree Of Models In The Correct Order • 1 year ago

Just had a thought while watching the Olympics opening ceremony.

I could let Laravel eager load the nested collections. That would be fairly efficient, with it getting all the models in three queries (one for each level).

Then I can do a single database query on the same data, but with my own custom ordering, whatever it may be. The results of that plain query can be used to order the IDs of all the models in the nested collections. That should be fairly simple to do, since all the ordering data will be in once result set.

consil left a reply on Getting A Tree Of Models In The Correct Order • 1 year ago

Good question. Yes, we can just take the first D under each C to determine the order of the Cs.

consil started a new conversation Getting A Tree Of Models In The Correct Order • 1 year ago

I am going to have to explain this one as it is a bit tricky. I have a tree of different models, four layers deep. We can call then A, B, C and D. Each A has many B, each B has many C, and each C has many D. Simple enough so far. Given a single A, I want to display the tree as nested lists. So for A I show a list of B. For each B I should a nested list of C etc. So far, so good - just do n eager load and off we go: A::with('B.C.D')->get().

Now the tricky part. The property to order this tree with is an attribute of D. So the the ordering happens at the leaf nodes of the nested collections that make up the tree. How can I do that? How can I make sure B and C are ordered so that the D leaf nodes are in the correct order?

I can work around this by putting an ordering property on every level (B, C and D) in the database, but I would like to avoid that if possible. Perhaps there is some kind of reordering I can do to the nested collections once I have them back, using recursive callbacks for ordering? Not sure - I have a hunch this will be the way to do it.

Any thoughts?

20th July, 2016

consil left a reply on [L5] Disable CSRF Middleware On Certain Routes • 1 year ago

@mdeclaire That is certainly the easiest technique. But do be aware, that App\Http\Middleware\VerifyCsrfToken lists the URLs that are excluded, not the routes. It uses the $request->is() method internally, so includes whatever wildcards that supports.

Personally, I don't like mixing route names and URL fragments all over the place. The controllers should not have to know what the URL formats are (laravel out of the box puts url paths in several places, which all need to be found and replaced with route names). Anyway, sorry to rant :-)

29th June, 2016

consil left a reply on Constraining/Ordering Multi-level Eager Loaded Models • 1 year ago

Yes, that is one way to do it. Eloquent collections have some great sorting methods built in.

I've just tried this out of curiosity, and it seems to work. The crazy thing is, the number of queries that are performed by eloquent do not increase - it does one SELECT for the orderlines, putting them in order, then one select for the products, making use of the orderlines it has already selected and cached. I have this working four levels deep, and it does exactly what I need.

Orders::where('id', 1)->with([
    'orderlines' => function($query) {
        $query->orderBy('line_number');
    },
    'orderlines.products' => function($query) {
        $query->orderBy('product_number');
    },
])->first();

(Ignore the fact that I have multiple products on each orderline!)

I will go for this technique for now, and if it every stops working (because I am not sure if it works by design, or some fluke) I have the fallback of being able to order the collections after the full nested tree is fetched from the database.

consil left a reply on Constraining/Ordering Multi-level Eager Loaded Models • 1 year ago

The callback that is passed $query seems to be called just once, against the last model in the chain. So in this case against the product. I need to be able to tap into both the product and the orderlines relationship query.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.