lindstrom

lindstrom

Member Since 5 Years Ago

Jacksonville, FL

VP of Engineering at AI

Experience Points 60,175
Experience Level 13

4,825 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 538
Lessons
Completed
Best Reply Awards 45
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

11 Jun
2 weeks ago

lindstrom left a reply on Horizon/Redis - Multiple Server Setup?

Faced with the same problem, this issue really drove our selection of cloud provider. We built a VPC on AWS with multiple, load balanced application servers connected to a clustered ElastiCache Redis. Without knowing more about your workloads and your requirements for reliability, I can't really opine further other than to say you don't horizontally scale with multiple, independent nodes. You need a single node you run on a dedicated instance or a managed solution like ElastiCache.

I wouldn't run your Redis on one of your app servers. While running your own Redis instance means you can defer and control the timing of maintenance, you'll have a failure or need to upgrade software or etc. Then you'll have to consider the data in your cache. Do you need to migrate it? Using a managed service like ElastiCache eliminates those issues, but doesn't free you from having some maintenance down time. We tested with a single Redis instance but found out that availability can be affected by the periodic maintenance AWS does. We have a critical path where we can't accept minutes-long interruptions so we run in clustered mode. They also recently improved availability when in clustered mode to allow writes to continue while maintenance is occurring. That said, during our test period of 8 months, we only had one maintenance event that made Redis unavailable for nearly 10 minutes.

You may have no other choice for hosting/hardware, but if you do consider AWS, they have a ton of reference material. Let me know if I can be more specific about anything.

22 Apr
2 months ago

lindstrom left a reply on App.css Reverting Back

Just my guess as to what you were doing, but yes. You edit your app.scss and with each change a new app.css is output. Your webpack.mix.js ought to have a line like this:

mix.sass('assets/sass/app.scss', 'public/css')

Edit the app.scsss and not the emitted app.css.

20 Apr
2 months ago

lindstrom left a reply on App.css Reverting Back

What's your webpack.mix.js file look like? Are you inadvertently editing the emitted app.css file instead of app.scss?

03 Apr
2 months ago

lindstrom left a reply on How To Create Timestamp From Date

@BOLDSTAR - Glad you figured it out. But, it still doesn't answer the question of why you are converting it to a timestamp because if you are using created_at, it's going to get cast to Carbon when you save it. Try it in Tinker (php artisan tinker) if you aren't convinced:

// From Tinker

>>> $user = User::find(1);
=> App\Models\User {#3602
     id: 1,
     first_name: "Shawn",
     last_name: "Lindstrom",
     email: "[email protected]com",
     username: "slindstrom",
     created_at: "2019-04-02 03:28:51",
     updated_at: "2019-04-02 03:28:51",
   }
>>> $user->created_at = \Carbon\Carbon::now()->timestamp;
// Here we see that created_at is set to the current timestamp
=> 1554316597
>>> $user->save();
=> true
// But, after we save the model and retrieve created_at we see that it's a Carbon instance because it was cast to Carbon when we saved it
>>> $user->created_at
=> Illuminate\Support\Carbon @1554175732 {#3570
     date: 2019-04-02 03:28:52.0 UTC (+00:00),
   }
// Now, if we actually want a timestamp we have to call the timestamp method
>>> $user->created_at->timestamp
=> 1554316597

lindstrom left a reply on How To Create Timestamp From Date

Assuming you want to use the date you pass and don't want to simply use now(), you can:

YourModel::where('id, $someId)->update([
    'created_at' => Carbon::parse($request->date),
]);

The created_at field is already cast to Carbon so you can save the Carbon instance directly--no formatting required.

02 Apr
2 months ago

lindstrom left a reply on How To Use DB Facade With Helper

@LUDO1960 - TMYK. I personally don't use Mongo sooooo, yes your strategy is foiled, but not your plan. Since you can't create a new _id by incrmenting, why not just do an insert and return the newly inserted id? Like so:

function get_next( $role_id )
{
    return DB::collection('counter')
        ->insertGetId(['name' => $role_id]);
}

lindstrom left a reply on Increase Year Range In Drop Down

@MARLONV - Thanks! Noticed an issue -- going back to edit that you need to cast the return to a string or the strict comparison in blade won't work.

lindstrom left a reply on How To Use DB Facade With Helper

@LUDO1960 - Your helpers are part of the global namespace. Your helper file(s) do not need a namespace declaration. In your last post you are trying to include them in a class. None of this will solve the underlying issue of the function not doing what you expect. And, there you were right--you're not calling it correctly because you are passing an array as your argument and then not accessing its value by its index.

// Instead of this:
$db_array = get_next(['name' => 'role_id]);

// Do this:

$db_array = get_next('role_id');

However, if you want/need to pass an array as your argument to get_next(), you have to access it by index in your helper:

// If you call it like this:
$db_array = get_next(['name' => 'role_id']);

// You'll need to access role_id like this:

    function get_next( $name )
    {
        DB::table('counter')
            ->where('name', $name['role_id'] )->increment('_id');

        return DB::collection('counter')->where('name', $name['role_id'])->first();
    }

If you don't need to pass an array as an argument, simply passing the value (role_id) to get_next will work with your helper:

// Call like this:
$db_array = get_next('role_id');

// But maybe change your parameter name and do this:
    function get_next( $role_id )
    {
        DB::table('counter')
            ->where('name', $role_id )->increment('_id');

        return DB::collection('counter')->where('name', $role_id)->first();
    }

HTH!

lindstrom left a reply on Increase Year Range In Drop Down

Expose less logic in your template. Do the work or getting your years in your controller or if you use that dropdown all over the place, put it in a birth_years() helper. Making some assumptions about what you are testing against for edit (a $user you have passed to the view);

// SomeController or some helper

$high = date('Y') - 5;
$low = date('Y') - 12;

$birth_years = [];

foreach (range($low, $high) as $year) {
    $birth_years[] = (string) $year;
}
// Some Blade template

<select id="year" class="birth_day" name="year">
    <option value="">Year</option>
    @foreach($birth_years as $birth_year)
    <option 
        value="{{ $year }}"
        @if ($user->birth_dt->format('Y') === $year) selected @endif
    ></option>{{ $year }}</option>
</select>

lindstrom left a reply on Know Each Other...

I use it for web dev at work. At home, I use it to enrage all the Grails/Flask/Rails devs in my life who think they have it better than we do. ?

lindstrom left a reply on Array Sum

So $request->stockid is an array of stock id's? Once you have built up your array, just collect and sum the array:

$stocks = [
    [
        'id' => 1,
        'kg' => 10,
    ],
    [
        'id' => 2,
        'kg' => 20,
    ],
    [
        'id' => 3,
        'kg' => 30,
    ],
];

$total_kg = collect($stocks)->sum('kg');

See: https://implode.io/ajr9a1

Alternatively, if you don't need to build up the array with other values and, again, that $request->stockid is an array of stock id's:

$total_kg = Stock::whereIn('id', $request->stockid)->sum('kg');

lindstrom left a reply on Can Anyone Correct My Blade Syntax For Window.location='' Location?

See last for a blind stab at how to do this using Laravel Collective Forms. I'd suggest abandoning its use though--not even form-model binding is worth trying to remember the syntax.

Just want to go back?

<button type="button" onClick="event.preventDefault(); window.history.back()">Go Back</button>

Have a specific destination?

<button type="button" onClick="event.preventDefault(); window.location = '{{ url('your/url') }}';">Go someplace specific</button>

But, really, use route names for the above so you can:

<button type="button" onClick="event.preventDefault(); window.location = '{{ route('somewhere.else') }}';">Go someplace specific</button>

If you have to use the Forms stuff, this might work or get your closer:

{!! Form::button('Back', null, null, ['type' => 'button', 'class' => 'btn_back', 'onClick' => "window.location = '{{ url('/') }}';"]) !!}
01 Apr
2 months ago

lindstrom left a reply on Array Sum

Might as well get straight to the point:

$total_kg = Stock::where('foo', 'bar')->sum('kg');
21 Mar
3 months ago

lindstrom left a reply on Dusk: Two Tests Not Working Together, But Individually.

Just getting into Dusk myself and had this problem. Logging out didn't work for me, because I was setting remember to true. I ended up having to delete the session cookie in each of my tests.

    $this->browse( function(Browser $browser) {
        $browser->visit(route('login')
            ->type('username', 'someusername')
            -> type('password', 'somepassword')
            ->click('@login-button')
            ->assertPathIs('/account')
            ->deleteCookie('app_session_cookie');
    });

Alternatively, and I haven't tried this, you may be able to uncheck remember and also call logout after your path assertion.

Just in case anyone finding this is unsure/new -- the session cookie is defined in config/session.php and either uses the APP_NAME concatenated with _session (e.g. you_app_name_session) or the default (laravel_session).

27 Feb
3 months ago

lindstrom left a reply on Method Not Allowed When Delete Record In Laravel

Unless it's a typo, you aren't enclosing the URL in the quotes on action. Change:

<form action=""{{url('product/destroy/'.$product->id)}} method="post">

To:

<form action="{{url('product/destroy/'.$product->id)}}" method="post">

You are posting to "".

07 Nov
7 months ago

lindstrom left a reply on Controllers

Once you have a handle on the 7 rest actions and get a bit more comfortable, you'll find this talk super useful: https://streamacon.com/video/laracon-us-2017/day-1-adam-wathan

26 Sep
8 months ago

lindstrom left a reply on Vue Default Selection For Select

@burlresearch Ooo, thanks so much for the example! I'm going to go give vue-select another go right now.

25 Sep
9 months ago

lindstrom left a reply on Vue Default Selection For Select

Hey, @dextercampos, thanks for responding! You're right, what I had was totally wrong and I could see that clearly when I looked again in devtools.

However, I do have to bind form.company_id or it won't get passed to the form object for submission. Here's where I ended up which actually does work and seems much more reasonable:

<template>
// form fields
    <select v-model="form.company_id" 
                  name="company_id">
        <option v-for="company in companies"
                        :value="company.id"
            :selected="selected" // Vue will make the option selected if the bound value matches the selected value.
                        v-text="company.name"></option>
    </select>
// more fields
</template>

<script>
    export default {
        props: ['companies'],
        data() {
            return {
                form: new Form({
            company_id: '1', // this will change when a new value is selected
                    name: '',
                    display_name: '',
                    phone: '',
                }),
                selected: '1' // initial value. This WILL NOT change when a diff value is selected which is fine
            }
        },
// methods etc
}
</script>

I think I tried to use a conditional or something dumb when I bound :selected without thinking that, of course, Vue is smart enough to do that for me. I legit couldn't find any good examples of how to do the above.

@burlresearch, I think vue-select would be ideal, but (IIRC) I had CSS issues when I tried it for a multiselect. I'm fine with wiring it up myself although multiselect with a search/lookup and tags (like select2/vue-select) may be more than I want to bite off right now. Guessing that most folks are using one of the two plugins you mention because there isn't very much out there about doing this kind of stuff. If you have anything else relevant, I'd love to have a look!

18 Sep
9 months ago

lindstrom started a new conversation Vue Default Selection For Select

Getting my feet wet with Vue and I'm looking for validation of my implementation of selecting a default value for a select input.

I have a component with a simple form. I pass company data to it for use in populating select options. This works and is (approximately) what I have:

<create-account :company="{{ $companies->toJson() }}"></create-account>

Inside the component:

<template>
// form fields
    // is binding data like what follows kosher?
    <select v-model="form.company_id, selected" 
                  name="company_id">
        <option v-for="company in companies"
                        :value="company.id"
                        v-text="company.name"></option>
    </select>
// more fields
</template>

<script>
    export default {
        props: ['companies'],
        components: {
            FormSubmissionMessages
        },
        data() {
            return {
                form: new Form({
                    name: '',
                    display_name: '',
                    company_id: '1 ', // initial value
                    phone: '',
                }),
                selected: '1' // value of desired selection
            }
        },
// methods etc
}
</script>

Didn't really find anything to support this so I can only assume this is how it's done. Are there other, more "correct", ways to achieve the same thing? Thanks for any, ah hem, input!

06 Sep
9 months ago

lindstrom left a reply on Undefined Offset 0

If the box isn't checked the browser doesn't send the input, hence you get the undefined index error. Further, you defined your index as ['enabled' === 'on'] and not $input['enabled'] === 'on'.

Easiest solution is to do the following:

$game->enabled = isset($input['enabled']) ? 1 : 0;

Alternatively, you can add a hidden input of the same name right before your checkbox. When the browser passes the parameters, it will only send the last. So, if your box doesn't get checked, it will send the value of the hidden input. If it is checked, it will send the value of the checkbox.

In your form:

<input type="hidden" name="enabled" value="0">
<input type="checkbox" name="enabled" value="1">

The you can just assign it in your controller

$game->enabled = $input['enabled'];

Have fun!

09 Feb
1 year ago

lindstrom left a reply on Homestead - Wrong Time

The last 6.* release introduced this issue for me. Since 7 was out, I just rebuilt and the issue is gone.

31 Oct
1 year ago

lindstrom started a new conversation Thoughts On What To Return After Passing Invalid Input To Helper

I have a helper that wraps libphonenumber. The package throws a NumberParseException when it receives a number that isn't valid* for a given region. My inclination is to return the original value after catching the error. This is just one scenario, but I could see it applying to lots of formatting helpers. Since they are typically used for display, returning null or false isn't very useful IMO. The answer may be simply to be consistent.

What do you typically do?

Here's the method for illustration:

    private function formatNumber($value, $format, $region)
    {
        try {
            $phoneUtil = PhoneNumberUtil::getInstance();
            $phoneNumberObject = $phoneUtil->parse(
                preg_replace('/\D/', '', $value),
                $region
            );
        } catch (NumberParseException $e) {
            return $value;
        }

        return $this->{$format}($phoneUtil, $phoneNumberObject);
    }
  • Why not validate first? Two words, legacy data. The value could be virtually anything.
05 Oct
1 year ago

lindstrom left a reply on PHP Array Output

Super duper answermagic based on literal interpretation of question:

$i = 0;
echo '[';
foreach ($arrays as $v) {
    foreach ($v as $x) {
        echo '[' . $x . ']';
    }
    if ($i < count($arrays) -1) {
        echo ',';   
    }
    $i++;
}
echo ']';

In all seriousness, could you provide some more detail on what you are trying to accomplish? Where are you wanting to print your array formatted that way? For what purpose?

lindstrom left a reply on How To Return Back The Page After Saving Data??

Is it a regular post or an AJAX post (where perhaps you aren't doing e.preventDefault();)? I can help if it's jQuery, but would need to see your blade template and the applicable JS.

For example, if you don't actually want/need to submit the page:

$( "form" ).submit(function( e ) {
  e.preventDefault();
  // $.ajax stuff
});

Otherwise, any of the above methods should work fine.

17 Aug
1 year ago

lindstrom left a reply on Laravel Mix: Prevent Moment.js Locales

I have one page that requires fullcalendar which has moment as a dependency. I ended up copying moment.min.js directly to public/js rather than loading it through webpack. And, to be clear, I did the same with fullcalendar as well.

There's probably a "right way" to do this so you can bundle it, but ain't nobody got time for that.

16 May
2 years ago

lindstrom left a reply on Can We Get Exact Updated Field From The Update()

You can definitely check the retrieved field against some input to be updated before executing the update. However, you have to retrieve the model first.

For example:

$user = User::find(1):

if ($user->age !== $request->age) {
    $user->age = $request->age;
    $user->save;
    // the age was updated - do something
}

Note: models are not retrieved when doing a mass update.

If that's not what you are asking, could you please explain further?

04 Apr
2 years ago

lindstrom left a reply on Good Alternative To Var_dumpling Chrome Extension?

Not familiar with the extension. Could you just use dump() instead?

{{ dump($foo) }}
23 Mar
2 years ago

lindstrom left a reply on I Want To Know What Reason Behind It

You need to pass an array or collection to @foreach. You're giving it an integer. Try:

public function notification()
{
    $users = DB::table('users')->where('Active', 0)->get();
   

    return view('admin.layout.master', compact($users));
 }
27 Feb
2 years ago

lindstrom left a reply on About To Launch My First Real Web Application, What Do I Need To Keep In Mind?

Use a service like Sentry / Rollbar / Bugsnag or get ready to tail -f laravel.log when you go live. Stay calm, fix bugs as they crop up. Wipe hands on pants, repeat.

31 Jan
2 years ago

lindstrom left a reply on The Requested URL Could Not Be Retrieved

Looks like something to do with Vimeo. I can't watch or download Introducing Laravel Echo: https://laracasts.com/lessons/introducing-laravel-echo

@JeffreyWay any ideas? I also noticed that the Laravel Echo demo Github repo is gone for that video.

25 Jan
2 years ago

lindstrom left a reply on 5.3 With XAMPP

It's not a XAMPP issue. It's that if you precede the path with a "/" it will make the URL relative to the root of your project. Whereas if you don't prefix with "/", it will be relative to the current path.

For example, if you are at http://some.dev/directory

A link to:
<a href-"/upload">Upload</a>

Would resolve to:
http://some.dev/upload

A link to:
<a href="upload">Upload</a>

Would resolve to:
http://some.dev/directory/upload

If you are talking about something else, please provide an example.

In the future, you will find the url(), action() and route() helpers useful, but they are not necessary. Just get your paths and routes correct for now.

lindstrom left a reply on Laravel 5.4 Dev Npm Run Dev Error

@JeffreyWay

I found that codemirror appears to be an optional dependency of Summernote (jQuery and Bootstrap are it's only published deps: https://github.com/summernote/summernote).

With the same fresh install of L5.4.3.

bower install summernote

Edit webpack.mix.js

mix.copy('bower_components/summernote/dist/summernote.css', 'resources/assets/css/vendor/summernote');
mix.copy('bower_components/summernote/dist/summernote.min.js', 'resources/assets/js/vendor/summernote');

mix.js(['resources/assets/js/vendor/summernote/summernote.min.js', 'resources/assets/js/app.js'], 'public/js/app.js')
   .sass('resources/assets/sass/app.scss', 'public/css');

Run npm run dev results:

This dependency was not found in node_modules:

* codemirror

Did you forget to run npm install --save for it?
                                                                    Asset      Size  Chunks                    Chunk Names
  fonts/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1   20.1 kB          [emitted]
  fonts/glyphicons-halflings-regular.svg?89889688147bd7575d6327160d64e760    109 kB          [emitted]
  fonts/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512   45.4 kB          [emitted]
 fonts/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158   23.4 kB          [emitted]
fonts/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb     18 kB          [emitted]
                                                               /js/app.js   1.28 MB       0  [emitted]  [big]  app
                                                             /css/app.css    685 kB       0  [emitted]  [big]  app
                                                        mix-manifest.json  66 bytes          [emitted]
                 ../resources/assets/css/vendor/summernote/summernote.css   13.2 kB          [emitted]
               ../resources/assets/js/vendor/summernote/summernote.min.js   92.2 kB          [emitted]

npm ERR! Windows_NT 10.0.14393
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
npm ERR! node v7.4.0
npm ERR! npm  v4.0.5
npm ERR! code ELIFECYCLE
npm ERR! @ dev: `node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the @ dev script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.
// snip irrelevant

Here is the relevant seciton of summernote.js where it checks for codemirror:

  var hasCodeMirror = !!window.CodeMirror;
  if (!hasCodeMirror && isSupportAmd && typeof require !== 'undefined') {
    if (typeof require.resolve !== 'undefined') {
      try {
        // If CodeMirror can't be resolved, `require.resolve` will throw an
        // exception and `hasCodeMirror` won't be set to `true`.
        require.resolve('codemirror');
        hasCodeMirror = true;
      } catch (e) {
        // Do nothing.
      }
    } else if (typeof eval('require').specified !== 'undefined') {
      hasCodeMirror = eval('require').specified('codemirror');
    }
  }

Finally, from within the emitted app.js I the following which appears to have some relevance:

      CodeMirror;agent.hasCodeMirror && (agent.isSupportAmd ? Promise.resolve().then(function() { var __WEBPACK_AMD_REQUIRE_ARRAY__ = [!(function webpackMissingModule() { var e = new Error("Cannot find module \"codemirror\""); e.code = 'MODULE_NOT_FOUND'; throw e; }())]; (function (a) {
    CodeMirror = a;
  }.apply(null, __WEBPACK_AMD_REQUIRE_ARRAY__));}).catch(__webpack_require__.oe) : CodeMirror = window.CodeMirror);var Codeview = function Codeview(a) {

Let me know if I can offer anything else.

lindstrom left a reply on Laravel 5.4 Dev Npm Run Dev Error

@JeffreyWay No -- I don't have them in my package.json as they are not dependencies of my project. I think they're being derived as dependencies from some vendor files I have in there for my admin theme (ProUI). Looking at it again now.

lindstrom left a reply on Laravel 5.4 Dev Npm Run Dev Error

I rm -rf node_modules/ then npm install.

Using new package.json, and my webpack.mix.js, on Windows 10 with latest (7.4) nodejs I get the following when I npm run dev:

These dependencies were not found in node_modules:

* codemirror
* moment
* ../fonts/bootstrap/glyphicons-halflings-regular.eot
* ../fonts/bootstrap/glyphicons-halflings-regular.woff2
* ../fonts/bootstrap/glyphicons-halflings-regular.woff
* ../fonts/bootstrap/glyphicons-halflings-regular.ttf
* ../fonts/bootstrap/glyphicons-halflings-regular.svg

I do have another issue with a vendor js file where webpack is trying to resolve a relative directory within that file and can't, but that's not related.

24 Jan
2 years ago

lindstrom left a reply on 5.3 Redirect Action - Not Defined

Try:

return response()->redirectToAction('Pages\Member\Crew\[email protected]',
        [$npc]');

And in web.php (see: https://laravel.com/docs/5.3/routing#route-model-binding)

Route::get('/crewmember/{npc}', 'Pages\Member\Crew\[email protected]');

Finally in CrewController

public function member(NPC $npc)
{
    // no idea what you are trying to do here,
    // but this method needs to return your
    // crewMember view
    $tile = $npc->tile; 

    return view('crewMember', compact('tile');
}
03 Jan
2 years ago

lindstrom left a reply on Laravel 5.3 - Roles And Permissions Provider

I'm in the middle of this. I reviewed a few packages and decided to roll my own for my limited use case (roles only). However, I missed https://github.com/JosephSilber/bouncer and I'm going to look at it today. Can't recommend one way or another but thought I'd contribute it to the list.

28 Dec
2 years ago

lindstrom left a reply on External Monitor Tips

I'm with @SaeedPrez , I have a Dell XPS 15 and a 27" external at 1920x1080. I'd much prefer dual 27's at a higher resoluation or maybe a single 34". I basically have mirrored my setup in my home office to my work office. Same angles, monitor, mouse, keyboard, laptop stand. It might seem like a small thing, but I have zero config or window dragging (I'm on Windows) when switching from one location to the other. Having ConEmu on the Laptop and everything else on the external works, but some more real estate would be welcome. Plus, for my taste (and eyes), the laptop monitor is just a little bit too far away to be more useful.

19 Dec
2 years ago

lindstrom left a reply on Array_key_exists() Expects Parameter 2 To Be Array, Null Given In Serachable

@neogeninfotech Sweet! Yeah, that turns off full group by in MySQL which is on by default in MySQL 5.7. The default sql modes are pretty annoying so I just set sql_mode='' when I provision a new box (I have a Forge recipe I run and include it in my Homestead's after.sh).

Glad you got it working!

17 Dec
2 years ago

lindstrom left a reply on Multiple Seeders And Factories - Is It Possible?

  • 1 for checking the environment. Seeders are also a convenient place to do ETL. For example, I moved our current app from legacy to Laravel and am now updating the underlying architecture. I've built a number of seeders that will populate new tables with data from existing tables as well as populate a few reference tables. However, it's a one shot deal. I can't see a use case for reusing a seeder after it's been run in production (successfully).
16 Dec
2 years ago

lindstrom left a reply on Array_key_exists() Expects Parameter 2 To Be Array, Null Given In Serachable

Sorry @neogeninfotech I didn't add the table and priority. What happens when you write it like this:

protected $searchable = [
    'columns' => [
        'users.name' => 10,
    ],
];
15 Dec
2 years ago
13 Dec
2 years ago

lindstrom left a reply on Is It Just Me?

I remember those early days of hitting the space bar and alt-tabbing back and forth to code and follow along all too well. I think everyone new here has thought the same thing about the pacing. The thing is, just take your medicine and pause/tab back and forth and grind through those first few series. After that, go through Be Awesome in PhpStorm/Sublime. Get yourself a nice little sandbox set up for local dev. Get comfortable with creating new laravel projects. Abandon anything that rhymes with AMP for Homestead or Valet.

Trust me, one day you'll be watching a lesson and wondering what's taking him so long and you'll actually speed up the videos. The only way you'll remember what Jeffrey actually sounds like is to listen to the Snippets podcast... until you realize you have that on 1.5x too.

lindstrom left a reply on Want To Load Country List From Database Table In Blade

There are lots of ways to do this and unless I'm missing your intent, this is the simplest way:

public function edit(User $user)
{
    $user->load('country', 'prefecture');
    $countries = Country::select('id', 'name')->get();
      
        return view('users.edit', compact('user', 'countries'));
    }

Then of course you can loop over $countries in your view to build up a select or whatever.

Don't forget to import the Country class.

10 Dec
2 years ago
08 Dec
2 years ago

lindstrom left a reply on Stopping The Form From Refreshing, Jquery, Ajax And Laravel

I don't like client-side validation. You have to do it on the server anyway unless you're all #yolo.

$('#commnetForm').on('submit', function(e) {
    var form = $(this);
    $.ajax([
        url: form.prop('action'),
        data: form.serialize(),
        success: function (data) {
            // do some cool stuff like returning a rendered comment
            $('.comments').append(data);
            // OR just display a message
            $('#success').html(data);
            $('#formDiv').html('');
        },
        error: function (data) {
            // display the error (note: you have to work harder when there is
            // an array of errors returned
            var error = data.responseJSON;
            $('#formDiv').html('<span style="color:red;">' + error.body + 'A message</span>');
        }
    });
});

Either create a form request or validate in the controller method. Personally, I prefer a form request. Laravel will return the the JSON representation of the response with a status code of 422 automatically:

php artisan make:request CommentRequest

CommentRequest.php

public function authorize(
{
    return true;
}

public function rules()
{
    return [
        'body' => 'required|min:6',
    ];

Controller

<?php

namespace App\Http\Controllers;

use App\Http\Requests;

class CommentController
{
    public function store(CommentRequest $request)
    {
        // store the request
        $comment = Comment::create($request->all());

        // return rendered view as a string:
        return view('comment', compact('comment')->render();
        // or maybe just a success message
        return ressponse()->json([
                'success' => true,
                'msg' => 'Thanks for the comment!',
            ], 200);


    }
}

We could get more specific if I knew what you wanted to achieve in the view for success/failure cases.

06 Dec
2 years ago

lindstrom left a reply on (Javascript Error; Uncaught SyntaxError: Missing ) After Argument List)

Try:

<script type="text/javascript">
    $('#districs').on('change', function(e){
        e.preventDefault();
        var kec_id = $("input[name='kec_id']").val();
        console.log(kec_id);
        $.get('/ajax-vilObj = ' + kec_id, function(data){
            console.log(data);
        });
    });
</script>

lindstrom left a reply on (Javascript Error; Uncaught SyntaxError: Missing ) After Argument List)

You're missing a comma:

$('#districs').on('change', function () {
   // the rest is fine

Also, you probably mean to spell 'districs' as 'districts' but that is beside the point.

HTH!

04 Dec
2 years ago

lindstrom left a reply on HI, I Can't Seem To Get My Ajax Call Working

Based on your response, I'm guessing you just want to validate email when the input loses focus. You still have to deal with the idea someone could not fill it out at all. Server or JS or give the field focus on page load for that--your call. At any rate, you could do your ajax like this:

$("#regemail").on('keyup blur', function (e) {
    e.preventDefault();
    var email = $(this).serialize();
    $.ajax({
        type: form.prop('method'),
        url: form.prop('action'),
        data: email,
        success: function (data) {
            // success stuff
        },
        error: function (data) {
            var errors = data.responseJSON;
            var errorsHtml = '<div class="alert alert-danger animation-fadeInQuick"><ul class="list-unstyled">';
            $.each(errors, function (key, value) {
                $.each(value, function (key, value) {
                    errorsHtml += '<li><i class="fa fa-close"></i> ' + value + '</li>';
                });
            });
            errorsHtml += '</ul></div>';
            $('#errors').html(errorsHtml);
            $('#success').html('');
        }
    });
};

You can either do the validation directly in the controller or you can create a form request as I alluded to in my previous response. Since you have a dedicated controller method, I don't see anything wrong with::

public function checkUsername(Request $request)
{
    $this->validate($request, ['email' => 'required|unique:users']);
}

From the docs, we then know: "When using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code."

Finally, in your success: and error: functions you can target the message to an appropriate selector in your form.

03 Dec
2 years ago

lindstrom left a reply on HI, I Can't Seem To Get My Ajax Call Working

You're doing way too much in jQuery relative to validation. Do the validation in a form request . If validation fails, it will be returned as a json response with a 422 status code. See: https://laravel.com/docs/5.3/validation#form-request-validation

Loop over the errors in the response and display them to the user. You AJAX call might look something like:

$("#register-btn").on('submit', function(e) {
    e.preventDefault();
    var form = $(this).closest('form');
    $.ajax({
        type: form.prop('method'),
        url: form.prop('action'),
        data: form.serialize(),
        success: function(data) {
            // success stuff
        },
        error: function(data) {
            var errors = data.responseJSON;
            var errorsHtml = '<div class="alert alert-danger animation-fadeInQuick"><ul class="list-unstyled">';
        $.each(errors, function (key, value) {
            $.each(value, function(key, value) {
                errorsHtml += '<li><i class="fa fa-close"></i> ' + value + '</li>';
            });
        });
        errorsHtml += '</ul></div>';            
        $('#errors').html(errorsHtml);
        $('#success').html('');
        }
    });
};

Add a couple empty divs at the top to contain your success/errors. If you are going to render a different view on success don't need the success function or to clear previous errors with $('#success').html('');.

HTH!