alanholmes

alanholmes

Senior Developer at Visualsoft

Member Since 6 Years Ago

Coulby Newham

Experience Points
84,130
Total
Experience

870 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
1021
Lessons
Completed
Best Reply Awards
26
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 17
84,130 XP
May
18
1 week ago
Activity icon

Awarded Best Reply on Update Last Login Column In User Table After Successful Login

Hi @jdauphinais

if you look in the \Illuminate\Foundation\Auth\AuthenticatesUsers trait that is included in the login controller (if you are using Laravels auth system).

There is an empty authenticated method, that you could override in the login controller to do some custom actions before the user is redirected.

something like

    protected function authenticated(Request $request, $user)
    {
         $user->update(['last_login' => now()]);
    }
Activity icon

Replied to Make Another Custom App In Laravel Project

Hi @dipcb05

If they are to be completely standalone separate apps, then make them separate apps, and you could host ot on a subdomain or something.

However, if the admin needs to exist within the main app, then that is fine too, you just need to have a way of identifying them from normal users.

There are at least 2 ways that you can do this.

  1. Do a duel model login - this is not something I have done before, but I did find a video series to it before, that I linked to in this post: https://laracasts.com/discuss/channels/laravel/how-do-i-authenticate-two-models

  2. Use something like https://github.com/spatie/laravel-permission to have different roles for users (this is the method I have used, and it works quite well)

Activity icon

Replied to Update Last Login Column In User Table After Successful Login

Hi @jdauphinais

if you look in the \Illuminate\Foundation\Auth\AuthenticatesUsers trait that is included in the login controller (if you are using Laravels auth system).

There is an empty authenticated method, that you could override in the login controller to do some custom actions before the user is redirected.

something like

    protected function authenticated(Request $request, $user)
    {
         $user->update(['last_login' => now()]);
    }
Apr
29
1 month ago
Activity icon

Replied to Predefined Queries Or Field 'sets' On Models?

Hi @geerizzle

You could try using scopes https://laravel.com/docs/7.x/eloquent#query-scopes

I use them often for common filtering clauses, but as it uses the builder, I assume that you can use it to do things like returning which fields.

Apr
22
1 month ago
Activity icon

Awarded Best Reply on How To Return Response 422 Status And Custom Error Message

Hi @norbertho

I have done this on an axios request before

window.axios.put('url', {
}).catch(error => {
    console.log(error.response);
});

so error.response has the actual response rather than just the 422 error thrown

Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

Hi @norbertho

I have done this on an axios request before

window.axios.put('url', {
}).catch(error => {
    console.log(error.response);
});

so error.response has the actual response rather than just the 422 error thrown

Activity icon

Replied to How To Return Response 422 Status And Custom Error Message

hi @norbertho

you just need to pass it as the second param of ->json()

eg:

return response()->json([
            'errors' => "Password does't match",
        ], 422);

Or instead of the 422 you could do this, so you (in future) dont have to remember what 422 is (useful for other areas too)

return response()->json([
            'errors' => "Password does't match",
        ], Response::HTTP_UNPROCESSABLE_ENTITY);
Apr
16
1 month ago
Activity icon

Replied to How Do I Prevent @ From Escaping {{}} Content In Blade

hi @mrkarma4ya

You could try

User: {{ '@' . $user->name }}
Apr
15
1 month ago
Activity icon

Awarded Best Reply on Who To Contact For Documentation Discrepancies ?

Hi @k-web-dev

The Laravel docs are available here: https://github.com/laravel/docs And I have seen plenty of Tweets from Taylor saying people can submit PRs to the docs

Activity icon

Replied to Who To Contact For Documentation Discrepancies ?

Hi @k-web-dev

The Laravel docs are available here: https://github.com/laravel/docs And I have seen plenty of Tweets from Taylor saying people can submit PRs to the docs

Apr
09
1 month ago
Activity icon

Replied to How Do Private Laravel Migration For Database ?

Hi @analien

I don't think there is a way to do what you are after, as it is kind of against the point of refresh which is to completely rebuild the DB from scratch (and only meant to local dev really).

You could use Seeders to will the tables back up with sample data if it is for local development, but it wouldn't be the data that was in there before you ran fresh, but you would always go back to the same starting point with the seeders.

Activity icon

Replied to Parent Child Relationship In Users Table.

@pavinder

If you are wanting to write the sql yourself, it would be something like this:

SELECT users.name, parent.name as parent_name
FROM users
LEFT JOIN users parent ON users.parent_id = parent.id

Or you can use eloquent to do it for you:

$user = User::find(1);
echo $user->name;

$parent = $user->parent;
echo $parent->name;

$children = $parent->children;
$children->each(function($child) {
   echo $child->name;
});

Apr
08
1 month ago
Activity icon

Replied to Parent Child Relationship In Users Table.

Hi @pavinder

There is 2 ways you could do it.

1. Simply have a parent_id on the User model, which for admin users is zero, and for normal users is their admin.

This could then be accessed by a relationship on the user model back to itself:

public function children()
{
    return $this->hasMany('App\User', 'parent_id', 'id');
}

public function parent()
{
    return $this->hasOne('App\User', 'parent_id', 'id');
}

(Note the columns may not be in the right order)

2. Have something like a Company Table that is user to group the users together.

This is what I have in my project, as the admin users are defined by permissions, but one of these users is marked as the "main user" for the company.

Apr
03
1 month ago
Activity icon

Replied to Losing My Mind Trying To Come Up With A Viable Queueing Scheme

I've not actually had to implement any rate limited queues, I just know about them.

Not sure if the example in the code would do it for you, as you set it to only allow X amount (15) every Y seconds (60*15).

The only thing to be aware of, is that it increases the number of attempts of the job, so that might have to be set quite high (or to infinite, if that is possible), as if there ends up being thousands of queues waiting, it could quickly end up marking them all as failed.

Activity icon

Replied to Adding Version Control To A Model

hi @andreboyle

Perhaps something like this if you are wanting to have control over which version is active (with option of switching back)

    /**
     * Returns the Profiles
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function profiles(): \Illuminate\Database\Eloquent\Relations\hasMany
    {
        return $this->hasMany('App\Profile');
    }

    /**
     * Returns the Active Profile
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function activeProfile(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne('App\Profile')
            ->active();
    }

    /**
     * Returns the Draft Profile
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function draftProfile(): \Illuminate\Database\Eloquent\Relations\HasOne
    {
        return $this->hasOne('App\Profile')
            ->draft();
    }

    /**
     * Returns the Archived Profiles
     *
     * @return \Illuminate\Database\Eloquent\Relations\hasMany
     */
    public function archivedProfiles(): \Illuminate\Database\Eloquent\Relations\hasMany
    {
        return $this->hasMany('App\Profile')
            ->archived();
    }

So active is the one that is shown, and draft is the one that has been edited / awaiting approval, and archived is anything that has been active.

So the flow is:

  • Changes are made, which creates a Draft.
  • The draft is approved
  • This marks the existing active as archived
  • Then the draft as active

This is all controlled by a status column on the Profile table (and active, draft and archived are just scopes).

This gives you the option of being able to switch back easily if needed, or have an approval system.

If you are simply wanting to have an audit of any changes, without the need of the above, then you could look at something like https://docs.spatie.be/laravel-activitylog/v3/introduction/ which keeps an audit of model changes

Activity icon

Replied to Losing My Mind Trying To Come Up With A Viable Queueing Scheme

hi @nexxai

Would the rate limiting option on queues help you: https://laravel.com/docs/7.x/queues#rate-limiting

Then you can put all of these requests into the queue, and let it handle the throttling.

To save this filling up the queue for any other tasks, you could also give this job its own queue.

However, if you can only do 15 in 15 mins, then it is likely that this queue is going to get very backlogged, and take a lot of time if you have a lot of users following a lot of users, but I don't see anyway around that if the limit is at twitters end.

Mar
30
2 months ago
Activity icon

Awarded Best Reply on What Is The Best Way To Authorize A Create Policy Depending On Value Of A Field?

Hi @chrisan

That is what I use, I have /profile for the company to manage themselves, which use the company id from the logged in user.

And then for admins, I have companies/{company} to manage the companies and companies/{company}/users to manage the users for that company - and I have extra checks to make sure the user being managed is for the company in the url. (if you are using Laravel 7, it has added a way to do this for you https://laravel.com/docs/7.x/routing#implicit-binding - Custom Keys & Scoping - which from what i understand if you do companies/{company}/users/{user:id} will automatically check that the user belongs to the company - this is useful if like me, you have users that can manage some companies but not others)

I guess that is the same method as having it in the post really, but the main thing is that I have a separate endpoint for a company to manage there own users and for admins to manage other companies users.

I ease the duplication by having them use the same form, but with a different post url, and I extract the validation to a request form class, so that is also shared, and you could also extra the logic for creating the user if it is more complex than just creating/updating on a model.

Activity icon

Replied to What Is The Best Way To Authorize A Create Policy Depending On Value Of A Field?

Hi @chrisan

That is what I use, I have /profile for the company to manage themselves, which use the company id from the logged in user.

And then for admins, I have companies/{company} to manage the companies and companies/{company}/users to manage the users for that company - and I have extra checks to make sure the user being managed is for the company in the url. (if you are using Laravel 7, it has added a way to do this for you https://laravel.com/docs/7.x/routing#implicit-binding - Custom Keys & Scoping - which from what i understand if you do companies/{company}/users/{user:id} will automatically check that the user belongs to the company - this is useful if like me, you have users that can manage some companies but not others)

I guess that is the same method as having it in the post really, but the main thing is that I have a separate endpoint for a company to manage there own users and for admins to manage other companies users.

I ease the duplication by having them use the same form, but with a different post url, and I extract the validation to a request form class, so that is also shared, and you could also extra the logic for creating the user if it is more complex than just creating/updating on a model.

Mar
27
2 months ago
Activity icon

Replied to Problem With Unique Field Validation On Update In Controller

Hi @spiral

for updates you can tell it to ignore the record being updated, see the docs: https://laravel.com/docs/7.x/validation#rule-unique

Activity icon

Replied to What Is The Best Way To Authorize A Create Policy Depending On Value Of A Field?

Hi @chrisan

I have a similar feature (though with a few more levels between admin and super admin).

The way I have done it, is have 2 sections, a 'profile' section for the company, where admin users can add users to their customers, and then the company id is not part of the post data, it is taken directy from the auth()->user() so I just need to check that they are an admin user.

Then I have another section for super admins to manage companies, that also allows for managing users of that each company.

Mar
26
2 months ago
Activity icon

Replied to Disable Redirecting To /home Route After Login For SPA

Hi @untymage

How are you doing the login? if you are using a ajax (json) request, it will return a json response rather than a redirect

        return $request->wantsJson()
                    ? new Response('', 204)
                    : redirect()->intended($this->redirectPath());
Mar
25
2 months ago
Activity icon

Replied to Remove Extra Characters After File Extension

hi @kalimeromk

you could try Str::before($filename, '?')

Mar
18
2 months ago
Activity icon

Replied to How To Deal With "flash Messages" When Using An Api

Hi @luddinus

If you switch to the web middleware for it, then you will be able to set the flash in your controller.

Here is an example of where I have used it:

public function store(StoreReferralRequest $request, CreateReferral $createReferral)
    {
        $referral = $createReferral->fromRequest($request);

        $request->session()->flash('referral_submitted', true);

        return response()->json([
            'success' => true,
            'redirect' => route('referrals.show', $referral)
        ], Response::HTTP_CREATED);
    }

This is getting set, and returning Json with the redirect url to the show page, and my JS does the redirect (as my form is being posted via Ajax), but once the redirect happens, I have access to the referral_submitted flash session to show a message

Activity icon

Replied to How To Deal With "flash Messages" When Using An Api

Hi @luddinus

Tbh, I'm not sure, I have done it via an Ajax call, but I have a web api, that just uses the web middleware rather than the api middleware (that is a separate api for me that is not being used by a browser).

The other option, is that you pass the success message back from the api end point in the JSON, and use your JS to either show the message, or pass it along in the querystring if you are still going to redirect

Mar
17
2 months ago
Activity icon

Replied to How To Deal With "flash Messages" When Using An Api

Hi @luddinus

If you are redirecting in the JS, you can still use your api endpoint to set a flash session, and it will still be available after the redirect.

Mar
16
2 months ago
Activity icon

Replied to Could I Get Data From Blade Views With Components

Hi @mcltano

If you are using Vuejs and Axios to fetch data upon select, then it should be able to return data in any format that you want, and it would just be down to your vuejs to handle that response (whether that be json, html, or whatever) and process it as required.

If you provide some example code of what you have done, I may be able to help you more

Mar
12
2 months ago
Activity icon

Replied to How To Pause Or Delay All Jobs On Horizon Queue

Hi @tindongvatvn

You could try looking at the rate limiting option on queues https://laravel.com/docs/7.x/queues#rate-limiting

I've not yet had to implemt them, but from the docs, its sounds like what you are wanting to do

Mar
10
2 months ago
Activity icon

Awarded Best Reply on How To Test Routes That Are Protected By A Middleware?

@ranx99

As this is a very common test for me, I have had added it to a trait RestrictUnverifiedEmailAccessViaGetRequests which I then include in the required tests (I have similar ones for Post, Put and Delete), and this the trait:

namespace Tests\Feature\Traits;

use App\User;

trait RestrictUnverifiedEmailAccessViaGetRequests
{
    /** @test */
    public function users_with_unverified_emails_cannot_access_via_get()
    {
        $user = factory(User::class)
            ->states('unverified')
            ->create();

        $this->actingAs($user);

        foreach ($this->routesToTest['get'] as $route => $params) {
            $this->get(route($route, $params))
                 ->assertRedirect(route('verification.notice'));
        }
    }
}

Then in my tests, I just have to use the traits, and setup the routes to test, eg:

class DashboardTest extends TestCase
{
    use RefreshDatabase;
    use RestrictGuestAccessViaGetRequests;

    protected $routesToTest = [
        'get' => [
            'dashboard' => [],
        ],
    ];
}

(this is if you used named routes, but you could easily modify)

Activity icon

Replied to How To Test Routes That Are Protected By A Middleware?

@ranx99

As this is a very common test for me, I have had added it to a trait RestrictUnverifiedEmailAccessViaGetRequests which I then include in the required tests (I have similar ones for Post, Put and Delete), and this the trait:

namespace Tests\Feature\Traits;

use App\User;

trait RestrictUnverifiedEmailAccessViaGetRequests
{
    /** @test */
    public function users_with_unverified_emails_cannot_access_via_get()
    {
        $user = factory(User::class)
            ->states('unverified')
            ->create();

        $this->actingAs($user);

        foreach ($this->routesToTest['get'] as $route => $params) {
            $this->get(route($route, $params))
                 ->assertRedirect(route('verification.notice'));
        }
    }
}

Then in my tests, I just have to use the traits, and setup the routes to test, eg:

class DashboardTest extends TestCase
{
    use RefreshDatabase;
    use RestrictGuestAccessViaGetRequests;

    protected $routesToTest = [
        'get' => [
            'dashboard' => [],
        ],
    ];
}

(this is if you used named routes, but you could easily modify)

Mar
09
2 months ago
Activity icon

Replied to How To Test Routes That Are Protected By A Middleware?

@ranx99

I would test middleware using the $this->actingAs($user)->get(route('profile.show')) function to test that the user is not able to access it if they do not meet the conditions of the verified middleware.

So using this method it would be a feature test

Mar
04
2 months ago
Activity icon

Replied to Laravel Airlock With Postman

hi @chrisblackwell

not tried it, but it might be possible with tokens (like for mobile apps) https://laravel.com/docs/7.x/airlock#issuing-mobile-api-tokens

Mar
03
2 months ago
Activity icon

Replied to How To Solve Laravel Union Queries Different Number Of Columns

Hi @aswathi

This shows you how to do unions in Laravel: https://laravel.com/docs/6.x/queries#unions

As the columns are different, you will need to specify for each query the columns to fetch, which can be done using select https://laravel.com/docs/6.x/queries#selects

Feb
26
3 months ago
Activity icon

Awarded Best Reply on Realtime Update With VUE

Hi @mick79

Depending on what data is included in the pusher update, then you could just append it to the questions.

Todo this, you will need to setup a data entry (as you cant, or should be changing props).

And then (assuming its an array), just push the new question onto the array


<script>
    export default {
        props: ['event'],


        data() {
            return {
                  questions: event.questions,
            }
        },

        mounted() {
            console.log('Component mounted.');

            // Enable pusher logging - don't include this in production
            Pusher.logToConsole = true;

            var pusher = new Pusher('*************', {
                cluster: 'eu',
                forceTLS: true
            });

            var channel = pusher.subscribe('my-channel');
            channel.bind('my-event', function(data) {
                // assuming questions is an array
                this.questions.push(data.newQuestion);
            });

        }
    }
</script>

and you would then need to change v-for="question in event.questions" to v-for="question in questions"

Activity icon

Replied to Realtime Update With VUE

Hi @mick79

Are you still passing the event prop in? as it is still needed to get the initial values

Activity icon

Replied to Realtime Update With VUE

Hi @mick79

so this.questions.push(data.newQuestion); was assuming there was something like newQuestion in the data, but it appears that there isnt that.

From the data returned looks like it might be message?

so this.questions.push(data.message);

If that is not the full question object that you need, but all the data is returned already, you could build up the object

this.questions.push({
    created_at: data.created_at,
    question_token: data.question_token,
    // etc
});

Or you would need to make sure that the new question (as I assume that is what you are trying to do) is passed in the pusher event, otherwise, if the data is not present, or available to be in the pusher object, you then have 2 options, to reoload the page like you were, or to fetch all the questions again via an ajax call

Activity icon

Replied to Realtime Update With VUE

Hi @mick79

Depending on what data is included in the pusher update, then you could just append it to the questions.

Todo this, you will need to setup a data entry (as you cant, or should be changing props).

And then (assuming its an array), just push the new question onto the array


<script>
    export default {
        props: ['event'],


        data() {
            return {
                  questions: event.questions,
            }
        },

        mounted() {
            console.log('Component mounted.');

            // Enable pusher logging - don't include this in production
            Pusher.logToConsole = true;

            var pusher = new Pusher('*************', {
                cluster: 'eu',
                forceTLS: true
            });

            var channel = pusher.subscribe('my-channel');
            channel.bind('my-event', function(data) {
                // assuming questions is an array
                this.questions.push(data.newQuestion);
            });

        }
    }
</script>

and you would then need to change v-for="question in event.questions" to v-for="question in questions"

Feb
25
3 months ago
Activity icon

Awarded Best Reply on Route::view Name

Hi @scooby

It has created a route, but you have not told it what to name itself.

If you want it to be a named route, you need to do this

Route::view('/welcome', 'welcome')->name('welcome');

See: https://laravel.com/docs/6.x/routing#named-routes

Activity icon

Replied to Route::view Name

Hi @scooby

It has created a route, but you have not told it what to name itself.

If you want it to be a named route, you need to do this

Route::view('/welcome', 'welcome')->name('welcome');

See: https://laravel.com/docs/6.x/routing#named-routes

Feb
24
3 months ago
Activity icon

Replied to Sending A Welcome Email After User Verify His Account

hi @nana-odai

It looks like you might not have imported the Illuminate\Auth\Events\Verified class in your listener, so it is looking for a Verified class within the App\Listeners namespace

Feb
17
3 months ago
Activity icon

Replied to Extending/Replacing A Core Trait

hi @booni3

I dont think there is a way you can fully replace it in core, as the way traits are loaded.

However, for traits that you are including in your own app files, you certainly can.

So, for example, in my app I am using Spaties permissions package, but I wanted to do some custom things when calling actions like assignRoles.

This package provides a HasRoles trait to include in your models, so that I did was create my own HasRoles trait, and then use the spatie one within my trait.

When you include a trait, you can have it rename/alias any of the methods within it, which will allow you to replace that method with a method of the same name, but will allow you to retain the option to call the original method as well (kind of similar to extending a parent class, and using parent::method).

Example:

namespace App\Permissions;

use Spatie\Permission\Traits\HasRoles as SpatieHasRoles;

trait HasRoles
{
    use SpatieHasRoles {
        assignRole as protected spatieAssignRole;
        syncRoles as protected spatieSyncRoles;
    }

    public function assignRole(...$roles)
    {
        $this->spatieAssignRole(...$roles);

        // custom logic here

        return $this;
    }

Activity icon

Replied to Proof Of Concept Of Dynamic Relationships Loading

Hi @ekhawlah

The include[]= option is the route I have gone down, as it is a feature available in the package I am using for these API endpoints: https://docs.spatie.be/laravel-query-builder/v2/features/including-relationships/

I think it works pretty well, means you only load what you need when you need it

Feb
12
3 months ago
Activity icon

Replied to Is It Required To Make Relation Functions In Both Models While We Just Wanna Use One Model.

@singhwithlaravel

not entirely sure what are trying to acheive, but if you are wanting to include soft deleted records you can use the withTrashed() scope

Activity icon

Replied to Is It Required To Make Relation Functions In Both Models While We Just Wanna Use One Model.

Hi @singhwithlaravel

No you dont have to define the relationships in both models, you only need to define the ones that you want to use.

Feb
10
3 months ago
Activity icon

Replied to How To Deal With Shopping Cart Processing?

Hi @burano

Not used the pacakge above, but I work for an eCommerce company (and have done eCommerce before here), and this is the general process that we use:

  • User adds an item to their basket
  • this creates a session with that product in the basket
  • They can add other products if they wish
  • They proceed to through the checkout, and the basket is saved as an order (with the product details at the time of purchase - eg the price at that point)
  • The payment is processed through the payment gateway.
  • Successful payments get updated as such, and things like bank transfer get marked as Pending Payment
  • At this point we clear the basket from the session

So, should the user start a new order either straight away or after a few days, it is treat as that, a new order.

And each order, is a snapshot of the details of that time (customer details, product details, etc), but they are still liked by having the IDs, but this means that should any details change for the product/customer, it doesnt effect previous orders.

So going back to your question, yes I would certainly start a new basket session for each order (unless you are also adding functionality to amend orders, in that case you would need to resume a previous basket session)

Activity icon

Replied to Spatie Role Permissions And Gates Help

Hi @sigalz

Glad you have it working :)

In terms of when the super admin check is being done, as you have added the Gate::before in AuthServiceProvider this tells the Gate to run this check before any other (whether that being direct through a can() call, ot through a permission check).

So if the Super admin check passes, it doesn't need to run any of the other checks. Which is also why you need to return null if it doesn't in the Gate::before, as it is looking for the first boolean response, and once it finds it, then it breaks there.

Think of it as a list of checks, and should any of them return a boolean, then that is where the check will exit.

Feb
06
3 months ago
Activity icon

Replied to Spatie Role Permissions And Gates Help

Hi @sigalz

So, the Gate function works with things like Auth()->user()->can('edit', $model) (which would go of to a policy for the model, and check the edit method).

The spatie package extends this, so that you can pass permissions in there, eg Auth()->user()->can('manage-users')

Which will check if the user has been assigned the Permsion manage-users (either directly, or if the permission has been assigned to a role).

So, as this runs through the gate, and Super Admin is set to pass all, it would pass.

Admin would also pass, if it had the permission assigned by givePermissionTo()

however, the Role Middleware is not going to using Gate, and is just checking if the user has a role directly assigned.

I went down the route of having everything limited by permissions, cause I was going to need different users with different permissions, and a possible mix of anything.

But if you are only having Super Admin, Admin and User roles, then using the roles would be enough, but you would need to check for the other roles too.

Eg, if checking User role, you would also need to check for Admin and Super Admin roles.

Another option, if you want to use the Gate stuff (like using the can(), you could create something like an is-admin permission, and assign that to the Admin role, then in your middleware group do

    'admin' => [
        'web',
        'auth',
        'role:is-admin'
    ],

And Super Admins would automatically pass that

Activity icon

Replied to Spatie Role Permissions And Gates Help

Hi @sigalz

From what I understand with the spatie pacakge, the permissions are running through Gate (using the can method), but the Role middleware doesn't appear to be.

I am using the pacakge, but I do all my restrictions based on permissions (which are assigned to roles), so the super admin passes that.

What you could try is when setting up the admin middleware group, is:


    'admin' => [
        'web',
        'auth',
        'role:admin|Super Admin'
    ],

I know you can do the above with permissions, as I have stuff like this on my routes

Route::get('/protected/route', '[email protected]')
     ->name('protected.create')
     ->middleware('permission:can-view|can-manage');

So I would assume you can do the same with roles

Feb
05
3 months ago
Activity icon

Awarded Best Reply on Validate A New Value Generated In Controller ?

hi @supunsam

If you are using Form Requests you can use the prepareForValidation method to alter/change any data before the validation.

For example, I have the following in one of mine to remove the trailing slash

protected function prepareForValidation()
    {
        $this->merge([
           'url' => rtrim($this->url, '/'),
        ]);
    }

So you could try something like this

protected function prepareForValidation()
    {
        $this->merge([
           'job_id' => $this->job_no . $this->cyc_no,
        ]);
    }
Activity icon

Replied to Validate A New Value Generated In Controller ?

hi @supunsam

If you are using Form Requests you can use the prepareForValidation method to alter/change any data before the validation.

For example, I have the following in one of mine to remove the trailing slash

protected function prepareForValidation()
    {
        $this->merge([
           'url' => rtrim($this->url, '/'),
        ]);
    }

So you could try something like this

protected function prepareForValidation()
    {
        $this->merge([
           'job_id' => $this->job_no . $this->cyc_no,
        ]);
    }