GlenUK

GlenUK

Member Since 6 Months Ago

Experience Points
16,210
Total
Experience

3,790 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
123
Lessons
Completed
Best Reply Awards
5
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

Level 4
16,210 XP
Apr
03
1 day ago
Activity icon

Started a new Conversation Relationship Loading

Hello,

I have a model that has 15 relationships. The model is about 20 fields, and each relationship has just a handful of fields.

I have around 700 records, and loading all these takes around a minute.

I am just passing the model to the view, and accessing the relationships like $model->relationship()->fieldName

I'm really hoping someone can advise on a better way to do this, because 1 minute will be too long - especially when the spreadsheet I am trying to replace takes seconds.

Please help :)

Apr
02
2 days ago
Activity icon

Replied to Create Method On Model Relationship

Ignore me, I haven't saved the parent model...

Activity icon

Started a new Conversation Create Method On Model Relationship

I have a Store and an Address with a one to one relationship.

            $store->address()->create([
                'address_1' => $storeData[50],
                'address_2' => $storeData[51],
                'address_3' => $storeData[52],
                'city' => $storeData[53],
                'county' => $storeData[54],
                'post_code' => $storeData[55],
                'trading_as' => $storeData[56],
            ])

Shouldn't this set the store_id for the newly created address? Currently, It's failing with store_id cannot be null but I thought I was doing it correctly from the docs.

The models:

Store:

public function address()
{
    return $this->hasOne(Address::class);
}

Address:

public function store()
{
    return $this->belongsTo('App\Store');
}
Mar
26
1 week ago
Activity icon

Replied to Dependancy Injection

I wasn't resolving the class through the container

app(Populator::class)

Thanks for your help.

Activity icon

Replied to Dependancy Injection

It still does not work, I put it into the ASP with:

    public function boot()
    {
        $this->app->bind(Populator::class, function ($app) {
            return new Populator(new SeedData());
        });

    }

But initialising (new Populator) still gives Too few arguments to function error.

Activity icon

Replied to Dependancy Injection

@jlrdw I have this use statement, if that's what you mean:

use App\Helpers\SeedData;

It works if I call it like this: (new Populator(new SeedData)) but I wanted to avoid passing in the parameter.

Activity icon

Started a new Conversation Dependancy Injection

Hello,

I have this class constructor:

    public function __construct(SeedData $seedData)
    {
        $this->techSupportList = $seedData::$TECH_SUPPORT;
    }

I see this from the laravel docs:

There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.

So my understanding is $seedData would be an instance of the SeedData class, but my code complains I have not passed in the parameter. How far off the mark am I with this and what's the correct way to do what I wish to achieve here.

Mar
14
3 weeks ago
Activity icon

Started a new Conversation Testing Model Relationships

Hello,

I have a test as such:

    public function testStoreIsAssociatedToRelatedModel($class, $method)
    {
        $store = factory(Store::class)->create();
        $store->$method()->associate(factory($class)->create());
        $this->assertInstanceOf($class, $store->$method);
    }

Using a data provider, I pass in the class and a method and expect this to fail if the relationship I have defined on the model is wrong.

Here is one such relationship, on my model:

    public function storeType()
    {
        return $this->belongsTo(StoreStatus::class);
    }

I have made a mistake here and defined the StoreStatus relationship with the ->storeType method, so my test should fail - but it does not.

I checked this in tinker. I span up a model using a factory, associated the model with a StoreType model

 $aStore->storeType()->associate(factory(App\StoreType::class)->create())

I called the ->storeType method - and to my surprise, it returned a StoreType instance. I noted the ID number of the parent model and restarted tinker and called ->storeType again, this time it returned an instance of StoreStatus.

Can anyone explain what is going on here, out of interest?

Mar
11
3 weeks ago
Activity icon

Replied to Database / Eoquent Testing

I just want to test the whole model and its relationships and the factory does that. The StoreFactory also calls all the other factories via the model's->save() and ->associate() methods so it just seemed like an easy way. I am a beginner though.

I have only really created the database and models, so I don't use the factory anywhere else. I wanted to write some database/model tests before moving on to building the back end system.

Activity icon

Started a new Conversation Database / Eoquent Testing

I've created a model with a dozen or so relationships and a factory that spins up a new model and one of each relationship.

I want to write some tests for this... So far all I have is a checking the factory creates an entry in the database:

    /** @test */
    public function StoreFactoryCreatesADatabaseEntry()
    {
        factory(Store::class)->create();
        $this->assertCount(1, Store::all());
    }

What other tests would be good? Maybe calling each of the relationship methods from the model and asserting an object is returned?

Mar
08
3 weeks ago
Activity icon

Replied to Factory - Eloquent Realtionships

Looks like I forgot to call the relationship

factory(App\Address::class)->make()->store()->associate($store)
Activity icon

Started a new Conversation Factory - Eloquent Realtionships

Hello,

I have two models:

Store hasOne Address / Address belongsTo store

When I call the Store factory, I want to create a new address and associate it with the Store.

$factory->afterMaking(Store::class, function ($store, Faker $faker) {
    factory(App\Address::class)->make()->associate($store);
});

this code gives me BadMethodCallException with message 'Call to undefined method App/Address::associate() error in tinker. Can anyone help?

Feb
07
1 month ago
Activity icon

Awarded Best Reply on Delete Relationships In Update Method

Via the store method on your controller, delete all the Timesheet items and then assign them from scratch from the HTTP request.

If you need to update the original timesheet items (so they have the same ID in the database, for example) then it's a little trickier. I personally use a helper class, such as this one (by patoui):

https://gist.github.com/patoui/cbd8a6370d8786565f2bb0efdae55867

I then call this from the update method of my controller as such:

(new HasManyUpdater($Timesheet_instance, Timesheet_item::class))->update($request->timesheet_items);

Essentially, it grabs the ID of the existing nested items before it updates each nested items, storing the ID of the updated nested item. It then compares the IDs of the items that existed before the update and the array of IDs that got updated. It then iterates over the IDs that remain and deletes them.

Feb
06
1 month ago
Activity icon

Replied to Delete Relationships In Update Method

Via the store method on your controller, delete all the Timesheet items and then assign them from scratch from the HTTP request.

If you need to update the original timesheet items (so they have the same ID in the database, for example) then it's a little trickier. I personally use a helper class, such as this one (by patoui):

https://gist.github.com/patoui/cbd8a6370d8786565f2bb0efdae55867

I then call this from the update method of my controller as such:

(new HasManyUpdater($Timesheet_instance, Timesheet_item::class))->update($request->timesheet_items);

Essentially, it grabs the ID of the existing nested items before it updates each nested items, storing the ID of the updated nested item. It then compares the IDs of the items that existed before the update and the array of IDs that got updated. It then iterates over the IDs that remain and deletes them.

Activity icon

Replied to Permission Brainstroming

Could you expand on what you are trying to achieve? What is a permission? Is it something you have set up as a many-to-many relation ship? Is it a field within the teams table? etc.

Feb
02
2 months ago
Activity icon

Commented on Prime Factors Kata

How does he get auto-complete on test? When I type that into phpstorm I get some plethora of options (i.e: public function runTest() {...})

Jan
27
2 months ago
Activity icon

Replied to Many To Many - Retrieve Multiple Records Through Pivot Table

What error do you get with the first statement?

Activity icon

Replied to Creating A Back-end And Front-end

When you refer to two different front ends, do you mean two different pages?

Everything you describe here is pretty standard stuff for Laravel and so if you follow the framework conventions you should have no issues.

I recommend you look at the https://laracasts.com/series/laravel-6-from-scratch course

Or, alternatively, this YouTube: https://www.youtube.com/watch?v=eD4yMI-IR8g&list=PLpzy7FIRqpGC8Jk6gyWdSVdxCVXZAsenQ

Jan
13
2 months ago
Activity icon

Replied to Sharing Model With All Views Via ASP Breaks Unit Tests

@tykus Would that be in the AppServiceProvider class?

Activity icon

Replied to Sharing Model With All Views Via ASP Breaks Unit Tests

@tykus

Thank you, is there a better way I should be sharing a model to all views that does not break migrating/unit tests?

Activity icon

Started a new Conversation Sharing Model With All Views Via ASP Breaks Unit Tests

Hello,

Since I added the following to my AppServiceProvider.php class:

    public function boot()
    {
        View::share('statuses', Status::all()); 
    }

All of my unit tests now error out with the following returned from phpunit:

57) Tests\Feature\StaffTest::staffValidationActiveMustBoolean
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: statuses (SQL: select * from "statuses")

Caused by
PDOException: SQLSTATE[HY000]: General error: 1 no such table: statuses

My tests are using the RefreshDatabase trait and are configured to use sqlite in memory for the testing enviroment via phpunit.xml:

        <server name="DB_CONNECTION" value="sqlite"/>
        <server name="DB_DATABASE" value=":memory:"/>

Is it possible to resolve this without deleting the call the View facade every time?

Activity icon

Replied to Excel Export With Date Format

@bhhuassain

Looking at the error, I believe you are implementing the WithMapping interface

class AccountExport implements WithMapping

If this is the case, you will need to write the method that the WithMapping interface dictates; such as this example from the docs:

{    
    /**
    * @var Invoice $invoice
    */
    public function map($invoice): array
    {
        return [
            $invoice->invoice_number,
            $invoice->user->name,
            Date::dateTimeToExcel($invoice->created_at),
        ];
    }
}

See: https://docs.laravel-excel.com/3.1/exports/mapping.html

If this does not resolve your issue, please repost your entire class with your error.

Jan
11
2 months ago
Activity icon

Awarded Best Reply on What's Next After Laravel 6 From Scratch

What do you want to learn next? If you wish to continue to expand your knowledge of Laravel, then you might consider:

https://laracasts.com/series/intermediate-laravel

Or, something from YouTube which I highly recommend is:

https://www.youtube.com/watch?v=_z9nzEUgro4&list=PLpzy7FIRqpGD5pN3-Y66YDtxJCYuGumFO

If you want to learn Test Driven Development then that course might be an option:

https://laracasts.com/series/build-a-laravel-app-with-tdd

Or, perhaps you want to see how a professional developer works on a current project:

https://laracasts.com/series/building-laracasts

Alternatively, now that you have some back end server knowledge,m you may wish to get the basics of a front end frame work under your belt:

https://laracasts.com/series/learn-vue-2-step-by-step

Activity icon

Replied to What's Next After Laravel 6 From Scratch

What do you want to learn next? If you wish to continue to expand your knowledge of Laravel, then you might consider:

https://laracasts.com/series/intermediate-laravel

Or, something from YouTube which I highly recommend is:

https://www.youtube.com/watch?v=_z9nzEUgro4&list=PLpzy7FIRqpGD5pN3-Y66YDtxJCYuGumFO

If you want to learn Test Driven Development then that course might be an option:

https://laracasts.com/series/build-a-laravel-app-with-tdd

Or, perhaps you want to see how a professional developer works on a current project:

https://laracasts.com/series/building-laracasts

Alternatively, now that you have some back end server knowledge,m you may wish to get the basics of a front end frame work under your belt:

https://laracasts.com/series/learn-vue-2-step-by-step

Activity icon

Replied to Excel Export With Date Format

@bhhuassain, Can you include the code where you are formatting the date and also the error you are getting?

If you want to format your column, you can implement the WithColumnFormatting interface and write a columnFormats() method that returns an array:

Please see: https://docs.laravel-excel.com/3.1/exports/column-formatting.html

Jan
10
2 months ago
Activity icon

Replied to API Route Accessible For Both: Authenticated And Unauthenticated

You could try checking if the HTTP_AUTHORIZATION key exists in $_SERVER to identify if the user is auth'd and then call the middleware. If the user is not auth'd you can omit the middleware and use the 'Auth::check()` in your logic.

public function __construct()
{
    if (array_key_exists('HTTP_AUTHORIZATION', $_SERVER))   
    {
        $this->middleware('auth:api');
    }   
}

//...

public function myFunction()
{
    if (Auth::check())
    {
        // Code if user is auth'd
    }
    else
    {
        // Everyone else
    }
}

If you use this approach, ensure you are not calling the middleware elsewhere, such as the route.

Activity icon

Replied to Eloquent 3 Table Query

@jredli93 , apologies, with is a facade, I updated my response.

Please note, ->get() returns a collection from a query builder object, so you would not do that twice for a single query like I have.

Further more, you can use php artisan tinker from the command line to play with the query and tweak it.

Activity icon

Awarded Best Reply on Eloquent 3 Table Query

auth()->user() will get the currently logged-in user, you can work through the relationships from there:

You should set up the inverse relationship for the category model.

Category.php

public function recipes() 
{
    return this->hasMany(Recipes::class);
}

To do the query you can chain the relationships as such - using the with facade to include a recipes' category.

$user_id = auth()->user()->id;

$results = User::with('recipes.category')->where('id', $user_id)->get()

You could then do a groupBy() and then do a count.

$results->select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();

You could do it in one go, of course, but I tried to highlight each step.

Activity icon

Replied to Eloquent 3 Table Query

auth()->user() will get the currently logged-in user, you can work through the relationships from there:

You should set up the inverse relationship for the category model.

Category.php

public function recipes() 
{
    return this->hasMany(Recipes::class);
}

To do the query you can chain the relationships as such - using the with facade to include a recipes' category.

$user_id = auth()->user()->id;

$results = User::with('recipes.category')->where('id', $user_id)->get()

You could then do a groupBy() and then do a count.

$results->select('id', \DB::raw("count(id)"))->groupBy('category_id')->get();

You could do it in one go, of course, but I tried to highlight each step.

Activity icon

Awarded Best Reply on No Query Results For Model [App\Posts] Error

->get() will return a collection and therefore you can use all the collection methods:

https://laravel.com/docs/6.x/collections#available-methods

So, you can do $posts->count() instead of using count($posts)

You then loop through each $post, which is an instance of the Post model, so you do not need to find it again, you can work directly with the $post.

        $posts = Posts::where('cat_id', $request->cat_id)->get();
        if ($post->count() != 0){
            foreach ($posts as $post){
                dd($post);
                $post->delete();
            }
        }

It also looks like you are deleting the same post in the second loop. Which line is it failing on?

Activity icon

Replied to No Query Results For Model [App\Posts] Error

->get() will return a collection and therefore you can use all the collection methods:

https://laravel.com/docs/6.x/collections#available-methods

So, you can do $posts->count() instead of using count($posts)

You then loop through each $post, which is an instance of the Post model, so you do not need to find it again, you can work directly with the $post.

        $posts = Posts::where('cat_id', $request->cat_id)->get();
        if ($post->count() != 0){
            foreach ($posts as $post){
                dd($post);
                $post->delete();
            }
        }

It also looks like you are deleting the same post in the second loop. Which line is it failing on?

Activity icon

Awarded Best Reply on Specify Dynamic Input Fields Based On Condition

So you could count the children on the rows parent and compare that to the condition you have there.

You can use php within the Javascript code using {{ }}

So, you could have something like:

function addRow() {
    if ({{Auth::user()->is_hod == '0'}}) {
        if ($('tbody').children().lengh <  3) {
            // code to add row 
        } else {
            alert('you cannot add a row')
        }
    }
}

Sanity check that code - as I am at work - but that should give you a starting point.

Activity icon

Replied to Specify Dynamic Input Fields Based On Condition

So you could count the children on the rows parent and compare that to the condition you have there.

You can use php within the Javascript code using {{ }}

So, you could have something like:

function addRow() {
    if ({{Auth::user()->is_hod == '0'}}) {
        if ($('tbody').children().lengh <  3) {
            // code to add row 
        } else {
            alert('you cannot add a row')
        }
    }
}

Sanity check that code - as I am at work - but that should give you a starting point.

Jan
09
2 months ago
Activity icon

Replied to Insert Data To A Pivot Table In Laravel Using Query Builder

These are covered in the 'Laravel 6 From Scratch' series on the site or if you want something on youtube, I recommend:

One to one: https://www.youtube.com/watch?v=9yeJ-93B-R4

One to many: https://www.youtube.com/watch?v=_2wJWVQEFAU

Many to many: https://www.youtube.com/watch?v=f7quw05phxs

Activity icon

Replied to Load Relationship Pivot OR Relationship From Route

Hello @cabeeb ,

I believe you want a Model Route Binding on a nested resource. Here is an except from the the docs on that topic:

Nested Resources

Sometimes you may need to define routes to a "nested" resource. For example, a photo resource may have > multiple "comments" that may be attached to the photo. To "nest" resource controllers, use "dot" notation in your route declaration:

Route::resource('photos.comments', 'PhotoCommentController');

This route will register a "nested" resource that may be accessed with URLs like the following: photos/{photos}/comments/{comments}.

If you are not using a resource controller then I believe you would need to define the logic yourself. Here is a recent article on that:

https://pineco.de/binding-relevant-models-to-routes-in-nested-laravel-resources/

Activity icon

Replied to Laravel Policies

@mstrauss That fixed it. thank you.

I did refactor this Policy class when I learned and implemented the authorizeResource() method but must have missed the export.

Activity icon

Replied to Laravel Policies

Thank you guys, I believe the before method on the policy should return true though? Or am I understanding that incorrectly?

Jan
08
2 months ago
Activity icon

Started a new Conversation Laravel Policies

I have a Controller with this method:

public function __construct()
{
    $this->middleware('auth');
    $this->authorizeResource(PurchaseOrder::class, 'po');
}

public function export(Request $request)
{

    $this->authorize('export' );

    $data = $request->validate([
       'dateFrom' => 'required|date',
       'dateTo' => 'required|date',
        'statuses' => 'required|array',
    ]);

    return (new PurchaseOrdersExport($request->dateFrom, $request->dateTo, $request->statuses))->download('PurchaseOrders.'.$request->file_format);
}

And I have a Policy as such:

public function before($user, $ability)
{
    if (in_array('Admin', $user->roles->pluck('name')->toArray()))
    {
        return true;
    }
}

public function export(User $user)
{
    return count(array_intersect($user->roles->pluck('name')->toArray(), [
    ])) > 0;
}

Can anyone assist as to why I am getting a 403 auth rejection reponse when exporting? My user has the Admin user role and thus should be able to access the action.