joshgallagher24

joshgallagher24

Member Since 3 Years Ago

Experience Points 24,750
Experience
Level
Lessons Completed 207
Lessons
Completed
Best Reply Awards 1
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.

06 Jul
6 months ago

joshgallagher24 left a reply on Refactor Model Creation

I must of deleted the last part of my Q.

I agree with everything you stated above @Cronix - I did do this also.

However, I was also meant to add: How can I refactor this code so I can include a Foreign Key Constraint in my Shop table.

Example Foreign Key

           $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');

Currently, I cannot do this because the User does not exist.

joshgallagher24 started a new conversation Refactor Model Creation

I have a block of code that I want to refactor.

Code to refactor:

        $shop = ShopApp::shop();

        if (!$shop->user_id > 0) {
            // Save token to shop
            $shop->shop_token = $api->requestAccessToken(request('code'));

            // External API
            $customerShop = $shop->api()->request('GET', '/shop');

            // Create shop user
            $user = new User;
            $user->name = $customerShop->body->shop->shop_owner;
            $user->email = $customerShop->body->shop->customer_email;
            $user->save();

            // Associate the user with the shop
            $shop->user_id = $user->id;
            $shop->save();

            // Login the shop's user
            Auth::login($user);
        } else {
            $shop->shop_token = $api->requestAccessToken(request('code'));
            $shop->save();

            $user = User::where('id', $shop->user_id)->first();

            Auth::login($user);
        }

The User has a 'has one' relationship. I am having problems using things like 'associate' because I need to make an API call to get specific data for the User?

04 Apr
9 months ago

joshgallagher24 left a reply on Policy Issue

Yes, I'm not crazy!

I skipped it in the docs, the solution:

$this->authorize('create', Event::class);

@rin4ik your solution works, however, I think the solution above is more elegant.

joshgallagher24 left a reply on Laravel Scout: Use More Than One Driver?

Using the config() helper. You can set the driver to MySQL in a controller action before doing anything, vice versa.

joshgallagher24 started a new conversation Policy Issue

I have an EventPolicy which defines a create method. This create method only allows an event to be created if the User has provided a contact number.

Event Policy 'create':

    public function create(User $user)
    {
        return $user->contact_number;
    }

Now in my controller I do this:

        $this->authorize('create', auth()->user());

And my AuthServiceProvider:

        'App\Models\Event' => 'App\Policies\EventPolicy',

Now, this should work right? Well, it doesn't. It gives me a 403 - doesn't even reach the Policy?

So the work around is this:

        'App\Models\User' => 'App\Policies\EventPolicy',

Giving the User the EventPolicy - this now works.

However, this does not seem right? Do I have to specify the User has the Event policy? Shouldn't it just work when I pass auth()->user() which returns a User instance?

Or, is this right and I've lost my mind?

09 Mar
10 months ago

joshgallagher24 left a reply on Fractal Paginating Subresources

@imJohnBon Thanks for doing the digging!

Could you elaborate on how you would go about doing this? would I return, let's say 4 authors and if I wanted more I would hit another URL to get them paginated?

08 Mar
10 months ago

joshgallagher24 left a reply on Using ReactJS With Passport?

This thread is very old now, but I saw an email just now!

I usually use Lumen, but sometimes use JWT-Auth - I don't think Laravel Passport is as feature rich as I'd want it, to warrant me using it.

For the SPA, I use Nuxt.js or Vue.js SSR.

The new version of JWT-Auth conveniently comes with middleware that re-authenticates and responds with a valid toke.

I am going to build an API starter kit that uses Lumen and Vue SSR and I'll stick it here when it's done.

06 Mar
10 months ago

joshgallagher24 started a new conversation Laravel Fractal Pagination

Hi all,

I am using Laravel Fractal with one of my API's.

I have a Thread that has many Replies and i want to paginate the Replies. The Replies are an include on the Thread Transformer.

How would I go about paginating a transformers include? Is it possible?

Thanks!

25 Feb
10 months ago

joshgallagher24 left a reply on Artisan Commands All Give Base Table Or View Not Found Error

I have the exact same issue - ran in to it today when re-running migrations.

Can someone explain to me why the "Base table or view not found" exception is thrown ? Is it because, when Laravel is booted the Permission model is hit, before it exists?

The fix suggested above seems messy - is there a way around that ?

01 Feb
11 months ago

joshgallagher24 started a new conversation Heroku Domain And Sub Domain Trouble

Hello all,

I am setting up a site which has a Lumen API and Vue SPA - these are both hosted on Heroku.

(I am using Namecheap)

I have the domain www.example.com - I want to map my SPA to www.example.com and have my API map to www.api.example.com.

For my Vue SPA I give it these details:

Domain name: www.example.com DNS Target: www.example.io.herokudns.com

For my Lumen API I give it these details:

Domain name: www.api.example.com DNS Target: www.api.example.io.herokudns.com

On Namecheap I have a URL Redirect Record with these details:

Host: @ Value: http://www.example.com/ unmasked

Then I have CNAME record with these details:

Host: www Value: www.example.io.herokudns.com TTL: auto

At this point, my Vue SPA points to this domain.

However, When I add my Lumen API CNAME record my API does not point to www.api.example.com.

These are the CNAME record details:

Host: api Value: www.api.example.io.herokudns.com TTL: auto

Can someone tell me why I can not get this working? Is it a limitation? Is there a work around?

I'm new to DNS stuff!

Thanks in advance

09 Jan
1 year ago

joshgallagher24 left a reply on Laravel Passport With VueJS/Axios FrontEnd

It's quite simple.

You'd have a SPA (vue app) and an API (laravel app). You would just send requests to your Laravel API, to get the token and then persist that is localstorage.

Make sure you take care of CORS.

If you don't get me, I'd suggest reading up on SPA's and API's, prototyping, understanding these approaches and then attempting to build the app - as authenticating between a SPA and API is relatively simple and guides are everywhere!

Goodluck.

06 Nov
1 year ago

joshgallagher24 left a reply on Vue.js V-for Help!

Would you suggest a more practical and less intensive way to implement this functionality?

05 Nov
1 year ago

joshgallagher24 left a reply on Vue.js V-for Help!

@sutherland Thanks for the reply.

I thought about using the modulus operator, but it seemed over kill.

The nth child could work - could get messy.

The array of classes are in the article-item component. I was attempting to find the best solution within the component. Maybe I should make a method that using the modulo operator to pull a class from the array?

joshgallagher24 started a new conversation Vue.js V-for Help!

I have a vue component that spits out a list of articles. I want to apply color classes to these articles.

in the article-item component I have an array of classes:

    data () {
      return {
        titleColors: [
          'article-item__title--green',
          'article-item__title--pink',
          'article-item__title--purple',
          'article-item__title--blue'
        ]
      }
    }

The problem is, i can only add these classes to the first 4 articles that are rendered as the array length is 3.

Is there anyway I can apply these classes to the first 4 articles, and then reset the v-for index?

This is where I am looping through the articles:

<article-item v-for="(article, index) in articles.articles" :article="article" :key="article.id" :index="index" :length="articles.articles.length"></article-item>

Any help would be much appreciated!

28 Oct
1 year ago

joshgallagher24 started a new conversation Lumen Fratcal Testing Error

Hello all,

I am testing features in my application and have ran into a problem. I have wrote this feature test:

public function a_collection_of_articles_are_returned_paginated()
    {
        $user = factory(User::class)->create();
        factory(Article::class, 25)->create();
        $genArticle = factory(Article::class)->create([
            'title' => 'Some title',
            'slug' => 'some-title',
        ]);

        $this->json('GET', '/articles?page=6')
            ->seeJson([
                'data' => [
                    'title' => $genArticle->title,
                    'slug' => $genArticle->slug,
                    'teaser' => $genArticle->teaser,
                    'body' => $genArticle->body,
                    'created_at' => $genArticle->created_at,
                    'updated_at' => $genArticle->updated_at,
                    'user' => [
                        'data' => [
                            'name' => $user->getFullName(),
                        ]
                    ]
                ],
                'meta' => [
                    'pagination' => [
                        'total' => 26,
                        'count' => 1,
                        'per_page' => 5,
                        'current_page' => 6,
                        'total_pages' => 6,
                        'links' => [
                            'previous' => 'http://joshuagallagherapi.dev/articles?page=5',
                        ]
                    ]
                ]
            ])
            ->assertResponseStatus(200);
    }

However, when I run it, I get this error from PHPUnit:

There was 1 failure:

1) Tests\Feature\ArticleTest::a_collection_of_articles_are_returned_paginated
Unable to find JSON fragment ["data":{"body":"Repudiandae ullam praesentium aut totam dolores. Consectetur doloribus temporibus unde unde est pariatur quas. Ea saepe rem quia sed voluptas quia aut. Facilis et error ea velit rerum aut labore.","created_at":"28\/10\/17","slug":"some-title","teaser":"Odio deserunt molestiae soluta sunt adipisci ipsam. Dolor sint fugit perspiciatis est quis dignissimos maxime. Magni laudantium expedita aperiam. Quos odio rem dolorem magnam accusamus sunt non.","title":"Some title","updated_at":"28\/10\/17","user":{"data":{"name":"Warren Corwin"}}}] within [{"data":[{"body":"Repudiandae ullam praesentium aut totam dolores. Consectetur doloribus temporibus unde unde est pariatur quas. Ea saepe rem quia sed voluptas quia aut. Facilis et error ea velit rerum aut labore.","created_at":"28\/10\/17","slug":"some-title","teaser":"Odio deserunt molestiae soluta sunt adipisci ipsam. Dolor sint fugit perspiciatis est quis dignissimos maxime. Magni laudantium expedita aperiam. Quos odio rem dolorem magnam accusamus sunt non.","title":"Some title","updated_at":"28\/10\/17","user":{"data":{"name":"Warren Corwin"}}}],"meta":{"pagination":{"count":1,"current_page":6,"links":{"previous":"http:\/\/localhost\/articles?page=5"},"per_page":5,"total":26,"total_pages":6}}}].
Failed asserting that false is true.

I believe I am getting this error because Fractal returns the data differently, but I am unsure on how to get the data to comply with the seeJson method.

Any help would be appreciated.

26 Oct
1 year ago

joshgallagher24 started a new conversation Testing Fractal Transformer In Lumen

This is Lumen specific.

I am currently creating an API with spatie's package fractalistic.

I am building it using TDD, but I am finding it hard to find the best method of testing them.

My first approach was to create a feature test for getting a collection of articles from the index endpoint.

ArticleTransformer.php

<?php

namespace App\Transformers;

use App\Models\Article;

class ArticleTransformer extends Transformer
{
    /**
     * Transform the given article collection into JSON.
     *
     * @param  Article $article
     * @return array
     */
    public function transform(Article $article)
    {
        return [
            'title' => $article->title,
            'slug' => $article->slug,
            'teaser' => $article->teaser,
            'body' => $article->body,
            'created_at' => $article->created_at,
            'updated_at' => $article->updated_at,
        ];
    }
}

ArticleTest.php

<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use App\Models\Article;

class ArticleTest extends TestCase
{
    /**
     * @test
     */
    public function a_collection_of_articles_are_returned_as_json()
    {
        factory(User::class)->create();
        $articles = factory(Article::class, 4)->create();

        $this->json('GET', '/articles')
            ->seeJsonStructure([
                'data' => [[
                    'title',
                    'slug',
                    'teaser',
                    'body',
                    'created_at',
                    'updated_at'
                ]]
            ])
            ->assertResponseStatus(200);
    }
}

In ArticleTest.php, I use "seeJsonStructure" to test that the structure is correct, I use this because Lumen's "seeJson" requires an array to be passed - fractal returns json wrapped in 'data'. However, I unsure if theres a better approach like testing a Transformer directly?

Anybody have any experience testing transformers?

23 Jun
1 year ago

joshgallagher24 left a reply on Wrapping Validation Errors In 'data'

Thanks @quickliketurtle.

I decided in the end to implement form requests as it looked cleaner in my controller methods.

22 Jun
1 year ago

joshgallagher24 left a reply on Laravel - Is It Possible To Learn It In A Few Weeks?

@teckel Laravel is an amazing Framework! I know people with basic PHP knowledge chuck out a basic blog application in a week. Laravel is simple to use, unless you are building a complex application with many different. Its not Laravel's fault if someone is not up to standards with correct practices and understands the concepts that come along with software development.

That is why you have the good coders and the highly paid software developers. it's a different league and takes time to get promoted.

joshgallagher24 started a new conversation Wrapping Validation Errors In 'data'

Hi all,

I have a validator in my Lumen project, specifically in my auth controller sign up method. It returns errors like this:

{
    "name": [
        "The name field is required."
    ],
    "email": [
        "The email field is required."
    ],
    "password": [
        "The password field is required."
    ]
}

But I would like them returned like this:

'"data" => [
    {
    "name": [
            "The name field is required."
        ],
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
]

Anyone know how to do this in Lumen? I know in Laravel you can extend the form requests class, but that is not available in Lumen.

19 Jun
1 year ago

joshgallagher24 left a reply on Fractal Include

Just for anyone who stumbles upon this, I found the fix.

It was a bad problem of me not reading the docs provided by spatie!

If you want to include meta data, use this method:

addMeta([
    'token' => 'jumbledjwt'
])

Output:

{
    "data": {
        "id": "f45c9d38-d64c-4489-8b23-2840a485f3f5",
        "email": "[email protected]"
    },
    "meta": {
        "token": "jumbledjwt"
    }
}

joshgallagher24 left a reply on How Do You Determine If The Code Quality Is Good Or How Can I Write Code In Good Way?

@alenabdula I agree.

I cannot count the amount of times I have taken an application and started from scratch to build it better. Every time, it comes out better.

Also, try prototyping. build the app and get it working, then create the final version based off of that design but refactor. This way, you will see bad design decisions in the prototype and be able to act upon them.

joshgallagher24 left a reply on How Do You Determine If The Code Quality Is Good Or How Can I Write Code In Good Way?

Understand OOP.

If you understand OOP, you will write code in a better more structured way. My lecturer said that learning a language is not key, but understanding how to design applications, how to structure modules and the relationships between these modules.

Then, start exploring design patterns. it will take time, but over time you will start seeing where to use these patterns to clean up code.

It not the most in depth explanation, but it should point you in a good direction.

joshgallagher24 left a reply on How To Calculate Time For Given Project?

Normally, I base it off of previous projects I've done. So, if someone comes to me asking for a news website and I have built a personal blog before using Laravel for arguments sake. I can base my project completion date off of the blog I built plus extra features. Then, usually I add a week or two on the end to make up for anything that goes wrong.

18 Jun
1 year ago

joshgallagher24 left a reply on Object Oriented Design Technique Tips And Tricks

Over the last year, my comp sci lecturer has sworn by the client + server design.

joshgallagher24 left a reply on How To Access Vuex Module Actions From A Component

Firstly import 'vuex' into your component.

Then, in your components method property use:

...mapActions([ Action names here ])

joshgallagher24 started a new conversation Fractal Include

Hi all,

I am developing a small API using Lumen, JWT Auth and Fractal. I am having trouble implementing some functionality within fractal.

I am returning a user using a transformer, however, in some controller methods I want to include the generated token.

The method I want to do this in:

    public function store(Request $request)
    {
        $this->validateUser($request);

        $user = new User;
        
        $user->email = $request->email;
        $user->password = bcrypt($request->password);

        $user->save();

        $token = $this->jwt->attempt($request->only('email', 'password'));

        return fractal()
            ->item($user)
            ->transformWith(new UserTransformer)
            ->toArray();
    }

How would I take the "$token" variable and add it o the transformer output?

I would like the structure to be on the lines of:

{
    "data": {
        "id": "05720397-c625-4be6-a52f-10e85eb9de5b",
        "email": "[email protected]"
    },
    "meta": {
    "token": Token here
    }
}

Thanks in advance!


16 Mar
1 year ago

joshgallagher24 left a reply on Problem With Laravel Mix

I just found it - skipped over it!

For anyone else using Sass with fonts or is having problems with URL rewriting add this:

   .options({
      processCssUrls: false
   });

joshgallagher24 started a new conversation Problem With Laravel Mix

Hi everyone!

I am using Laravel Mix in a project outside of Laravel - a static website. However, I am having an issue with the config.

I have fonts in a font folder, which I add through a SASS file as shown below:

@font-face 
    font-family: 'Graphik-bold'
    font-weight: 500
    src:  url('../fonts/GraphikSemibold.woff') format('woff')

@font-face 
    font-family: 'Graphik-reg'
    font-weight: 300
    src:  url('../fonts/GraphikReg.woff') format('woff')

Here, in the paths I set "../fonts/GraphikSemibold.woff", however, upon compilation this path is changed to "/fonts/GraphikSemibold.woff".

How do I stop Laravel Mix from changing the file path?

13 Feb
1 year ago

joshgallagher24 left a reply on Passport - Customising Token Response

@cisco The class I have to edit is not part of Passport - it is part of the League OAuth package.

The specific class is 'PasswordGrant.php'. I have looked and I am not sure how to implement it still.

11 Feb
1 year ago

joshgallagher24 started a new conversation Passport - Customising Token Response

Hi all,

I am working on an API at the moment and have hit a brick wall. I am using Passport with the 'Password' grant type.

I want to return the user's username with the access tokens, however, I am not sure how to.

For example, currently this is returned:

  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "token omitted",
  "refresh_token": "token omitted"
}

However, I would like this to be returned instead:

  "token_type": "Bearer",
  "expires_in": 31536000,
  "access_token": "token omitted",
  "refresh_token": "token omitted",
    "user": {
        "username": "a username"
    }
}

Thanks in advance!

21 Jan
2 years ago

joshgallagher24 left a reply on Forum Help

Ok, if I go with duplicate posts how can I deal with them?

If a user posts a post called "laravel" and another user posts "laravel" - the exact same title. In this instance, if the user clicked on either one of these posts, they would be directed to the latest one only. This would only be a problem with slugs - which is what I want to use.

How would I overcome this in an API design for an SPA?

20 Jan
2 years ago

joshgallagher24 left a reply on Getting Too Many Requests Error On API

You should not comment out this middleware. Imagine, if I decide to attack your API now - it will sink. You are not limiting the amount of requests that can be made to it, thus enabling someone to send millions of requests if they wanted to.

18 Jan
2 years ago

joshgallagher24 started a new conversation Forum Help

Hello everyone,

I am building out a forum, and wanted your feedback on an area. Should I allow duplicate posts? For example, someone creates a post called 'what is laravel?' and then 2 months down the road someone posts the exact same thing. Should I allow this, or force them to post in an old thread?

Thanks!

14 Jan
2 years ago

joshgallagher24 left a reply on Don't Want To Use Vue In Laravel 5.3

Yes, just remove it! Then, just use blade templates etc.

16 Dec
2 years ago

joshgallagher24 left a reply on Can You Help Me To Rank Up My Website??

Of course. Any clients that come my way, I'll forward them to you. I don't need them.

11 Dec
2 years ago
08 Dec
2 years ago

joshgallagher24 left a reply on Laravel 5.3 Passport For Mobile Client App

In response to storing the client Id and secret in your app. You can store the client id in the manifest file and then create some middleware to inject the secret on every request. Do this for both SPA and mobile apps. As for the tokens being pruned, you don't have to. It is an optional setting that can be turned on or off I believe.

04 Dec
2 years ago

joshgallagher24 left a reply on Do I Have To Create Password Reset Routes?

I found the routes in Router.php and implemented them!

joshgallagher24 left a reply on Do I Have To Create Password Reset Routes?

I'm creating an API so I don't want to run that. It will bloat up the project. How do u go about creating the routes, because the methods are in a trait not the controller?

joshgallagher24 left a reply on Do I Have To Create Password Reset Routes?

I have and they are not listed. However, I though they come pre-installed?

joshgallagher24 started a new conversation Do I Have To Create Password Reset Routes?

Hi all,

I am creating an API and have come across an issue I don't really understand. I am setting up password resets to work with my api, but when I post through to the password/reset route in Postman with an email address i get an 'NotFoundHttpException'.

Do I have to create these routes manually, and how when I am using a trait with no available methods in my controller?

Thanks!

joshgallagher24 left a reply on How To Configure Password Resets For An API

When I post to 'myapp.dev/password/reset' within postman with the correct headers and the users email I get a 'NotFoundHttpException'.

joshgallagher24 started a new conversation How To Configure Password Resets For An API

Hi all,

I just wanted some help on how I could configure the password reset functionality into an API. I am not to sure on how to achieve this, because it is built around views etc.

Any help would be appreciated!

29 Nov
2 years ago

joshgallagher24 left a reply on Temporarily Lock A User Into A Certain Route

Personally, I would go with what you have suggested. I would add a column to your Users table where you would set it to true if the user was required to change their password. Then, couple this with middleware and check this field on all routes you do not want the user to navigate to.

Other than that, I do not know of any other way to achieve this. Also, I do not think this is re-creating the wheel so it should be all good!

27 Nov
2 years ago

joshgallagher24 left a reply on API Authentication (with Passport)

@adiachenko I've been speaking with Alex Bilbie - the creator of PHP's OAuth2 Lib. I clarified with him that, firstly using the Password Grant for a first party SPA was correct which he agreed upon. However, I am awaiting his reply on the cookie situation.

I am in two minds about the cookie use, because in either situation - cookie or no cookie we still create angles of attack through CSFR and XSRF.

I am still messing around with this concept, and I will push my project up soon so you all can give feedback and PR's. I am, also hoping that I can have a package done in the coming weeks to support this functionality.

Finally, to address what you have said are you referring to cross domain cookies?

joshgallagher24 left a reply on Passport Grant Client- Unsupported Grant Type Error

Double check in your DB that you're not using the 'Personal Access Token' that is auto generated by Laravel Passport.

25 Nov
2 years ago

joshgallagher24 left a reply on API Authentication (with Passport)

Hello all,

The PR I was trying to push through was closed. here it is: PR.

However, I will try and create a package out of this implementation! I'm not sure when I will have time due to Uni.

Do you all agree that this should be a package, or should we self implement this functionality on a per project basis?