dhermann

dhermann

Member Since 1 Year Ago

Experience Points 830
Experience
Level
Lessons Completed 0
Lessons
Completed
Best Reply Awards 0
Best Answer
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.

25 Oct
3 weeks ago

dhermann left a reply on Please Explain Dusk DatabaseMigrations Like I'm A Dummy

I agree @jlrdw, I was just using the migrations to sterilize the database, which seemed like a nice side effect of having them from my original migration process. Do you think a series of SQL truncate and insert statements would be better? How could I run such a file as part of a setUp() method call?

dhermann left a reply on Please Explain Dusk DatabaseMigrations Like I'm A Dummy

Thanks Doctor @Drfraker. Can you point to an example Factory class so I can make sure I'm doing this right before I set up all the data I need?

24 Oct
4 weeks ago

dhermann left a reply on Please Explain Dusk DatabaseMigrations Like I'm A Dummy

@jlrdw Thanks for replying, but this tutorial doesn't address the DatabaseMigrations trait inside Dusk at all.

dhermann started a new conversation Please Explain Dusk DatabaseMigrations Like I'm A Dummy

So my end goal is to have a single line of code ("php artisan dusk") that will wipe the current test database, execute all my database migrations to create the tables, run the seeds for test data, then run set of Dusk testcases in a specific order.

How can I use the DatabaseMigrations trait to handle this? I have a successful Dusk installation using the test database with a sandbox environment file, but I can't really tell what's happening on the database side.

dhermann left a reply on Wrapping Inherited View() Method In Controller.php

Wow! I had been trying to use View Composers (specifically, the View::composer() method for at least a week but I couldn't get the database call to execute only once, regardless of how many child views were rendered, but I think the View::share() method takes care of that. I will give it a spin! Thanks @lostdreamer_nl !

dhermann started a new conversation Wrapping Inherited View() Method In Controller.php

I'm sure I'm just forgetting a day from CS 101 but I'd like to intercept the view() call in my child controllers and add a parameter onto the array. This code doesn't work:

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    protected $year;

    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct() {
        $this->year = \App\Year::where('is_current', '1')->first();
    }

    public function __view($view, $params) {
        return parent::view($view, array_push($params, $this->year));
    }
}

Is this possible? Am I using the right notation? Do I need a trait or something else?

19 Oct
1 month ago

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

@tykus Yep, that's what I was trying to refactor away from. I'll just revert to an @inject directive on every view.

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

@tykus I have over 30 views for this site, plus I'd end up having to pass it into all the child views anyway. It doesn't seem worth it.

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

A good idea @tykus but I still hit the same problem with child views either a) not having access due to scope or b) running the composer more than once, defeating the purpose of the optimization. I'm beginning to think composers were just not meant to house database calls.

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

Wait, @include has to be a named view. That won't work.

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

Aha, that's it @tykus . Is there a way to pass it into the yielded views or do I need to change the @yield to @include directives and pass in the data manually?

dhermann left a reply on View Composer Data Not Available When Assigned To Layout

Yes.

@extends('layouts.app')

@section('title')
    Camp Cost Calculator
@endsection

@section('heading')
    Use this tool to easily estimate the cost of your fees for {{ $year->year }}.
@endsection
...

dhermann started a new conversation View Composer Data Not Available When Assigned To Layout

I was taking the advice of @Snapey and @Cronix to assign my View Composer to my master layout, instead of a wildcard, but it doesn't seem to be working.

ComposerServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        View::composer(['layouts.app'], function ($view) {
            $year = \App\Year::where('is_current', '1')->first();
            $view->with('year', $year);
...
        });

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

ErrorException (E_ERROR) Undefined variable: year (View: /home/vagrant/code/resources/views/campcost.blade.php)

I can see from the debug bar that the ComposerServiceProvider database calls are not happening. Any ideas?

15 Oct
1 month ago

dhermann left a reply on Getting User Facade Within View Composer

@Cronix Is there any way to make it visible to both the Controller classes and the ServiceProviders (where my View Composer is registered)?

14 Oct
1 month ago

dhermann left a reply on Getting User Facade Within View Composer

Just curious @Cronix, is there a way to use a Factory or Singleton to make this data available to my Controller layer as well, but only run the database call once?

dhermann left a reply on Getting User Facade Within View Composer

Ugh just reverted all my changes and it's working now. I wonder what I was doing wrong. Thanks @Cronix @Snapey @Dalma.

dhermann left a reply on Getting User Facade Within View Composer

It looks like Auth::check() is false even when I'm logged in. Do I call $view->with() multiple times for multiple objects?

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function boot()
    {
        view()->composer(
            'layouts.app',
            'App\Http\ViewComposers\MuustrapComposer'
        );
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}
<?php

namespace App\Http\ViewComposers;

use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class MuustrapComposer
{

    public function __construct()
    {
        //
    }

    public function compose(View $view)
    {
        $year = \App\Year::where('is_current', '1')->first();
        $view->with('year', $year);
        if (Auth::check()) {
            $camper = \App\Camper::where('email', Auth::user()->email)->first();
            $view->with('logged_in', $camper);
            $view->with('registered', \App\Yearattending::where('camperid', $camper->id)->where('year', $year->year)->first());
        }
    }
}

dhermann left a reply on Getting User Facade Within View Composer

@Dalma Okay, but then if I call Auth::user()->camper() multiple times in a blade (which I do often), won't it run the database call multiple times? If so, how do I avoid this if I didn't want to put that code in every Controller view method?

dhermann left a reply on Getting User Facade Within View Composer

@Cronix Good idea, but how do I get the data I'm looking for?

@Snapey Thanks.

dhermann left a reply on Getting User Facade Within View Composer

@Snapey Again, a good idea, but the issue is that Auth::user() is not set at that point in the View Composer. How would a relationship help?

dhermann left a reply on Getting User Facade Within View Composer

@Snapey Okay, I'll add a nullcheck, but I'm still not sure if the data is available at that point (in the View Composer).

dhermann left a reply on Getting User Facade Within View Composer

@Dalma It is such a common piece of data for my application that I'd like it directly available in every view. Does that make sense?

dhermann left a reply on Getting User Facade Within View Composer

So move the code from ComposerServiceProvider::boot() to ComposerServiceProvider::compose()? That doesn't seem to work.

I have the debug bar installed, but the page doesn't render because Auth::user() returns null.

dhermann started a new conversation Getting User Facade Within View Composer

I've created the standard View Composer class and registered it:

`<?php

namespace App\Providers;

use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\View; use Illuminate\Support\ServiceProvider;

class ComposerServiceProvider extends ServiceProvider { /** * Register bindings in the container. * * @return void / public function boot() { View::composer('', function($view) { $year = \App\Year::where('is_current', '1')->first(); $camper = \App\Camper::where('email', Auth::user()->email)->first(); $view->with('year', $year); $view->with('logged_in', $camper); });

}

/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    //
}

}`

But at that point, the Auth::user() method is null. Can I "delay" the rendering of the View Composer until after that facade is available, or is there a way to get that data from another object?

Thanks,

Dan

04 Oct
1 month ago

dhermann left a reply on Correct View Caching Method?

@Cronix It looks like I can't access the Auth::user object at that point in the render. Is there a later point at which I can attach some common code to all views with that object intact? I tried both the [email protected] method and adding my own custom ServiceProvider and adding the data through the View::composer() method.

01 Oct
1 month ago

dhermann left a reply on Correct View Caching Method?

That's what I thought as well. Thanks for the quick response.

dhermann left a reply on Correct View Caching Method?

Thanks @Cronix; great answer. What is the advantage to using a View Composer instead of the View::share() method as described earlier on the Views doc page? Is it just that you can assign the method to be available only on some specific views?

dhermann started a new conversation Correct View Caching Method?

All,

While I realize that the best way to ensure you only run a query once is to pass the variable into the view after setting it in the Controller layer, I have some common values that I am constantly using in my layout blades and really don't want to set it every time. I have put the method in the HomeController and used the @inject directive to allow access to it on every page. This has resulted in duplicate database calls at run-time as the page loads.

What is the correct method to allow access to a common database call on every page, especially in your layout blades? Should I just rely on MySQL to cache the call? Is there a way to set a global variable in the layout without resorting to a PHP scriptlet?

Thanks,

Dan

15 Mar
8 months ago

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

Does anyone have any ideas for how to proceed? @bobbybouwmann

07 Mar
8 months ago

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

I don't understand. I just upgraded to 5.6.

Dans-MacBook-Air:muustrap danhermann$ php artisan --version
Laravel Framework 5.6.7
06 Mar
8 months ago

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

Progress! Thanks @bobbybouwmann ! But still getting unexpected errors:

Dans-MacBook-Air:muustrap danhermann$ composer dump-autoload
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
You made a reference to a non-existent script @php artisan package:discover

Should I remove the package:discover directive you mentioned? I'm running the latest version of Homestead.

Dans-MacBook-Air:muustrap danhermann$ php artisan dusk
PHPUnit 7.0.2 by Sebastian Bergmann and contributors.

E                                                                   1 / 1 (100%)

Time: 116 ms, Memory: 6.00MB

There was 1 error:

1) Tests\Browser\ExampleTest::testBasicExample
TypeError: Argument 1 passed to Illuminate\Database\Eloquent\Model::setEventDispatcher() must be an instance of Illuminate\Contracts\Events\Dispatcher, null given, called in /Users/danhermann/Homestead/muustrap/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php on line 79

/Users/danhermann/Homestead/muustrap/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasEvents.php:326
/Users/danhermann/Homestead/muustrap/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:79
/Users/danhermann/Homestead/muustrap/vendor/laravel/dusk/src/TestCase.php:23

ERRORS!
Tests: 1, Assertions: 0, Errors: 1.

I'm not sure what to do with this one?

05 Mar
8 months ago

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

Thanks @shez1983 but I have the namespace Tests (from @bobbybouwmann 's class) in there now with no difference.

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

I copied the createsApplication trait into /Tests and added the post-autoload-dump script to my composer.json, updated composer (which interestingly updated about a dozen dependencies), but no change in the error message.

Dans-MacBook-Air:muustrap danhermann$ php artisan dusk

Fatal error: Class 'Tests\DuskTestCase' not found in /Users/danhermann/Homestead/muustrap/tests/Browser/ExampleTest.php on line 9
03 Mar
8 months ago

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

It's the example straight out of the box. I added the interfaced method.

<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ExampleTest extends DuskTestCase
{

    public function createApplication()
    {
        // TODO: Implement createApplication() method.
    }

    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee('Laravel');
        });
    }
}

dhermann left a reply on Dusk Base Installation Does Not Function In 5.6

Thanks Bobby. I did that; no difference.

use Illuminate\Support\ServiceProvider;
use Laravel\Dusk\DuskServiceProvider;

class AppServiceProvider extends ServiceProvider
{
@@ -23,6 +24,8 @@ class AppServiceProvider extends ServiceProvider
     */
    public function register()
    {
        //
        if ($this->app->environment('local', 'testing', 'staging')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}
02 Mar
8 months ago

dhermann started a new conversation Dusk Base Installation Does Not Function In 5.6

I want to give Dusk another try as I upgraded to 5.6 and find myself more and more often in need of automated browser testing. The base installation does not appear to function, however.

Dans-MacBook-Air:muustrap danhermann$ composer require --dev laravel/dusk
Using version ^3.0 for laravel/dusk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing facebook/webdriver (1.5.0)
    Downloading: 100%         

  - Installing laravel/dusk (v3.0.3)
    Downloading: 100%         

Writing lock file
Generating autoload files
> Illuminate\Foundation\ComposerScripts::postUpdate
Dans-MacBook-Air:muustrap danhermann$ php artisan dusk:install
Dusk scaffolding installed successfully.
Dans-MacBook-Air:muustrap danhermann$ php artisan dusk

Fatal error: Class 'Tests\DuskTestCase' not found in /Users/danhermann/Homestead/muustrap/tests/Browser/ExampleTest.php on line 9

The base ExampleTest class doesn't even have an createApplication() implementation, which right away worries me. But I added that and still get the same error. PhpStorm is also giving me grief about unhandled exceptions in the browse() method but running dusk from the command line clearly doesn't work out-of-the-box. I'm also not sure what I'm missing to get the ServiceProvider to register automatically but there were no changes in my /config/app.php. Can anyone assist?

class ExampleTest extends DuskTestCase
{

    public function createApplication()
    {
        // TODO: Implement createApplication() method.
    }

    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/')
                    ->assertSee('Laravel');
        });
    }
}
07 Mar
1 year ago

dhermann left a reply on 5.4 Iterating Over An Eloquent Collection After GroupBy Using Foreach

Wow. That is... not immediately apparent.

06 Mar
1 year ago

dhermann left a reply on 5.4 Iterating Over An Eloquent Collection After GroupBy Using Foreach

Thanks, Tykus, but your answer seems to go against the documentation.

https://laravel.com/docs/5.4/collections#method-groupby

Shouldn't groupBy naturally put rows with the same key into an array, instead of "just one row for each name"? It seems like you're describing the functionality of keyBy(). Can you explain a little further?

03 Mar
1 year ago

dhermann started a new conversation 5.4 Iterating Over An Eloquent Collection After GroupBy Using Foreach

Imagine, if you will, a table. But this table isn't like other tables, for it has... a composite key.

Years_My_Family_Has_Visited_The_Circus | Name | Year | | --- | --- | | Alan | 2015 | | Alan | 2016 | | Alan | 2017 | | Betty | 2014 | | Betty | 2016 | | Betty | 2017 | | Charlie | 2017 |

So I make that model into an Eloquent object and call it with a groupBy.

$family = \App\YMFHVTC::groupBy('name')->get();

But in my blade, I don't get what I'm iterating over. What comes out of the outer foreach()?

@foreach($family as $name => $member)
   {{ $name }}
   @foreach($member as $eachyear)
      {{ $eachyear->name }} {{ $eachyear->year }} 
   @endforeach 
@endforeach 

This fails horribly. Shouldn't an YMFHVTC object come out of the inner foreach()? When I use print_r() to try and debug it I see a populated attributes object, should I be referencing $eachyear->getAttributes()? In the documentation they reference $family->toArray(); why is flattening it necessary?

01 Mar
1 year ago

dhermann left a reply on Laravel HTML Form With File Input To Mailable HTML?

Forgot to rename my input field name to "images[]" when I added multiple. It works!

dhermann left a reply on Laravel HTML Form With File Input To Mailable HTML?

This seems like it should work... what am I missing? It won't even attach the first image now.

    public function build()
    {
        $view = $this->from($this->camper->email)->view('mail.artfair');
        foreach($this->request->images as $index=>$image) {
            $view->attach($image, [
                'as' => $this->camper->lastname . $index . "." . $image->extension(),
                'mime' => $image->getMimeType(),
            ]);
        }
        return $view;
    }

dhermann left a reply on Laravel HTML Form With File Input To Mailable HTML?

Perfect! That worked!

    public function build()
    {
        return $this->from($this->camper->email)->view('mail.artfair')->attach($this->request->images, [
            'as' => $this->camper->lastname . "." . $this->request->images->extension(),
            'mime' => $this->request->images->getMimeType(),
        ]);
    }

But how do you handle multiple? Does $request->multiplename come across as an array to iterate through?

dhermann left a reply on Laravel HTML Form With File Input To Mailable HTML?

Snapey,

Thanks for your reply. You were exactly right: the form encoding type needs to be set.

So I've discovered my primary misunderstanding: attachData in the build() method will attach a file to the email itself, while embed in the blade is what you use to view a file (in this case, an image) inline in the mail's HTML. Not sure why I didn't pick up on that right away.

So now I'm at this line of code: MyMailable.php

    public function build()
    {
        return $this->from('[email protected]')->view('mail.artfair')->attachData($this->request->file('images'), 'My Image Superfun Name');
    }

Which results in an attachment to the message, but it's 1KB and Gmail won't let me download it. I know you suggested saving it to disk first, but this seems very close to not needing to. I don't want to host the image; just send it in an email. Do you have any advice for what to try next?

28 Feb
1 year ago

dhermann started a new conversation Laravel HTML Form With File Input To Mailable HTML?

Imagine, if you will, for just a moment: a form. A form like many others, but this one... has a file input.

<form id="artfair" class="form-horizontal" role="form" method="POST" action="{{ url('/artfair') }}">
...
<div class="form-group{{ $errors->has('images') ? ' has-error' : '' }}">
   <label for="images" class="col-md-4 control-label">High-quality Images</label>

   <div class="col-md-6">
      <input type="file" name="images" value="{{ old('images') }}"/>

      @if ($errors->has('images'))
          <span class="help-block">
              <strong>{{ $errors->first('images') }}</strong>
          </span>
      @endif
   </div>
</div>
... 
(submit button)

This form should have validation, right? MyController.php

...
$this->validate($request, [
            'message' => 'required|min:5',
            'images' => 'image|dimensions:min_width=100,min_height=200',
            'g-recaptcha-response' => 'required|captcha',
], $messages);
...

And then pass the $request to a Mailable, yes? MyMailable.php

class ArtFair extends Mailable
{
    use Queueable, SerializesModels;
    public $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function build()
    {
        return $this->from('[email protected]')->view('mail.artfair')->attachData($this->request->file('images'), 'Does not matter name');
    }
}

And then the image gets shown in the HTML of the blade? mail/artfair.blade.php

...
<p><strong>Images</strong>:</p>
<div><img src="{{ $message->embedData($data, $name) }}"></div>
...

So there's a couple problems. First off, validation is failing on a png? $errors->first('images')

The images must be an image.

Second, did I use attachData() correctly? I can't find any examples using input from the request.

Third, I'm testing locally on Homestead with a Mailgun driver. Do I need to do anything to my settings to allow this feature?

Thanks,

Dan