mmacdonald

Experience

7,490

1 Best Reply Awards

  • Member Since 2 Years Ago
  • 54 Lessons Completed
  • 0 Favorites

11th October, 2018

mmacdonald left a reply on Laravel And Vue - Web / Auth Middleware Is Pushing Out My Users Randomly. • 4 days ago

@jekinney Wow! Thank you so much! That actually makes a lot of sense. The part I was missing was storing the token in vuex and checking for it in the before route for Vue.

Any chance you could post a bit of code for what the "before route file" in Vue looks like?

Are we just talking about doing

router.beforeEach((to, from, next) => {
    // ..
}

in the Vue router? or do you actually have an entire separate file where you're essentially creating Vue "middleware"?

10th October, 2018

mmacdonald left a reply on Laravel And Vue - Web / Auth Middleware Is Pushing Out My Users Randomly. • 5 days ago

@jekinney So you're saying to remove all Laravel middleware basically and make my app use API authentication through Vue?

Only thing I don't understand with this strategy is how you deal with "logged in" vs "logged out"? If the token doesn't exist or isn't valid doesn't the data call just fail? What forces the user out?

Or is there middleware I can set up with Vue somehow so that when you switch Vue routes it checks authentication?

mmacdonald started a new conversation Laravel And Vue - Web / Auth Middleware Is Pushing Out My Users Randomly. • 5 days ago

My app has two Vue single page "Apps" within it that Laravel redirects to based on the web / auth middleware.

So all routes go through "/" as usual. If the user is authenticated then they're redirected to the interior app, if the aren't then they are redirected to the Welcome app.

The interior app has a Vue router which chooses the components to display.

The problem though is that somehow people are getting pushed out to the Welcome app fairly often. Often you can even just go back to the www.website.com/ base route in your browser and it will take you back to the interior app again, because you weren't really "signed out".

It's as if the app is forgetting my session token or something temporarily and I don't know how to trace what's causing it.

So that's what I'm hoping for here: that someone can "trace" out what the process is for Laravel -> Vue and where the token might be getting "lost".

Here are the two important routes:

//This one has no middleware
Route::get('welcome', 'Auth\[email protected]')->name('login');

AND

//This one is in the web middleware group AND I'm calling the Auth middleware inside the //HomeController
Route::group(['middleware' => 'web'], function(){
    Route::get('/', '[email protected]');
}

//Home Controller
public function __construct()
 {
       $this->middleware('auth');
  }

Anything else you want to see, just let me know. This one is a bit hard to know what I should include, since I don't really know which file might be the source of the problem.

Thanks for your help!

9th August, 2018

mmacdonald started a new conversation Using Laravel Passport And Postman Gives Me A Method Not Allowed Exception • 2 months ago

I'm trying to request a token from Passport with Postman

The docs say to make a request to "http://your-app.com/oauth/token" but all I get at that route is a MethodNotAllowedHttpException.

I checked my route:list and the route shows up and says "POST | oauth/token" which is exactly what I'm trying to send the request to from Postman.

Here is a screenshot of my Postman parameters. (Changed the values of course).

It doesn't seem to matter what keys I use. I've also tried putting the data in the body instead of the Headers but it gives me the same result. That's the part I don't understand, I'm new to using APIs and Passport but I know what a MethodNotAllowed exception in Laravel typically means but it doesn't seem to matter here. The route list says its POST, I'm sending it with POST, what else can go wrong to throw that exception every time?

Anyone with some experience with Postman or Passport or even just HTTP POST requests. Any advice would be greatly appreciated!

Thank you!

16th April, 2018

mmacdonald left a reply on PHP Fatal Error Says Exception\Handler Does Not Exist In An Essentially New Laravel Build • 5 months ago

@bobbybouwmann

Thanks for the reply!

Just tried deleting the vendor directory and running composer install and it fails on the same command! It runs the entire install then catches the postAutoLoadDump and runs artisan package:discover and fails on the Reflection Exception... super weird.

And I double checked and I do have the correct version of Laravel (5.6.*) and fideloper/proxy, tinker, guzzle, php... all the essentials are updated to the current versions.

Can you think of a way I could actually catch the real error? Instead of letting it go to the Handler (which doesn't yet exist)?

mmacdonald started a new conversation PHP Fatal Error Says Exception\Handler Does Not Exist In An Essentially New Laravel Build • 5 months ago

I created a new Laravel 5.6 build and I imported some settings (composer.json, package.json, some config files, and some env settings) from a 5.5 project that I had and it now fails with the exception:

PHP Fatal error:  Uncaught ReflectionException: Class App\Exceptions\Handler does not exist in ...\vendor\laravel\framework\src\Illuminate\Container\Container.php:767

//Line 767 of Container.php calls:

$reflector = new ReflectionClass($concrete);

It's specifically failing on a call to php artisan package:discover when I'm calling composer dumpautoload (since composer catches the "post-autoload-dump" event and calls package:discover). But I can't call any artisan commands without getting an exception.

I think something I changed may have broken something and this error is really just because my App is trying to throw an exception before the Exception Handler is ready. Which leads me to thinking it is something earlier in the life-cycle. I don't know the Laravel life-cycle well enough though to guess what that could be...

Any thoughts? It's basically a brand new project so it must be a config file or env setting or something... my routes file is only the default Laravel route. I'm a bit lost because the exception isn't really pointing to the real error. Just to the lack of a Handler for the real exception.

I can always go through and undo the config files and such one at a time until I figure out which one broke it, but any help is appreciated in the meantime!

17th March, 2018

mmacdonald left a reply on How Can I Get The First Model Of A HasMany (creating A Separate Relationship Didn't Work...) • 6 months ago

@shez1983 Hmm... so that was close... for which I am eternally grateful. Didn't need the "orderBy" or "first" though (since hasOne only returns one). So this:

firstBook() {
    return  $this->hasOne('App\Book', 'series_id', 'id');
}

works perfectly.

Can you possibly explain why though? I guess I'm just forcing a model which does have many, to pretend it only has one? Which defaults to the first available?

It seems really counter intuitive... but at the same time it somehow makes perfect sense that it would work since I only ever wanted one anyway. I think I'm more confused about why mine didn't work.

I was asking for a collection, and then specifying I only wanted the first. Shouldn't that have worked?

Either way, thank you so much for your help! It was just the recommendation i needed!

mmacdonald started a new conversation How Can I Get The First Model Of A HasMany (creating A Separate Relationship Didn't Work...) • 6 months ago

I have a table called "Series" and a table called "Books"

Series
=====
id
name

Books
=====
id
title
series_id

Each Series hasMany Books.

public function books(){
        return $this->hasMany('App\Book',  'series_id', 'id');
 }

I want to get ALL of the series, and ONE (the first) Book in each series.

My Googling has shown me people recommending something like this:

public function first_book(){
        return $this->books()->first();

    //OR

    return $this->hasMany('App\Book', 'series_id', 'id')->limit(1);
}

Both of those return the same thing... An array of ALL the series (yay) but only the FIRST series shows any relationship (nay). I can confirm without a doubt that there are 1000s of Books divided between 14 series (always with at LEAST one per series).

In the controller I am calling the relationship like this:

$series = Series::with('first_book')->get();

I've tried calling first() in the controller, instead of the relationship, but I'm pretty sure you can't eager load like that.

//Relationship
public function books(){
        return $this->hasMany('App\Book',  'series_id', 'id');
 }
//Controller
$series = Series::with(['books' => function($q){
    $q->first();
}])->get();

But this gives me the same result... no first book for any series except the FIRST one.

Here is a DD of the result (without the unhelpful info):

Collection {#1404 ▼
  #items: array:4 [▼
    0 => Series {#1305 ▼
      #relations: array:1 [▼
        "books" => Collection {#1403 ▼
          #items: array:1 [▼
            0 => Book {#1393 ▶}
          ]
        }
      ]
    }
    1 => Series {#1306 ▼
      #relations: array:1 [▼
        "books" => Collection {#1359 ▼
          #items: []
        }
      ]
    }
}

In the 7th Row you can see the single book returned inside Series[0]. In the 15th Row you can see Series[1] returns an empty array.

Any thoughts? Where am I going wrong? Thank you!

19th November, 2017

mmacdonald left a reply on Can I Eager Load A Relationship On An Implicitly Bound Model? • 10 months ago

@Snapey Thanks!

That worked. Its odd... I've used load before, but somehow it didn't seem right here until I actually tried it.

In my head I kept thinking it would be something like this:

public function index(Model $model.relationship){
    //
}

Which is obviously quite silly!

Didn't help that I was looking under the routing#implicit-binding section of the documentation instead of Eloquent.

Anyway, thanks for the help! Simple and straight forward, like I hoped!

mmacdonald started a new conversation Can I Eager Load A Relationship On An Implicitly Bound Model? • 10 months ago

In a controller I can receive the implicitly bound model and pass it to the view like this:

public function index(Model $model){
    return view('page', compact('model'));
}

But is it possible to eager load a relationship on that model?

If I was finding it myself I would just do something like:

$model = Model::where('id', 1)->with('relationship')->get();

but when it's implicitly bound I don't have access to the model while it's being loaded.

Thanks!

22nd October, 2017

mmacdonald left a reply on In A Blade View I Can't Seem To Get A Column To Print. • 11 months ago

@Snapey I'd picked up on the collection issue, but is it not possible to access a collection directly by index? (Like modelThree[0])

Trying first, it gives me a "property of non-object" exception.

Still weird... Can I specify in the Nested Eager Load that I only want "first"?

mmacdonald started a new conversation In A Blade View I Can't Seem To Get A Column To Print. • 11 months ago

To simplify it I'll just make up model names...

ModelOne -> belongsTo(ModelTwo)

ModelTwo -> belongsToMany(ModelThree)

If I load ModelOne and use "with" then I can't print ModelThree's columns in a Blade view... but I can print the entire ModelThree (as an object)

$modelOnes = ModelOne::select(...blah...blah...)->with('modelTwo.modelThree')->get();

//So I'm using a nested relationship to get both ModelTwo AND ModelThree

And if in my view I try to echo out a column on ModelThree I get nothing...

{{ $modelOne->modelTwo->modelThree }}

//This prints the entire object (all it's columns and their data...)

{{ $modelOne->modelTwo->modelThree->column_name }} 

//This prints nothing... even though I can *see* the column is there when I print the entire object

When the entire object prints it shows up like this:

"[{"col_1": data, "col_2": data ...}]

Which lead me to think I could maybe access the data if I used an index like this:

{{ $modelOne->modelTwo->modelThree[0]->column_name }}

//But this gives me an 'offset undefined' error

Not really sure where to go... this is my first time using Nested Eager Loading. Any thoughts on where I'm going wrong?

If any of what I said here doesn't make sense, I can clarify... just ask! I'm just trying not to bog it down with what the Models actually are. Thank you!

19th October, 2017

mmacdonald left a reply on Migrations Won't Run Because "blank" Class Doesn't Exist. • 11 months ago

Hmm... so I solved it, but I'm going to leave this up in case some other person stumbles upon it...

Today I learned that Laravel has to have the timestamp at the start of the migration name! I re-added the timestamps and adjusted the seconds to order them how I wanted instead of just an index. Ran composer dump-autoload . and then it migrated perfectly.

Yay!

mmacdonald started a new conversation Migrations Won't Run Because "blank" Class Doesn't Exist. • 11 months ago

I'm extremely confused... I have an (essentially) fresh install of Laravel. All I've really done is create my models and migrations. Now I'm trying to run the migrations and I keep getting the error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Class '' not found```

Which makes no sense to me. It successfully creates the "migrations" table and then fails to run even he first migration. The part that confuses me though is that the Class is '' (blank)... it doesn't have a name! How can i be missing a blank class? Where is it even trying to call this non-existent class?

I've tried ```composer dump-autoload
php artisan cache:clear
php artisan optimize
php artisan clear-compiled```

Not necessarily in that specific order... and a bunch of combinations therein.

Error log looks like:

[2017-10-19 15:57:48] local.ERROR: Class '' not found {"exception":"[object] (Symfony\Component\Debug\Exception\FatalThrowableError(code: 0): Class '' not found at /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php:417) [stacktrace] #0 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php(168): Illuminate\Database\Migrations\Migrator->resolve('0create_users...') #1 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php(146): Illuminate\Database\Migrations\Migrator->runUp('/home/vagrant/W...', 1, false) #2 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Database/Migrations/Migrator.php(95): Illuminate\Database\Migrations\Migrator->runPending(Array, Array) #3 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php(69): Illuminate\Database\Migrations\Migrator->run(Array, Array) #4 [internal function]: Illuminate\Database\Console\Migrations\MigrateCommand->handle() #5 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(29): call_user_func_array(Array, Array) #6 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}() #7 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure)) #8 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Container/Container.php(549): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL) #9 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Console/Command.php(180): Illuminate\Container\Container->call(Array) #10 /home/vagrant/__/vendor/symfony/console/Command/Command.php(264): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle)) #11 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Console/Command.php(167): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle)) #12 /home/vagrant/__/vendor/symfony/console/Application.php(888): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #13 /home/vagrant/__/vendor/symfony/console/Application.php(224): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Database\Console\Migrations\MigrateCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #14 /home/vagrant/__/vendor/symfony/console/Application.php(125): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #15 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Console/Application.php(88): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #16 /home/vagrant/__/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(121): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #17 /home/vagrant/__/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) #18 {main} "}

Ignore the path containing "___" I just changed out the project name, for NDA reasons...

This is all running locally on an out-of-the-box Homestead setup. 

All the advice I've found for related issues is basically "composer dump-autoload" which runs fine... but doesn't fix the issue. Which I'm *assuming* is because the class is blank and there is some other underlying issue here.

The only thing I can think of is changing the names of the migrations to just use a numerical index instead of a timestamp... I'm not really sure why that would matter though. All the class names still match their respective migration names. For example the first migration is 0_create_users_table.php and it looks like this:

class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); }

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('users');
}

}

*Any* input at this point would be greatly appreciated! I'm not sure what I've messed up... but I'm completely stumped as to how I should proceed.

Thanks!

2nd June, 2017

mmacdonald left a reply on Advice On How Best To Design Component • 1 year ago

That should be fine if it's working for you. There isn't really any security concerns there assuming the component isn't a form? I suppose if you're passing it to a form someone could change the ID and submit the form... but that check could/ should be handled on the other end anyway.

For example, if the user is editing a course with this component and they change the ID and submit the edit and then your controller saves their changes to a different course... Kind of silly, but it's the only thing I can think that would really matter about passing the ID.

But otherwise, passing the value like that is really just echoing it out. So it's no different than you simply writing

<course :user="user" :course="4" inline-template>

directly into the prop.

mmacdonald left a reply on Very Fast Teaching Way • 1 year ago

I think Snapey really nailed it though... if the content seems too fast, just repeat what you don't understand or literally slow down the playback speed.

Jeff certainly has little tricks and shortcuts he might not always realize he's using but I think he does a pretty good job of explaining everything he's doing as he goes along.

Either way though, if you can't understand something specific you can always post a question here asking for further explanation. Like "How is Jeff doing ___" or "I don't understand how ____ works".

It's extremely difficult to make videos that appeal to everyone, particularly when it comes to content speed. Some people absorb new info very quickly while others need a lot more explanation. Jeff has to try and balance between too quick for the slow learners and too slow and boring for the fast learners.

Maybe try finding some text tutorials that you can take at your own pace or watch some of Jeff's other videos where he covers some of his workflow (the series on PHPStorm was quite helpful for me, as it showed a lot of tips and tricks he uses in that particular program).

Scotch.io (https://scotch.io/search?q=laravel) has some pretty useful videos and text tutorials on Laravel that might help a bit. Laravel can be a bit tricky to wrap your head around if you're particularly new to coding, so maybe try the links that jlrdw linked to and get more comfortable with HTML and PHP basics before advancing into Laravel. I'm sure you can find someone, somewhere, who teaches in a way that appeals to you! It's unfortunate that maybe it isn't Jeff, but I don't think he'll be offended if you just move on and try someone else! :)

If you do have any specific questions, I'm sure the people in this community can help you figure out the answer though!

16th April, 2017

mmacdonald left a reply on Dynamic Route Path In Form Action Based On The Selected Option • 1 year ago

Are you using Vue at all? jQuery? There are a couple different options available if you are...

mmacdonald left a reply on Best Practice For Same API URL But Accessible Both Privately And Publicly • 1 year ago

@darkylmnx Oh right, sorry, forgot it was an API.

Honestly, that's what I would do then, just keep using the If. You have to check anyway and it's simpler to have less routes which are more concise. Especially with an API.

As long as those routes perform the same (or almost the same) function (which they do, in this case).

It would be kind of like having "Roles". You wouldn't make different routes for Admin/User/Other, you would make one route which then checks in the controller which Role is accessing and returns the appropriate data. In your case, the 'Roles' just happen to be Auth'd or Not Auth'd.

mmacdonald started a new conversation Counting A Distant Relationship In A Blade Without Looping. • 1 year ago

I have a Rules model, an Exception model, and a Word model.

There are Rules, those rules have exceptions, and those exceptions have a list of words attached.

Rule 1
    -> Exception 1
        -> Word 1
        -> Word 2
        -> Word 3
    ->Exception 2
        -> Word 1
        -> Word 2
        -> Word 3

Is there a way to count the Words from the Rule? So in the example above, I want to be able to display the number "6" because Rule 1 has 6 exception words...

$rule->exceptions->words->count()
//Something like this would be awesome, but because 'exceptions' is a collection of Exceptions, the 'words' relationship doesn't exist without looping through them one at a time

Obviously in the Blade view it would be extremely inefficient to have to loop through each exception getting the count of its words and then adding them to some grand total which I then display... It's possible, it just feels really sloppy.

So is there a way to count the distant relationship without looping?

Thanks!

mmacdonald left a reply on Best Practice For Same API URL But Accessible Both Privately And Publicly • 1 year ago

I would use the same route for both and put an IF in your controller method. (Wherever you're returning your Blade view)

return Auth::check() ? view('private_view_here') : view('public_view_here');

Unless you aren't using views? Or you don't want to separate the views... Either way, just do the check in your controller (or if you're really desperate, you could do the check directly in your routes file... but that's less desirable)

The two routes option would work as well, but you'll likely still be doing the Auth:check() somewhere anyway, so probably cleaner just to change the view

mmacdonald left a reply on Quick Help With Turning A MySQL Query Into A Laravel Query. • 1 year ago

... I'm not "getting" anything... I swear I looked at this for like 20 minutes and I can't believe I was just missing ->get() lol

Sorry guys. I'll do better next time.

mmacdonald started a new conversation Quick Help With Turning A MySQL Query Into A Laravel Query. • 1 year ago

This works in MySQL:

SELECT word_id, COUNT(*) AS total FROM word_counts WHERE level_id = 2 GROUP BY word_id ORDER BY total DESC;

And I'm trying to get it as a query builder or eloquent select.

I have this currently:

App\WordCount::select('word_id', DB::raw('COUNT(*) as total'))->where('level_id', '=', $level->id)->groupBy('word_id')->orderBy('total', 'desc')

but it returns nothing... Not an error, just no results. The MySQL query returns 73 results.

I'm confused where I'm going wrong and I can't seem to figure it out! Do any of you see any issues in my Laravel query?

1st April, 2017

mmacdonald left a reply on Task Scheduler Problem • 1 year ago

I'm not an expert on the scheduler, but I believe it's that it isn't 'ready yet' when you're calling it. Try calling schedule:run and then try again 5 minutes later. Now does it work?

For mine I have a kron job that runs the scheduler every minute on my server. So I think of php artisan schedule:run as a 'check' to see if any events are ready to be fired.

So you need to 'check' frequently but it will only fire when an event is actually ready.

So my scheduler runs every minute and I have an event that backs up my site every night at midnight and another event that send out a temp password that changes every hour. So even though the scheduler is called every minute, it only fires the events hourly or daily.

I'm honestly not even 100% sure if this is the correct way to be doing it, but it's always worked for me...

mmacdonald left a reply on Failed To Decode Downloaded Font • 1 year ago

No problem, glad you got it working!

mmacdonald left a reply on Email Not Being Sent When Using Artisan Command • 1 year ago

Can you post the code for the command?

mmacdonald left a reply on Failed To Decode Downloaded Font • 1 year ago

"While I'm developing a project"

What are you doing at the time specifically, though? Is this happening when you try to Mix? Serve? When are you getting the error?

Also, do those fonts exists in your /public/fonts folder?

mmacdonald left a reply on API Documentation And Testing • 1 year ago

I haven't done testing or documenting with it but Postman is an incredible tool for any API building.

Their home page describes it as "A powerful GUI platform to make your API development faster & easier, from building API requests through testing, documentation and sharing..." so it might have the functionality you're looking for.

Again, not a part of Postman I have experience with, so I can't help much with how good it is, but somewhere for you to start, if you aren't already familiar with it!

Good luck!

mmacdonald left a reply on Easiest Way To Display Time Slots From 8AM To 5PM With 15 Minute Increments? • 1 year ago

Just a loop will suffice, but you might want to try using Carbon

Something like this in your controller:

$today = Carbon::today(); // 2017-04-01 00:00:00
$allTimes = [];
for ($i = 0; $i <= 0(or however many steps you need...); $i ++){
    $time = $today->addMinutes(15 * $i); // add 0, 15, 30, 45, 60, etc...
    array_push($allTimes, $time->toTimeString()); // inserts the time into the array like 00:00:00, 00:15:00, 00:30:00, etc.
    
}

Then just return the array to your view and use a blade @foreach to loop through the content, making a checkbox each time.

mmacdonald left a reply on New Installation Of Laravel Throw 500 Error • 1 year ago

Are you serving the site in some way locally? ```php artisan serve`` or something like it?

Honestly, try following along with this video series to get started: https://laracasts.com/series/laravel-from-scratch-2017

Even just the first couple videos (which are like 11 minutes combined...) will get you at least up and running in a browser and explain some of the basics!

25th March, 2017

mmacdonald left a reply on How To Not Commit Multiple Version Of Js And Css Files Using Webpack • 1 year ago

I think the simplest solution is to just use

npm run watch

(instead of production) while developing without versioning. Then when you want to push a production build delete everything (or at least everything that is being webpacked) in your public/css and public/js directories and run

npm run production

Seems like it would be a real pain in the butt to be running versioning all the time when developing. My IDE would be indexing every time a new version was made. So I only version when I have a build I'm ready to push live.

There is probably a better way, but that's how I've been doing it for a while.

19th March, 2017

mmacdonald left a reply on How Does Webpack Work On Prod Server • 1 year ago

As long as you changed it in devDependencies you should only need to run npm install on your server.

/node_modules is .gitignored but package.json isn't. So running npm install will still install all of the relevant packages.

mmacdonald left a reply on HasManyThrough Is Not Working But I Need An Option • 1 year ago

protected $fillable = array('book_id', 'isbn', 'user_id',  'comments');

If you're using the isbn as the primary key, what does 'book_id' reference?

I think you're referencing the table wrong in your relationships as well, so:

public function book()
    {
        return $this->belongsTo(Book::class, 'isbn'); //this should be the foreign key, so the key you're referencing on the *other* table.
    }

and

public function reviews()
    {
        return $this->hasMany(Review::class, 'book_id'); // this one should be fine, but be consistent. (See my comment below about changing to book_isbn)
    }

If you're making the switch to 'isbn' as the PK then you don't also want to have a book_id column... on the review model something like 'book_isbn' will give you the best of both worlds. You want it to say 'book' so that it is clear what table it relates to, but you also want don't want to call it 'id' since that implies there is a column on 'Book' called 'id' (which there isn't).

Something like this:

Book Columns = 'isbn', 'isbn13', 'title', 'pub', 'phydes', 'sum'

Review Columns = 'book_isbn', 'user_id', 'comments'

mmacdonald left a reply on Can I Modify A Model's Values On A Relationship Before Returning The Results? • 1 year ago

@Cronix Yeah, the more I've gotten into this the more I'm realizing the single name column is a really terrible idea... I've been locating all the spots I referenced 'name' on my site and it shouldn't be too hard to update everything and use two columns instead.

Just wish I'd realized it from the start... hindsight, though.

I'll keep the double last names in mind though when I do my update queries, since I'll need to check for that! Only split on the first space or something...

Thanks for the tip!

mmacdonald left a reply on Can I Modify A Model's Values On A Relationship Before Returning The Results? • 1 year ago

@jimmck Honestly, I'm not sure why it was ever made as a single name field... I'm 99% sure it was the default table that Laravel uses when you make your initial Auth migration.

Back when I first built the site I didn't even think to change it but Laravel really should change that default away from a single column.

I'm heavily leaning in the alter table direction... I just need to make sure I find all the places I'm using the current single string way...

mmacdonald left a reply on Can I Modify A Model's Values On A Relationship Before Returning The Results? • 1 year ago

@swalker I like that, but I'd also need to be able to sortBy or orderBy... which I don't think a presenter would help with, as it just reformats after the collection is created, right?

That is a really interesting way to format things for Blade though... Definitely have a few other places I'm going to be implementing that, haha!

@jlrdw I tried a custom array but I get an error saying relationship method must return an object of type Relation. Working on a query builder solution now, to see if I can work it out.

Definitely turning into a real pain just for some last name sorting... Might just end up altering the table

mmacdonald started a new conversation Can I Modify A Model's Values On A Relationship Before Returning The Results? • 1 year ago

So I have a User model (which in this case is acting as a "student"). I also have a Classroom model which has a relationship that gets all the Users in that class.

The relationship works and looks like this:

public function students(){
        return $this->belongsToMany('App\User', 'classroom_student', 'classroom_id', 'student_id');
    }

Each user has a 'name' column which formats like this: "Firstname Lastname".

Occasionally I need to get the students with their names formatted like this: "Lastname, Firstname". I could change the table to have two separate columns, but I already have a few thousand users in there and I'm already using their full names in a bunch of places. So changing the formatting this way seems easier.

I tried creating a custom function on the Classroom model that looks like this:

public function studentsLastNameFirst(){
        $students = $this->students();
        foreach($students as $student){
            $name = $student->name;
            $nameArray = explode(' ', $name);
            $nameArray = array_reverse($nameArray);
            $name = implode(", ", $nameArray);
            $student->name = $name;
        }
        return $students;
    }

The php part isn't really a concern as I know it will split the name at the space, flip the names, and add a comma... (I tested it independently).

The issue is that on my view it just returns the 'students' relationship. Their names don't change at all... Is there a better way to do this? Do you see a glaring issue I'm missing here?

Thanks!

4th February, 2017

mmacdonald left a reply on Upgraded A Laravel Project To 5.3 (from 5.2) And It No Longer Passes Object Instances Through Routes... • 1 year ago

Definitely stuck here, so if anyone has any guesses at all, I'm willing to try them... I created a new test route to see if I can figure it out which goes like this.

Route:

Route::group(['middleware' => ['web', 'auth']], function(){

    Route::get('test/book/{currentBook}', '[email protected]');

}

BookController:

public function test(Book $currentBook){

        print_r($currentBook);

}

Which returns:

App\Book Object ( 
    [connection:protected] 
    => [table:protected] 
    => [primaryKey:protected] 
    => id [keyType:protected] 
    => int [perPage:protected] 
    => 15 [incrementing] 
    => 1 [timestamps] 
    => 1 [attributes:protected] 
    => Array ( ) [original:protected] 
    => Array ( ) [relations:protected] 
    => Array ( ) [hidden:protected] 
    => Array ( ) [visible:protected] 
    => Array ( ) [appends:protected] 
    => Array ( ) [fillable:protected] 
    => Array ( ) [guarded:protected] 
    => Array ( [0] => * ) [dates:protected] 
    => Array ( ) [dateFormat:protected] 
    => [casts:protected] 
    => Array ( ) [touches:protected] 
    => Array ( ) [observables:protected] 
    => Array ( ) [with:protected] 
    => Array ( ) [exists] 
    => [wasRecentlyCreated] 
    =>
)

Which makes zero sense to me... anyone see where I'm going wrong? Did something change drastically with Laravel 5.3 that I'm completely missing?

mmacdonald left a reply on Upgraded A Laravel Project To 5.3 (from 5.2) And It No Longer Passes Object Instances Through Routes... • 1 year ago

Now I'm exceptionally confused since the 5.3 official docs say:

You can define a route to this controller action like so:

Route::get('user/{id}', '[email protected]');

Now, when a request matches the specified route URI, the show method on the UserController class will be executed. Of course, the **route parameters will also be passed to the method**.

So nothing changed in 5.3 ... so why would it stop working in my controller? For the record, this is the same with any use where I directly access a controller method. All of the books exist in the DB, and none of their column names changed in any way.

mmacdonald started a new conversation Upgraded A Laravel Project To 5.3 (from 5.2) And It No Longer Passes Object Instances Through Routes... • 1 year ago

So before in 5.2 I had all of my routes looking like this:

//Display a book 
Route::get('books/{book}/display', '[email protected]');

This example would create a URI like "website.com/books/17/display" which would then pass load the book with an ID of 17 in the display page...

This meant on the other side I could use that Book instance and do something with it. I have a function that updates a table with load_counts that would add a count for the book with the ID of '17'. I would access that on the [email protected] function like so:

public function display(Book $book){
        $count = new loadCount();
        $count->book_id = $book->id; //This is the offending line... $book->id doesn't exist now...
        $count->user_id = Auth::user()->id;
        $count->save();
    ...
}

Well, this function is no longer receiving the $book and therefore $book->id = null which causes the $count->save() method to fail because I can't insert a load_count with a book->id of null.

Is there something I am supposed to change in 5.3 to utilize this? Am I going to have to go and update all of the functions in my code that are using this? Is there a 'setting' I can change to use the old way? Why would this feature have been removed?

Thanks for any help you can give!

20th September, 2016

mmacdonald left a reply on CSRF Fails If I Wait More Than 10 Seconds ... • 2 years ago

Lifetime is set to 120 minutes already and I've tried using database as well. Same error.

Only solution I've found so far is disabling the web middleware (but that is not optimal... )

19th September, 2016

mmacdonald started a new conversation CSRF Fails If I Wait More Than 10 Seconds ... • 2 years ago

If I load my page and submit the form right away it 'passes' fine.

If I load my page wait 10+ seconds and submit the form it 'fails' with a CSRF token mismatch error.

Any ideas? I've been at this for hours. I've tried setting the CSRF in my layout head instead of in the form, I've tried using

{{ csrf_field() }}

AND

{!! csrf_field() !!}

I honestly don't see what is going on... beyond posting all of my code is there something specific I can add to this post that will help point out a culprit? Or any ideas off the top of your head?

Also in chrome debug looking at the XSRF-TOKEN field shows a reeeeally long value and the 'echoed out' csrf field in my form is only like 20 chars.... are these the two that are supposed to match?

I'm nearing the point where I'm just going to turn of csrf and stop wasting time.... but I'd rather have the security. I should also mention I have another form that uses the EXACT SAME method, and a nearly identical route and goes through the exact same middleware and it never has this issue. Quite frustrating.

1st September, 2016

mmacdonald left a reply on How To Call A Controller With A Function On The Routes Page AND Forward Parameters? • 2 years ago

@TheNodi Your suggestion worked perfectly!

How often my programming issues can be fixed by one or two words always astounds me.... thanks you SO much! It seemed like i was close but i just couldn't figure out the missing piece!

mmacdonald started a new conversation How To Call A Controller With A Function On The Routes Page AND Forward Parameters? • 2 years ago

I have a program which has many 'levels' and each 'level' has its own function (method) on ONE controller.

I need to dynamically call these based on wildcards in the route. So for example I would have a route called:

example.com/test/1_1/5

Then the route looks something like this:

Route::get('/subject/{level}/{count}', function(){
        $count = Route::current()->count;
        $level = Route::current()->level;

        App::call('App\Http\Controllers\[email protected]' . $level , ['count' => $count]);

 });

Which should be directing to a TestController method called 'subject1_1' and passing the parameter 'count=>5'

Basically on the 'TestController' there are all these functions named subject1_1, subject1_2, subject1_3, subject2 ... etc. And I need to dynamically call them.. so what I'm attempting here is to use the wildcard IN the route and then forward to the correct method...

My biggest issue is that it isn't giving me any error right now.. it is as if my code works, but nothing comes out the other end of the controller method... (it should be returning a view). I know it isn't an issue with the controller method because if I manually change the route to

Route::get('/subject/{level}/{count}', '[email protected]_1');

Then it works perfectly... any ideas where I'm going wrong? What it should do in simple steps:

  • Route is received
  • Wildcards are 'read'
  • TestController is called with the correct method attached
  • When calling that method the second parameter (count) is passed WITH the call

30th June, 2016

mmacdonald started a new conversation AJAX Not Hitting It's Success Function, Despite Success... • 2 years ago

Totally lost here... I'm running an AJAX call to a Laravel Controller. It successfully does everything it's supposed to but it returns to the error function instead of the success function.

Call:

$.ajax({
        url: "testing/saveEdit",
        type: "POST",
        beforeSend: function (xhr) {
            var token = $('meta[name="csrf_token"]').attr('content');
            if (token) {
                return xhr.setRequestHeader('X-CSRF-TOKEN', token);
            }
        },
        data: { words: $wordsArray, list : $list},
        dataType: 'json',
        success: function () {
            $("#mdlEdit").modal("hide");
        },
        error: function () {
            console.log("Save Edit AJAX Error");
        }
    });

Instead of hiding the modal, its logging that error message to the console.

Save Edit Function (on the controller)

public function saveEdit(Request $request){
        $listID = $request->list;
        wordsList::where('wordlist_id','=',$listID)->delete();

        $words = $request->words;
        foreach($words as $word){
            $swing = new wordsList();
            $swing->wordlist_id = $listID;
            $swing->word_id = $word;
            $swing->save();
        }
    }

So (this is a swing table) it's deleting all the old records for this 'list' and creating new records for this 'list'. And I check the DB and it does exactly that... with no errors. It's only on the javascript end that there is an error. But it doesn't throw one, other than the simple one I put in there.

Any idea why it's hitting the Error response, instead of the Success one?

Thanks!

23rd June, 2016

mmacdonald left a reply on Echo A Single Object WITHOUT Foreach • 2 years ago

@willvincent Fantastic! That was the ticket there! I nearly had it, just needed to treat it as an array before I returned it, apparently...

Thanks very much!

mmacdonald left a reply on Echo A Single Object WITHOUT Foreach • 2 years ago

@snapey @rookwood I'm familiar with the count method, but I need to use DB::select ('raw query') for a couple queries (to make them more straightforward) and I don't think it would work quite the same... Like this:

$dailyReads = DB::select('SELECT COUNT(*) AS "count" FROM load_counts WHERE MONTH(date) = MONTH(NOW()) AND YEAR(date) = YEAR(NOW()) AND DAY(date) = DAY(NOW());');

Would I just remove the count aggregate from INSIDE the query and add it to the end? Or will ->count not work on a DB::select ?

I'm mostly using DB::select for the sake of consistency at this point... I guess I could rewrite those queries.

mmacdonald left a reply on Echo A Single Object WITHOUT Foreach • 2 years ago

Wow... finally post a question and I think i figured it out right after... is this alright? It works... but is there a better way?

<h5>{{ $allTimeReads[0]->count }}</h5>

Basically because allTimeReads is technically an array (even though it only has one item) I need to call it this way.. is there, perhaps, something I can do controller side so it isn't an array anymore?

mmacdonald started a new conversation Echo A Single Object WITHOUT Foreach • 2 years ago

I'm passing an object to my blade view and trying to 'print' it to the screen.

I KNOW this result will only ever be a single item as it's just a count from the DB.

Doing this works:

<h5>
@foreach($allTimeReads as $count)
            {{$count->count }}
@endforeach
</h5>

But the foreach is pointless... I know it will only give one result. But I can't figure out how to print it without a foreach. I tried:

<h5> {{ $allTimeReads }}</h5>
*(gives 'htmlentities() expects parameter 1 to be string' error)*

&& I Tried

<h5> {{ $allTimeReads->count }}</h5>
*(gives 'trying to get property of non-object' error)*

Can't seem to figure out how to google or forum search this question... but I'm sure the answer is dreadfully simple. All my results just end up telling me how to get print WITH a foreach, but i already know that!

2nd June, 2016

mmacdonald left a reply on Added SSL To My Site, Now I Get 404 Without HTTPS:// • 2 years ago

Thanks to everyone who answered!

It actually ended up going all the way back to when I created my server... I kept using the 'default' site that it creates (because apparently I missed the notification that says "don't use the default site") and you can't implement SSL on that site.

I contacted Taylor through Forge help and he pointed that out to me! So i created a new (twin) site, using the same repo and applied SSL to that and it worked perfectly!

So if it helps someone in future, and your SSL isn't working: check if you're still using the 'default' site in forge!

mmacdonald left a reply on Added SSL To My Site, Now I Get 404 Without HTTPS:// • 2 years ago

@ejdelmonico It sounds like the type of thing that Forge would do automatically... but I definitely didn't do it myself, so I'll try it! Any input on how I would do that? I'm assuming nginx has a config or something somewhere... I'll look into it! Thanks for the suggestion!

Edit Your Profile
Update

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