Buy your loved one the ultimate gift. Lifetime gift certificates are $100 off.

thc1967

Experience

28,860

3 Best Reply Awards

  • Member Since 8 Months Ago
  • 250 Lessons Completed
  • 0 Favorites

18th October, 2017

thc1967 left a reply on Testing A Digest - Email Content • 1 month ago

I think I clicked too quickly. Sigh.

So I like the idea of having a separate digest creator. In fact, I think that's what I must do. $mail->items is nothing. I can see the things that I attach to the Mailable if I dump() it, but they wind up as protected properties so I can't look at them in the test.

10th October, 2017

thc1967 started a new conversation Testing A Digest - Email Content • 2 months ago

Hi again.

Today, I'm writing code that sends an email digest. To stay with the ubiquitous forum example everyone is familiar with, let's say that Users can Subscribe to get Notifications when Posts or Comments are created. Let's also say that we want to do this in daily digest format instead of immediately upon creation.

This means that I have to periodically create email and when I do that, I need to ensure that the Posts and Comments of interest to the User are included in the email while those that are not of interest to the user are excluded.

I already know how to code the email generation. I can generate the mail digest no problem.

What I don't know is how to write the unit test to dig into the body of the email to ensure that I see the information I expect to see and do not see the information I expect to be absent.

I can do something like this to verify that we send to the user I expect, but how do I interrogate the body of the email?

public function digest_email_filters_to_subscribed_posts()
{
    // Do my setup

    Mail::fake();

    // Do the thing that would send the emails

    Mail::assertSent(PostDigest::class, function ($mail) use ($user) {
        return $mail->hasTo($user->email);
    }
}

I think Tighten.co has a package that might let me test this, but I wanted to stick with core Laravel if it's possible there.

Thanks!

8th October, 2017

thc1967 left a reply on Migrate & Seed Only Once? • 2 months ago

I think I have it working with the Laravel DatabaseTransactions trait... mostly.

MySQL behaves differently than Sqlite when using transactions. The biggest change seems to be that when we consume an autonumber in MySQL, that autonumber stays consumed. This invalidates tests like ensuring I've redirected to a specific record ($this->assertRedirect(route('posts.show', 1))). The ID of the record would only be 1 for the very first test that I run that creates the object.

This is more proper database behavior, of course, but it means I need to rethink my test cases a little bit.

7th October, 2017

thc1967 left a reply on Migrate & Seed Only Once? • 2 months ago

Actually, the make(Comment::class) calls create(Post::class) which does persist it to the database...

...but it doesn't because it's all transacted because I'm using the transaction trait in my test.

So my theory is that the the data created during the transaction that started in my test class isn't able to be seen in my controller, which I'm almost certain is running in a separate process from my test class.

thc1967 left a reply on Migrate & Seed Only Once? • 2 months ago

$item = make(Comment::class); // Creates a Post behind the scenes.

$this->post('/comments/store', $item->toArray()); // Touches the Post

The $this->post() results in a 500 error, which comes back as a referential integrity constraint violation because the Post that the Comment created doesn't exist within the context of the controller.

I think that's because I'm running the transaction within the Test object, which is a different memory space than the Controller, so the Controller isn't aware of the transaction...

Unfortunately, I'm distracted with other things so I've had to stop digging. Will be back to it later this weekend hopefully.

thc1967 left a reply on Migrate & Seed Only Once? • 2 months ago

That's a cool idea.

Unfortunately, transactions do not seem like they're going to work because of the context switch when testing controllers with objects that have relationships.

I'm creating the related objects in my test case, but those relations don't carry through into the controller when I call it with something like $this->post($route, $params). Therefore, I bomb out on referential integrity constraints in my controller.

Maybe if I do it without transactions. Do a migrate:fresh --seed before each run of my full test suite and just let the tests load up the database. Doesn't matter; it's a test database, right?

6th October, 2017

thc1967 started a new conversation Migrate & Seed Only Once? • 2 months ago

I've finally bumped into a spot in my project that I can no longer use an in-memory sqlite database for my unit tests. It was cool while it lasted but, alas, I need to do some stuff that sqlite simply doesn't support.

And I want to keep using unit testing. I'm pretty stoked that I have hundreds of tests with thousands of assertions. I've found it helps tremendously with everything I do.

And I refuse to design my code around shortcomings in the testing setup I've elected to use. My code needs to be right and the tests should support and verify that; not the other way around.

So now I face the prospect of running my unit tests against a real, "on-disk" database like mysql (same thing I'm using for production).

With a sqlite memory database, I didn't have to worry or care about exactly how the tests would run the migration and the tiny little seeder I set up. If it ran them before each test class or even each function, that wouldn't be a big deal. It's all in memory.

That won't be the case any longer.

How, using Laravel 5.5, do I ensure that my PHPUnit tests run my migration and seed just once before running all the test classes & methods?

Thanks for the advice!

30th September, 2017

thc1967 left a reply on How To Get Array Of Fields That Have Been Updated • 2 months ago

Call $this->getDirty() to get the elements that are changing and the values they're changing to.

The Eloquent model will only return an array from that method if you have not yet persisted the record.

$user = User::findOrFail(1);
$user->name = 'a new name';
$user->getDirty(); // ["name" => "a new name"]
$user->save();
$user->getDirty(); // []

thc1967 started a new conversation My Array-fu Is Weak. Is There A Better / More Efficient Way To Do This? • 2 months ago

In an Eloquent Model class...

        $changing = collect($this->getDirty());
        $originals = collect($this->getOriginal())->intersectByKeys($changing);
        $mapped = collect([]);

        $changing->each(function ($item, $key) use ($mapped, $originals) {
            $mapped->push([
                $key => [
                    'new' => $item,
                    'old' => $originals[$key],
                ]
            ]);
        });

22nd September, 2017

thc1967 left a reply on Local Scopes Functioning Apparently Intermittently • 2 months ago

Answer:

return static::forSearch()->addSelect([...

Sometimes you just have to look at it in a different context to see the obvious.

thc1967 started a new conversation Local Scopes Functioning Apparently Intermittently • 2 months ago

In my Model-derived class, I have added two query scopes:

public function scopeForSearch($query)
{
    $query->leftJoin('clients', 'clients.id', 'tickets.client_id')
        ->leftJoin('users as submitter', 'submitter.id', 'tickets.submitted_by')
        // blah blah blah stuff here is irrelevant
        ->addSelect([
            'clients.name as client_name',
            // blah blah blah more irrelevant detail here
        ]);
    
    return $query;
}

public function scopeForDownload($query)
{
    return $query::forSearch()->addSelect([
        'issue_types.sort_order as issue_type_sort_order',
        // blah blah irrelevant list of stuff
    ]);
}

Then off to my PHPUnit test class:

/** @test */
public function scope_for_search_returns_related_name_values()
{
    $t = create(Ticket::class);

    $tickets = Ticket::forSearch()->get();

    $this->assertCount(1, $tickets);
}

/** @test */
public function scope_for_download_returns_related_table_values()
{
    $t = create(Ticket::class);

    // BadMethodCallException: Call to undefined method App\Models\Ticket::forDownload()
    $tickets = Ticket::forDownload()->get();  

    $this->assertCount(1, $tickets);
}

The problem?

The line in scope_for_download_returns_related_table_values throws an exception. The scope for search test works fine.

What'd I do wrong?

20th September, 2017

thc1967 left a reply on Traversing Multiple Many-to-many Relations • 2 months ago

No, not for the application I'm writing. This is without a doubt the right data model. Clients can share users. When a user logs in, I want them to easily see all their clients and all their products associated to all their clients. There is also plenty of other stuff that I'm tracking that needs to relate to both and trying to split clients & users out into a separate database per client would be brutal for the rest of the app.

I don't know why I'm trying to save a few simple queries when the ORM is so chatty anyway, but I'm pretty sure I can do it with inner joins.

That solution is more SQL than "Eloquent", but I can't figure out an Eloquent implementation that gets me down to one query instead of one query per client associated to the user + the products query afterward.

19th September, 2017

thc1967 started a new conversation Traversing Multiple Many-to-many Relations • 2 months ago

Say I have set up my data model such that a user has multiple clients and a client has multiple products. My tables look something like this:

users -> client_user -> clients -> client_product -> products

What's the most efficient way, given a user, to get the list of (distinct) products?

I looked over the documentation for hasManyThrough() but that seems to require a 1:M relationship.

I could use raw queries, I suppose, but there seems like there should be a better, "Eloquent" way.

Thanks!

10th September, 2017

thc1967 left a reply on Many-To-Many Detach Sometimes Fails • 3 months ago

Based upon additional testing I've done to narrow it down, it looks like it's a bug in the framework.

If you call ->detach([...]) after loading the relationship, the framework correctly deletes the rows from the pivot table but does not remove the records from the in-memory object you called it on.

https://github.com/laravel/framework/issues/21111

thc1967 started a new conversation Many-To-Many Detach Sometimes Fails • 3 months ago

My Models are User and Client with a Many to Many between them. Both sides implemented as a $this->belongsToMany().

In the following code the second method to detach seems to fail. The records do seem to be removed from the database because those assertions pass; however, the final assertion that they're actually gone from the Model fails.

The failure on that last assertion only occurs for the second method of detaching. The first and third methods pass that assertion, too.

Why does the second fail?

/** @test */
    public function basic_user_client_detach_test()
    {
        $user = create(User::class);
        $clients = create(Client::class, [], 2);
        $user->clients()->attach($clients);

        // Method 1 works.
        $user->clients()->detach($clients);
        
        // Method 2 does not detach.
        $intersectingClients = $clients->intersect($user->clients);
        // dd($intersectingClients->pluck('id')->toArray());  // ->  [0 => 1, 1 => 2]
        $user->clients()->detach($intersectingClients->pluck('id')->toArray());

        // Method 3 works.
        $user->clients()->detach();

        // These pass for all 3 methods.
        $this->assertDatabaseMissing('client_user', [
            'client_id' => $clients[0]->id,
            'user_id' => $user->id,
        ])->assertDatabaseMissing('client_user', [
            'client_id' => $clients[1]->id,
            'user_id' => $user->id,
        ]);

        // This fails for Method 2.
        $this->assertEquals(0, $user->clients->count());
    }

Thanks!

8th September, 2017

thc1967 left a reply on Testing And Apostrophe Characters In Fields • 3 months ago

That does the trick. Thanks!

thc1967 started a new conversation Testing And Apostrophe Characters In Fields • 3 months ago

I get tests that fail every so often because of the way the system, not sure what part, handles apostrophes.

When I use $faker->name, I often get something with an apostrophe, and it's most often O'Connell.

When this happens, my tests that do an ->assertSee($model->name) fail because what actually goes into the HTML is O'Connell.

What's the best way to avoid these phantom failures?

Thanks!

2nd September, 2017

thc1967 left a reply on Passing A Variable Into A Blade @include - Variable Not Defined • 3 months ago

OK this totally doesn't make sense. When I do a simple test with it, even nesting includes and sections relatively deeply, it works.

It doesn't work in more complicated code.

thc1967 started a new conversation Passing A Variable Into A Blade @include - Variable Not Defined • 3 months ago

This seems to be the way the documentation suggests to do it.

In my parent Blade template, I have:

 @include('layouts.forms.btnsavecancel', ['cancelRoute' => '/'])

In the layouts.forms.btnsavecancel, I have:

<a class="button" href="{{ $cancelRoute }}">

The result in Whoops is a variable not defined error on $cancelRoute.

This is using Laravel 5.5. Documentation I referenced: https://laravel.com/docs/5.5/blade#including-sub-views

23rd August, 2017

thc1967 left a reply on TDD Forum Lesson 29: Vue Component Not Displaying • 3 months ago

Well, I'm certain the Vue component gets loaded as a Vue component else it wouldn't show up in the Vue debug tool in the browser.

And wth... apparently my classes are not correct. Thanks for bringing me back around to the obvious. :)

thc1967 started a new conversation TDD Forum Lesson 29: Vue Component Not Displaying • 3 months ago

I've actually used Vue pretty successfully so far, but for some reason at the first point in Lesson 29 that we build the site with the Vue component, it is not displaying in my page.

Flash.vue

<template>
    <div class="alert alert-success fade show" role="alert">
      <strong>Success!</strong> {{ body }}
    </div>
</template>

<script>
    export default {
        data() {
            return {
                body: 'You forgot to set body'
            }
        }
    }
</script>

app.js

require('./bootstrap');

window.Vue = require('vue');


Vue.component('flash', require('./components/Flash.vue'));

const app = new Vue({
    el: '#app'
});

What it does in my browser (Chrome on Windows 10) is... no display. Console shows no errors. Vue toolkit shows that the Vue object is there and has the data I expect. When I hover the component in the Chrome Vue utility, it highlights where it should be on the web page, but it simply does not display at all.

What did I miss?

17th August, 2017

thc1967 started a new conversation Kind Of A Gross Functional Test. How To Improve It, Maybe? • 3 months ago

GIVEN that we have a Character with a Type that has a Might pool value and a Descriptor that has a Might bonus value WHEN we run that character through the calculation rules for rendering THEN the Character's Might will be calculated accurately

    public function it_calculates_might_accurately()
    {
        $this->signIn();

        $stat = Stat::findOrFail(Stat::MIGHT);
        $type = create(Type::class);
        $type->stats()->save($stat);
        $type->stats[0]->pivot->pool = 10;
        $type->save();

        $descriptor = create(Descriptor::class);
        $descriptor->stats()->save($stat);
        $descriptor->stats[0]->pivot->bonus = 2;
        $descriptor->save();

        $characterModel = new ModelCharacter();
        $characterModel->type()->associate($type);
        $characterModel->descriptor()->associate($descriptor);

        $characterRender = new RenderCharacter($characterModel);

        $this->assertEquals(12, $characterRender->stats[Stat::MIGHT]->pool);
    }

Laravel 5.5. The only thing I seed into the database for my tests is the core rule stats.

I probably don't need the signIn() since I'm never saving the character.

14th August, 2017

thc1967 left a reply on What Are You Working On ? • 3 months ago

I'm toying with a few.

I recently rewrote my wife's main web site using Laravel. I need to get around to her secondary site after October.

I've been up & down writing / re-writing a defect tracking application for the company I work for as I try to learn Laravel and Vue better. I think in the end, this one is a waste of time. I mean, our current system is homebrew, ancient, and craptastic. We're not going to buy one, so that's out. But our IT manager hates Linux with a passion so he'll never deploy what I write either. (Maybe if I can figure out how to do scheduled events on Windows...)

Finally, I'm working on a character generation and management web app for a table-top RPG that I enjoy playing. This one is a huge learning experience because of all the weird one-off rules embedded in otherwise neatly aligned design. This one is probably a dead-end, too, because I doubt the publisher will be interested in a partnership where I do all the work and they take a portion of the profit.

11th August, 2017

thc1967 left a reply on Best Practice For Controllers • 4 months ago

I would probably use method #2 simply because I like to stick to the HTTP action verb method names. Plus it's more familiar for me to control with policies / gates.

I'm relatively new to this though so don't take that as a great answer. I'm interested to see what more experienced developers than I have to say.

4th August, 2017

thc1967 left a reply on Eloquent Get All And Count • 4 months ago

Your controller confuses me. You're running a query in the for loop but not doing anything with the results. Since $send is the iterator on the loop, I suspect it would be null by the time you pass it to the view.

If you're a subscriber here, there is a video maybe 25% of the way through (as of this writing) the TDD Forum series that shows you how to return a count of a related relationship when you load values into a model. I think that could work for you. If you implemented it, your controller code could be 2 lines - get the result list and return the view.

Look for the video that covers addGlobalScope().

3rd August, 2017

thc1967 left a reply on Question About Paypal Express Checkout, Braintree, And Stripe. • 4 months ago

You should use the one your customers will favor. Assuming you can't offer options, that is. Plenty of sites use an "internal" (seems like Stripe) processor and offer a PayPal option.

I hate PayPal with the searing fire of 10,000 suns... but that's what I use on my wife's sites because that's what her customers are far and away most comfortable with.

30th July, 2017

thc1967 left a reply on What Kind Of Web Hosting I Would Need To Deploy Laravel And Php Websites ? • 4 months ago

Others have suggested you can't use shared hosting. You can, but you need the right one. The main things you need are the minimum requirements (PHP version, database, etc.). It's helpful to be able to set the home directory for each site you host. I have Laravel sites hosted on shared hosting and it works.

However, it's probably much easier for you to use a cloud-based server and provision it and deploy your software with Forge. Add Envoyer if zero downtime is a requirement.

26th July, 2017

thc1967 left a reply on Relationship Help - Coach -> Teams -> Players • 4 months ago

You haven't established a direct relationship between coaches and players. You have to go through teams. Think more along the lines of:

$players = coach->teams->players;

(May not be exactly syntactically correct.)

22nd July, 2017

thc1967 started a new conversation Compiling Promises For IE11 • 4 months ago

I'm stuck. Need help.

I'm using Laravel 5.4, Vue, and Axios. In my Vue components, I use Axios to make Ajax calls, and those calls use Promises.

I believe there's a way to compile that all down using mix (or elixir?) so that the Promise constructs are smushed down into a script that IE11 supports, but I can't figure out how to do it.

I'd appreciate advice, point me to lessons here, point me to tutorials on the internet, whatever.

Here's an example of my use of Promises in Axios within a Vue component (this function dynamically loads a Vueified SELECT):

        loadList(uri) {
            // Cache the current value so we can put it back
            // after loading the list.
            this.isLoading = true;
            var cacheValue = this.myValue;
            axios.get(uri)
                .then( (response) => {
                    this.list = this.transformList(response.data);
                    this.myValue = cacheValue;
                    if (!this.myValue && this.initialValue) {
                        this.myValue = this.initialValue;
                    }
                    this.isLoading = false;
                })
                .catch( (error) => {
                    this.list = [];
                    this.isLoading = false;
                });
        },

Here's my app.js that loads my Vue components:

require('./bootstrap');

require('sweetalert');

window.Vue = require('vue');

// Third-party components
Vue.component('vue-draggable', require('vuedraggable'));
Vue.component('date-picker', require('vuejs-datepicker'));

// My components
Vue.component('active-tabs', require('./components/ActiveTabs.vue'));
Vue.component('pagination', require('./components/Pagination.vue'));
Vue.component('paginated-table', require('./components/PaginatedTable.vue'));
Vue.component('notification', require('./components/Notification.vue'));
Vue.component('data-select', require('./components/DataSelect.vue'));
Vue.component('sort-dialog', require('./components/SortDialog.vue'));

Finally, here's my webpack.mix.js that compiles everything down:

mix.js('resources/assets/js/app.js', 'public/js')
   .js('resources/assets/js/zxcvbn.js', 'public/js')
   .js('resources/assets/js/cleave.js', 'public/js')
   .js('resources/assets/js/vuemain.js', 'public/js')
   .js('resources/assets/js/vuecrud.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   //TODO: .version()
   ;

21st July, 2017

thc1967 left a reply on Database Structure Advice • 4 months ago

Cardinality is the number of unique values in a column. Typically a database engine will use an index on a column only if the cardinality is advantageous to it. The general rule of thumb is that if any one value in the column comprises more than about 7% of the table's inventory, it won't use the index. This does vary by database engine and other factors.

However, given a column with a cardinality of 2, you're guaranteed that at least one of the values has way over 7% of the inventory of the table, so you probably will not use an index on that column.

A showplan is a tool in the database engine that lets you evaluate the plan the database engine generates to resolve a query. Among other statistics and information, it will show you the index or indices the database engine will use to resolve a query.

thc1967 left a reply on Database Structure Advice • 4 months ago

It seems unlikely that your database would leverage an index on a column that has a cardinality of 2. Might want to showplan that to see if you're wasting space there.

10th July, 2017

thc1967 left a reply on Load A Laravel App In An Apache Server • 5 months ago

I found that same link on StackOverflow and promptly ignored it.

Does your hosting provider let you change the default root for a web site? I discovered that mine does, right through CPanel. I dropped my Laravel app in just like it was and pointed the document root to /myapp/public.

You should also check if the host offers SSH access. Mine does but I had to ask for it. This will let you do the command-line things.

If your host doesn't offer either of those, you might consider changing hosts. Depending on your capabilities and scope of the site, it might be worthwhile to consider a cloud host so you have complete control over the box, rather than a shared host where you have minimal control over the box.

thc1967 left a reply on Laravel Training • 5 months ago

Not sure if a 7 page troll, but...

My first exposure to Laravel was when it first came out. Version one point oh. That thing... I could not understand that thing. I had been a developer for a good 20 years by that point. I understood the MVC pattern. I had a reasonable handle on PHP. But... just... nope. Brain couldn't hack it.

Next opportunity I had to explore Laravel again was after 5.4 came out. Holy night and day, Batman! Laravel 5.4 is awesome!

And I found the FREE up-to-speed on Laravel 5.4 course that Laracasts offers to be such a boon that I ordered the T-shirt. (And it's a really nice t-shirt!)

I'm normally not a visual / video learner. So I fired up my trusty dusty Apache server with some PHP and MySQL and I followed along with Jeffrey through that course. I paused him every once in a while and wandered off into the weeds on my own. It worked out pretty well, with Jeffrey building block after block and me figuring out how Laravel really worked and what its capabilities and boundaries are.

As to, "Why Laravel?", well, your employer dictated it. The, "Why?" is to remain gainfully employed, assuming you want to do that with this particular employer.

Others have chimed in with other reasons, too. It's nice not to have to worry about the rote framework crap when I code. It's nice to have the MVC structure in place for me to extend. It's nice to write one line of code to establish a relationship between two objects that "just works" everywhere I want to use it. It's actually kind of a fun framework to use, and I wish I could use it at my job full-time.

And that's kind of the kicker there. The Laravel team is writing the framework not only that they WANT to use, but that they DO use every single day. I look at that sort of like I look at computer games. My favorite games are the ones that are written by programmers because they want to play the games, not (just) because they're getting a paycheck. That's how I view the team that produces this particular framework, and it makes all the difference in the world.

Another answer to, "Why Laravel?" can be found in Matt Stauffer's book, "Laravel Up and Running". The free sample is the chapter titled, surprisingly enough, "Why Laravel?" Read it here: https://laravelupandrunning.com/

7th July, 2017

thc1967 left a reply on Struggling To Understand The Concepts Of Laravel And Frameworks, Can You Help? • 5 months ago

Why use a framework?

I've worked in the software industry for almost 30 years, first as a developer and now as a project manager. I've really grown to appreciate Laravel and Lumen.

Good frameworks like Laravel are a jump-start to development. They offer great value by doing things for you so you don't have to code it yourself. If their developers are active, they constantly grow and expand and improve.

They do come with some trade-offs. There's a learning curve. They usually offer a certain way to do things, and if you want to take advantage of the benefits they offer, you need to stick roughly to the agenda. They may not be perfectly optimized for performance for your application.

But when it comes right down to, "What do I want to develop using?", I pull Laravel and Lumen out of the toolkit to launch some projects.

My company develops enterprise application software for which we frequently need to create custom web service hooks into client line of business systems. I can whip up a test harness for those web services in a matter of hours, or a day for something relatively big and complicated, using Lumen. Write that from scratch? Never going to happen.

I also manage a couple of web sites for my wife's business. I recently rewrote one of them in under 4 hours using Laravel. The last rewrite before that one took weeks.

I'm not a professional PHP developer. Never have been. It was always C, C++, VB (shudder), and Java. But when the time for semi-retirement comes, I'm looking forward to being a part-time, work-from-home PHP developer and leveraging the hell out of Laravel to stay competitive with the young whippersnappers.

30th June, 2017

thc1967 left a reply on Building A History Of Data Changes • 5 months ago

I would prefer to manage the record as a whole instead of creating the equivalent of a row per field. If I have new and old together, I can show them side-by-side and do cool things like filter to only populated values or only changed values.

I don't think I'll be high enough volume that I need to worry about purging or storage. The system that I'm replacing has been in place for over 15 years, it tracks history as 1 record per 1 field change, and it has under 500,000 records in its history table.

So let's change the question...

If I have a JSON representation of an Eloquent model inside a field in a table, how would I reconstitute that into the right Eloquent model object in PHP / Laravel? I feel like I should be looking into how polymorphic relations work...

thc1967 started a new conversation Building A History Of Data Changes • 5 months ago

I'd like to build a history feature into my application such that when a user updates one of my objects / records, I track that as an event that also stores the original values on the object and the updated values on the object.

I'd like to be able to come back around to look at that using the objects themselves, so I think that means I would need to store the data in a way I can read it back.

I'd like to do this without too much variance from the way Laravel and Eloquent manage the Model - Table relationship, so I think that precludes doing something like storing multiple copies of the record in the model's table.

I thought about creating a history table of sorts and storing the pre-edit and post-edit versions of the Eloquent model object as JSON (or something else?) in two different fields, creating a new record each time there was an update. I got about that far and thought it would be cool to do that but I couldn't figure out how to reconstitute an Eloquent Model object from JSON sitting in a record in a table.

What techniques have you guys used to do this with Laravel?

Thanks!

19th June, 2017

thc1967 left a reply on Defining A Relationship For A Report Card System • 5 months ago

If you only care about grades for the intersection of students and subjects, you can put the grade on the student_subject pivot table.

If you have marking periods, it gets a bit more complicated.

18th June, 2017

thc1967 started a new conversation This.$emit() Gets Delayed, Overridden • 5 months ago

I've written a Vue component that encapsulates an HTML SELECT control and knows how to read information from a URL.

Within that component's JavaScript, I have a loadList() method that takes a URL.

Within that method, the first thing I do is this.$emit('update:loading', true); to set a value that is synched. The last thing I do is the reverse of that: this.$emit('update:loading', false);.

It seems that Vue isn't actually emitting the value, or my receiving code isn't processing it, until the entirety of the loadList() method processes. I say this because when I comment out the last line in the method, the page behaves as if loading = true, which would only have happened if the first line in the method ran successfully.

Here's my loadList() method:

loadList(uri) {
    // Cache the current value so we can put it back
    // after loading the list.
    this.$emit('update:loading', true);
    var cacheValue = this.myValue;
    axios.get(uri)
        .then( (response) => {
            this.list = this.transformList(response.data);
            this.myValue = cacheValue;
            if (!this.myValue && this.initialValue) {
                this.myValue = this.initialValue;
            }
        })
        .catch( (error) => {
            this.list = [];
        });
    this.$emit('update:loading', false);
},

I would think the axios function is asynchronous. In fact, I've added a PHP sleep() method call into the URL this is calling so it takes at least 5 seconds to return.

The only time the parent - the code catching the value of the loading variable - changes is when I comment out the last line. It's as if the value is set to true then false immediately.

15th June, 2017

thc1967 left a reply on Proper Way To Deploy A Laravel Application From A Repo On Github • 5 months ago

If I were using a hosted server like Digital Ocean, I'd probably take a look at Envoyer (http://envoyer.io).

Without seeing the specific error messages you're getting, it's tough to help you with specifics.

Are you sure everything you expected to see in your vendor folder is there? If you just run php artisan, does it dump commands or error out?

12th June, 2017

thc1967 left a reply on Do You All Use Vue ? Or Still With Jquery Or Mix Between • 6 months ago

It depends.

If I'm building a site with Bootstrap, I use JQuery because it's already required. I just did that, in fact, when I re-wrote one of my wife's web sites in Laravel + Bootstrap4 in a day.

On the other hand, if I'm not using Bootstrap, as I am with another project where I'm using Bulma for the UI, I use Vue.

As @topvillas mentioned, I use Axios for AJAX when using Vue.

11th June, 2017

thc1967 left a reply on Envoyer Without Forge • 6 months ago

It's actually more expensive to run on a VPS / Cloud Server, but only because I don't need that much power for the sites I'm serving and because I'd probably need something like Forge to provision the servers if I did that.

Forge + Envoyer + the cheapest Cloud box I can find is $35/month. Even without Envoyer, which is the one thing I really like, it's $25/month. I'm under $10/month on a shared host.

I can't sudo, so I can't use Envoyer, but the host I'm with is awesome about keeping modern software on the boxes and I'm super happy with the email service.

thc1967 left a reply on Envoyer Without Sudo • 6 months ago

I could fake it and implement my own custom step if I knew what the sudo was trying to do. That doesn't seem evident though.

I'm guessing whatever Envoyer is trying to do with sudo, it could do without it. Sudo feels like a shortcut.

I've deployed the site manually, cancelled my Envoyer account, and emailed Taylor to see if anything can be done to work around it.

Thanks for the confirmation.

thc1967 left a reply on Envoyer Without Forge • 6 months ago

Thanks for the response. I tried Envoyer, but it doesn't work on a shared host because it requires sudo. (You replied on that query, too, thanks.)

Ah well. Neat concept. Unfortunate implementation.

For the moment, I've deployed the site manually.

thc1967 started a new conversation Envoyer Without Sudo • 6 months ago

So I've bitten the bullet and tried Envoyer to deploy... to my server that's a hosted server and not just a processor that I had to build.

Deployment gets to the point that it runs "Activate New Release", then it errors out because, no sudo. It's a hosted box. I don't get to be super-user.

stdin: is not a tty
Linux Detected...
Release Activated (20170611154953)!
PHP-FPM Detected: Reloading
bash: line 19: sudo: command not found

Anyone know if there's a way to work around not having sudo, or am I cancelling my Envoyer account?

Thanks!

10th June, 2017

thc1967 started a new conversation Envoyer Without Forge • 6 months ago

So I have an ISP that has plenty of goodies on the box for me and I'm quite adept at managing that server back-end. I've managed servers and sites running a variety of PHP applications for years. Therefore, I don't think I need the capabilities of Forge.

However, I'm intrigued by the capabilities of Envoyer. It seems like once I have a server configured, Envoyer should streamline the (Laravel) application deployment process. I've watched the Envoyer videos here at least twice each and, if I were using Forge, I'd feel pretty comfortable...

...but I'm not using Forge. I can't imagine a reason I'd drop $20 a month on that. $10 a month for Envoyer? In a heartbeat, probably, after doing some more due diligence.

I've searched the Internet in a variety of ways to find any documentation at all about "Envoyer Without Forge" but nothing comes up.

So I'll ask the community: Have you tried Envoyer on a server that's not a Forge server? If so, how did it work out for you? Any issues I should be aware of? How different is the process from the Envoyer videos here?

Thanks!

26th May, 2017

thc1967 left a reply on Custom Validator Not Firing • 6 months ago

And it was the way I was building the $validations array. Too deep. Bad PHP.

thc1967 left a reply on Custom Validator Not Firing • 6 months ago

I think it's actually worse than that. $this->validate() in this particular controller class doesn't ever actually do anything, even if I strip the validations array back to only stock Laravel validations.

Completely different problem. :(

thc1967 left a reply on Custom Validator Not Firing • 6 months ago

I'm not calling validatePwdForUser. The $this->validate() in the controller should do that for me based on the validation array I pass it.

I'd not terribly worried about the logic and bcrypt() calls right now. My main concern is why the validator doesn't seem to be firing.

As I mentioned, I have other controller classes that use other methods on the same validator class and they fire. I can't figure out why they're not firing for this one controller class, or perhaps for these two specific methods.

thc1967 started a new conversation Custom Validator Not Firing • 6 months ago

I'm trying to use a custom validator on a user profile page that manages a password change. The validator doesn't seem to be getting called.

This is not the only custom validator in the solution. I have a few others and those are all called as I expect them to be.

If there's a better way to validate the current user's password on a password change, I'll be happy to hear about it. As it is, here's what I'm doing...

I created a custom validator class called ExtendedValidator.php. Into that, I've placed a few new functions. The one that isn't being called is coded as follows:

    public function validatePwdForUser($attribute, $value, $parameters)
    {
        $this->requireParameterCount(1, $parameters, 'pwd_for_user');

        $userId = array_shift($parameters);

        $where[] = [
            ['id', '=', $userId],
            ['password', '=', bcrypt($value)]
        ];

        dd($where);
        return (1 == Users::where($where)->count());
    }

When I put a dd($parpmeters) as the first line in that method, it never dies and dumps. This tells me that the method is never getting called.

I think my controller should call that method because in the controller, I have the following code:

    public function update(Request $request, Profile $profile)
    {
        $authUser = Auth::user();
        $hasPassword = (strlen($request->input('new_password')) > 0);

        $validations = [];

        if ($hasPassword) {
            $validations [] = [
                'password' => 'required|pwd_for_user:' . $authUser->id,
                'new_password' => 'required|confirmed|min:6|password_complexity:2,ipd,ultera,helpdesk'
            ];
        }

        $this->validate($request, $validations);

When I put a dd($validations) right before the $this->validate() call, it dumps the 2 validations I expect to see. The second one should call my custom validation method.

In my AppServiceProvider.php file, I reference my custom validator class:

    public function boot()
    {
        Validator::resolver(
            function($translator, $data, $rules, $messages, $customAttributes) {
                return new ExtendedValidator($translator, $data, $rules, $messages, $customAttributes);
            }
        );

What have I done wrong?

Thanks!

17th May, 2017

thc1967 left a reply on Auth::attempt() Fails If There Are Multiple Rows Of Same Username With Different Password. • 6 months ago

From a logical perspective, this enables users to have multiple passwords. Is that what you really wanted to do?

If so, it may be better to model it in a separate, one-to-many passwords table. You'll still need to implement your own custom login, but that's a better model than multiple records in the users table.

If multiple passwords per user was not your intent, you need to rethink why you even had to ask this question.

Edit Your Profile
Update

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