PaulClarke

PaulClarke

Member Since 3 Years Ago

Experience Points 82,570
Experience Level 17

2,430 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 775
Lessons
Completed
Best Reply Awards 8
Best Reply
Awards
  • start-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-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-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist 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.

11 Mar
4 months ago

PaulClarke left a reply on Testing Notifications

@BWRIGLEY - Hi Ben,

Sorry, I have only used this method for DB notifications, so not sure about how you would do it instantly.

PaulClarke left a reply on Testing Notifications

Hi Ben,

I use your fourth option and made a factory e.g.

//Notification factory 

use Illuminate\Notifications\DatabaseNotification;

$factory->define(DatabaseNotification::class, function () {
    return [
        'id' => \Ramsey\Uuid\Uuid::uuid4()->toString(),
        'type' => 'App\Something',
        'data' => ['message' => 'message']
    ];
});

Then in the test I set it up like this and then use however needed in the specific tests which follow

        
    protected $notification;

    public function setUp():void
    {
        parent::setUp();
   
        $this->notification = factory(DatabaseNotification::class)->create([
        'notifiable_id' => factory(User::class)->create()->id
    ]);
    }
29 Jul
11 months ago

PaulClarke left a reply on Displaying AWS S3 Bucket Image In Vue (via Laravel Storage)

No worries - glad you got it sorted.

03 Jul
1 year ago

PaulClarke left a reply on Displaying AWS S3 Bucket Image In Vue (via Laravel Storage)

You can create a presigned request I think and then pass that url through as a prop or set up a route and fetch the url via AJAX. E.g. this will get you the presigned url (valid for 5 mins) which you can pass through:

/**
     * @param $path
     * @return string
     * @throws FileNotFoundException
     */
    private function s3Url($path)
    {
        $disk = Storage::disk('s3');

        if ($disk->exists($path)) {
            $s3_client = $disk->getDriver()->getAdapter()->getClient();
            $command = $s3_client->getCommand(
                'GetObject',
                [
                    'Bucket' => env('S3_BUCKET'),
                    'Key'    => $path,
                    'ResponseContentDisposition' => 'attachment;'
                ]
            );

            $request = $s3_client->createPresignedRequest($command, '+5 minutes');

            return (string) $request->getUri();
        } else {
            throw new FileNotFoundException($path);
        }
    }
07 May
1 year ago

PaulClarke left a reply on Changing Max Post/upload Size In Laravel 5.5

Do you use Forge to serve your site? If so, I had a similar problem a while back which was answered by Nash. This is the thread :

https://laracasts.com/discuss/channels/forge/changes-to-phpini-not-being-reflected-on-forge-server

18 Mar
1 year ago

PaulClarke left a reply on OrderBy Relationship !

Hi @DivPro I think the reason it is saying 'unknown column' is that you are trying to use orderBy on Anime, but the 'episode_number' lives on 'episode', so that won't work.

You need to use a closure like this:

$anime_E_li = Anime::where('anime_name', '=', $anime->anime_name)
    ->with(['Episode' => function ($q) {
        $q->orderBy('episode_Number', 'asc');
    }])    
    ->get();
16 Mar
1 year ago

PaulClarke left a reply on Elequent Relation With Where Clause

In that case my suggestion would be to remove the query element you are currently attaching to the relationship and ensure that the relationship is being returned.

Set up a test route, something like this (assuming you have some records already) just to see whether you can call anything from the relationship. Then play around to query it as needed after:

Route::get('/test', function() {
    return House::with('roomprices')->where('id', 1)->get();
});

PaulClarke left a reply on Elequent Relation With Where Clause

Are you using the standard convention for foreign keys and are those relations defined in the migration? If the key is non-standard, you can pass it as another argument e.g.

public function roomprices()
    {
        return $this->hasMany('App\Roomprice', 'your_foreign_key')->where('house_type',1)->get();
    }

PaulClarke left a reply on Elequent Relation With Where Clause

That error sounds like you are still mixing static and non-static methods. Can you paste the full code you have in both models please?

Also, have you used standard conventions for the foreign keys? If not, you may need to add those to the relationship explicitly.

PaulClarke left a reply on Elequent Relation With Where Clause

On the assumption that a House hasMany Roomprices and a Roomprice belongs to a House, why don't you do something like this:

On House model

public function rooms() 
{
    return $this->hasMany(Roomprice::class);
}

On Roomprice model

public function house() 
{
    return $this->belongsTo(House::class);
}

You cannot mix the scope resolution operator (::) in a non-static context.

I am not quite sure what you are trying to achieve as the outcome of your query, but you are trying to eager load the House with its room prices where the house type meets a particular condition: (obviously adapt as necessary if you change the relation name)

    $houses = House::with('rooms')->where('house_type', 1)->get();
    
15 Mar
1 year ago

PaulClarke left a reply on PHPStorm Settings (Smooth)

Hi Kropcik, I have a similar system to you and had one main problem which I had set up in error, leading to my fans going into overdrive!

When I was running npm run watch things were going crazy because my assets were being watched for changes, but I had not excluded my public directory from the watch, so the outcome files were also being watched, creating a horrible loop of doom which led to continual indexing.

To solve this you can right click the directory and pick Mark Directory As and then select Excluded from the menu, which will turn the icon red. This made a huge difference for me as the continual indexing stopped. You should also do this for the node_modules directory.

10 Mar
1 year ago

PaulClarke left a reply on Axios Request Returns Empty

It looks to me like you are not passing id through properly which may be why you are getting results from Room:all() but not when trying to find by ID.

Give this a go:

 created(id) {
    axios.get(‘/rooms/‘ + id)
        .then(response => this.rooms = response.data) 
}
06 Mar
1 year ago

PaulClarke left a reply on Font Awesome In With Laravel Mix

If you add .copy('node_modules/font-awesome/fonts', 'public/fonts' to you mix file it should do the trick, or you can select individual files if needed.

05 Mar
1 year ago

PaulClarke left a reply on Undefined Variable: User

Can you show the controller which is handling this please?

01 Mar
1 year ago

PaulClarke left a reply on Laravel Migrate Error

I was assuming there was data already in the tables, so they couldn't be blown away, but yes, if not, definitely!

PaulClarke left a reply on Laravel Migrate Error

I'm not certain that you can; that's essentially what the migrations table is for.

You could try and make a migrations table in your DB and manually add the existing migrations to it, which shouldn't be difficult if you only have 3 tables.

CREATE TABLE `migrations` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `migration` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `batch` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Set the batch to 1 for each existing table. Your migration takes this format 2014_10_12_000000_create_users_table i.e. the file name of the migration, but without the '.php' extension.

PaulClarke left a reply on Laravel Migrate Error

If you have already migrated your first two tables then they should be logged in the 'migrations' table. It sounds like they are not which is why Laravel is trying to run the migrations again.

Why don't you check your config/database.php and just check you have the migrations table set correctly. It looks like this...

/*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',
19 Feb
1 year ago

PaulClarke left a reply on The Mail Didn't Send To My Gmail !?!?

Well normally of course it would be whatever the company's outgoing email address would be e.g. [email protected]

PaulClarke left a reply on The Mail Didn't Send To My Gmail !?!?

You will need to put the credentials into your config/Mail.php or .env file for whichever settings are right for the mail account you own. There are some videos here in Laracasts which show exactly how to do that.

In my case, I am using a gmail account and off the top of my head the .env looks something like this, but of course you will need to check your own settings if you use something different.

MAIL_DRIVER=smtp 
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=yourpassword
MAIL_ENCRYPTION=tls 

You should set the global application email in your config too.

PaulClarke left a reply on The Mail Didn't Send To My Gmail !?!?

That is exactly as expected. Mailtrap’s job is to intercept the email so that you do not inadvertently send real emails from your application during testing.

29 Jan
1 year ago

PaulClarke left a reply on Cannot Correctly Test A Queued Notification With Email

@bobbybouwmann Thank you. I can see I was mixing too many things together here. I did eventually solve it. The reason the Notification / Mail assertions were failing was not because of the queue, but an entirely different element of the application where a request was returning null, but the error was not bubbling up.

I have taken your advice and made a separate test so that each element is being tested separately. Thanks :)

27 Jan
1 year ago

PaulClarke started a new conversation Cannot Correctly Test A Queued Notification With Email

Hi,

I am trying to properly test a Notification via email on a queue so that I can be absolutely clear that one user received it and another type of user did not.

The code works correctly, but I cannot get the test right. I am assuming that the reason is that I don't have a worker on the Queue during testing so the job is never processed and I am not certain how to change that. I have attempted to use the 'assertQueued' method, but no job. Can anyone give me some suggestions please?

A User reports a Concern and another user is notified: In the Controller

    //Other stuff
    event(new ConcernReported($concern));

In the Listener

    public function handle(ConcernReported $event)
     {
            $dsl->notify(new NotifyDslOfConcern($event->concern, $dsl));
      }

The Notification class sends an email (standard MailMessage).

In my test I have attempted:

/** @test */
    public function notifications_for_new_concerns_only_go_to_dsls_from_that_school()
    {
        Notification::fake();
        Mail::fake();

        $dsl = create(User::class);
        $dslFromOtherSchool = create(User::class);


        $this->actingAs($dsl)
            ->post('/safeguarding/concern/report, [
                'concern' => [
                    'incident_at' => Carbon::now(),
                    'reason' => 'A reason',
                    'details' => 'Some details'
                ]
            ])
            ->assertStatus(200);

    $concern = Concern::first();

    //Assert sent to DSL
         Mail::assertQueued(MailMessage::class, function ($mail) use ($dsl) {
            return $mail->dsl->id === $dsl->id;
        });

        Notification::assertSentTo(
            $dsl,
            NotifyDslOfConcern::class,
            function ($notification) use ($concern) {
                return $notification->concern->id === $concern->id;
            }
        );


    //Assert NOT sent to other user
    Mail::assertNotQueued(...);

    Notification::assertNotSentTo(
            [$dslFromOtherSchool],  NotifyDslOfConcern::class
        );
    }
19 Jan
1 year ago

PaulClarke left a reply on How To Use Vue Material In A Project

It looks like your error is on this line: <md-app-drawer :md-active.sync="menuVisible">

You are working in blade and trying to bind a variable to md-active.sync which does not exist in blade.

So you could either extract the content you have here to a Vue component and declare menuVisible as a prop or data property, or if you want to stay in blade and the view is receiving a menuVisible variable you could do something like <md-app-drawer :md-active.sync="{{ json_encode($menuVisible) }}">

28 Dec
1 year ago

PaulClarke left a reply on The Simple Things Can Trip You Up

I cannot see in the code you have given where you are calling suggest(). I think you should move it into a mounted () hook so that the AJAX call runs as soon as the component is mounted and then suggestions will be set.

17 Dec
1 year ago

PaulClarke left a reply on Non-static Method App\Collaboration::project() Should Not Be Called Statically, Assuming $this From Incompatible Context In Laravel

Flex, on line 150 you are calling the local scope you have made, but you have not passed through the parameter (project id). Give that a try:

$collaborators = \App\Collaboration::project($id)->get();
12 Dec
1 year ago

PaulClarke started a new conversation Laravel And MPDF Overriding Vendor Files Correctly

Hello everyone,

I want to use some fontawesome elements in mPDF which you can do by adding an element to the config_fonts.php file which is in vendor/mpdf/mpdf/ and then copying fontawesome in the vendor/mpdf/mpdf/ttfonts directory.

However, there are some problems with this because if mPDF is updated then any changes to the vendor files are obviously lost. So this seems like a bad approach. From what I have read elsewhere it indicates that you can do something like this to add to the config_fonts.php file e.g.

         $this->pdf = new mPDF('utf-8', 'A4-P');

        $this->pdf->fontdata["fontawesome"] = [
            'R' => "fontawesome-webfont.ttf"
        ];

Unfortunately this does not work for me and I am not sure why (I have manually copied the fontawesome-webfont.ttf to the correct directory, and the icons are visible if I add them directly to the config file in the vendor directly).

In addition, I am struggling a bit with Mix when copying from node_modules e.g.

Works: .copy('node_modules/font-awesome/fonts/fontawesome-webfont.ttf', 'public/build/fonts')

Does not work: .copy('node_modules/font-awesome/fonts/fontawesome-webfont.ttf', 'vendor/mpdf/mpdf/ttfonts')

How can I tell Mix that for this file I don't want things automatically in the public folder?

Any help much appreciated.

09 Dec
1 year ago

PaulClarke left a reply on Action="{{ Route('register') }}" Not In Routes/web.php

If you look in your web.php file you will see that it calls a Auth::routes(); which ultimately calls the auth method in \Illuminate\Routing'Router.php that auth method contains the routes I think you are looking for.

07 Nov
1 year ago

PaulClarke left a reply on How To Make A Drop Down Component With Ajax Options

Oh well - glad you’ve sorted it!

06 Nov
1 year ago

PaulClarke left a reply on How To Make A Drop Down Component With Ajax Options

@phpguru I think the reason is that you have not accepted partners as a prop in the partnerComponent, instead you only have it as a data property. So it doesn't matter which partners is in on your parent component, because it is never being passed through.

You should change your partnerCompontent as follows and see if it works:

var partnerComponent = Vue.extend({
    props: ['direction', 'partners'],
    template: `
<div class="partner-component">
    <label v-bind:for="'partner_'+direction">{{ direction | capitalize }} Partner
    <select v-model="selectedPartner">
    <option v-for="partner in partners" v-bind:value="partner.id">{{ partner.name }}</option>
    </select>
    </label> {{selectedPartner}}
</div>
`,
    data: function () {
        return {
            selectedPartner: '',
        };
    },
});


05 Nov
1 year ago

PaulClarke left a reply on Null Object In Test Using Eloquent

@shez1983 Thanks for your idea - I have solved it now! And am somewhat embarrassed. The reason it was not finding the user was that in my User Factory I have an active attribute which was set to false and then on my User Model I have a global scope which removes anyone whose active status is false. Doh. My bad.

PaulClarke left a reply on Null Object In Test Using Eloquent

@shez1983 Eloquent automatically allows for ‘findBy’ + attribute name is my understanding (the code works in production). But even using ng `User::where(‘email’, ‘[email protected]’)->firsn the controller, but not in the test.

PaulClarke started a new conversation Null Object In Test Using Eloquent

So I am attempting to test that when a user has forgotten their password, they can enter their email address and receive a password reset email.

The code works, but the test fails. (I have made a create helper method like JW had on the 'How to Build a Forum' series).

 /** @test */
    public function a_user_can_request_an_email_to_reset_their_password()
    {
        Notification::fake();

        $user = create(User::class, [
            'email' => '[email protected]',
        ]);

        dd($user);  //This correctly shows the full User object

        dd(User::findByEmail('[email protected]')); //This is null ! 

        $this->post('/password/reset', ['email' => '[email protected]'])
                ->assertStatus(302)
                ->assertSessionHas('success', 'Email sent, please check your inbox.');

        Notification::assertSentTo($user, NotifyPasswordReset::class);
    }

I am using Database Migrations in an sqlite DB. But I thought that only reset per test, not mid-test. Cannot anyone suggest which I have done wrong please?

PaulClarke left a reply on Laravel Notification Not Working

How are you expecting to send the notification? I notice that in the via method you have selected slack, but you also have the toMail method.

I have not used slack before, but if you want to send a notification via email you need to include 'mail' in the array e.g.


/**
 * Get the notification's delivery channels.
 *
 * @param  mixed  $notifiable
 * @return array
 */
public function via($notifiable)
{
    return ['mail', 'slack'];
}

Have you entered the email/slack settings in your .env file?

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=username
MAIL_PASSWORD=password

In config/mail.php you should also set up your default email e.g.

'from' => [
        'address' => '[email protected]',
        'name' => 'Your Company name'
    ],

If you are putting the notification on a Queue, have you set this up correctly? If so, you will need to run php artisan queue:work to process the queue locally.

Finally, you are passing a $notification variable to your notification class, but I cannot see where you have accepted it in your code above.

static function SendMxg($user,$notification) { 
    $user->notify(new InvoicePaid($notification));
}
03 Nov
1 year ago

PaulClarke left a reply on PHPWord Works Locally But Not When Pushed To Test Server

@Snapey Thank you, you are absolutely right. I had $doc = new \PhpOffice\PhpWord\Phpword(); when it ought to have been $doc = new \PhpOffice\PhpWord\PhpWord();

PaulClarke started a new conversation PHPWord Works Locally But Not When Pushed To Test Server

Dear All,

I am having a problem using PHPWord and I am hoping someone else has experience of this and can let me know where I am going wrong.

Locally, PHPWord is working absolutely perfectly and producing my files as expected.\

My settings are:

In composer.json (shortened)

 "require": {
        "php": ">=7.0.2",
        "laravel/framework": "^5.4.17",
        "mpdf/mpdf": "^6.1",
        "phpoffice/phpword": "v0.13.0"
    },

I can also see in my composer.lock that 'v0.13.0' is being used.

I am using fully qualified class names as per the documentation (although it also works fine importing them).

$doc = new \PhpOffice\PhpWord\Phpword();

When I have deployed to my test server and tried to run the file I am getting this error:

production.ERROR: Symfony\Component\Debug\Exception\FatalThrowableError: Class 'PhpOffice\PhpWord\Phpword' not found in /home/forge/...(myProject)..

Yet when I have checked in the vendor directory on the server, all the files are exactly where you would expect them to be. I have run composer dump-autoload just in case, but no joy.

One more piece of information: elsewhere in my project I have been using mPDF and I can now see PHPStorm saying where I have imported mPDF it is 'undefined' due to a clash with PHPWord's version.

Can anyone suggest what I could try next please?

28 Oct
1 year ago

PaulClarke left a reply on Avoid Mutating A Prop Directly Since The Value Will Be Overwritten Whenever The Parent Component Re-renders

@Uzenkov The reason is that you are over writing a property.

You have passed 'item status' into the component as a prop. Then at the bottom of your code snippet you are over writing it according to the value of the selector which is why Vue is throwing the error.


  props: ['itemid', 'itemstatus'],


  computed: {
    status: {
      get() { return this.itemstatus },
      set(value) {
        this.itemstatus = value;
      }
    }
  },
}

To avoid this you need to assign an initial property. Something like...


  props: ['itemid', 'initialStatus'],


  data() {
    return {
        currentStatus: this.initialStatus,
    }
  },

  computed: {
    status: {
      get() { return this.currentStatus },
      set(value) {
        this.currentStatus = value;
      }
    }
  },
}

That way when you change status, the initial prop value is not altered and Vue will stop squawking. You could also assign currentStatus in a mounted method.

14 Oct
1 year ago

PaulClarke left a reply on Changes To Php.ini Not Being Reflected On Forge Server

@Nash fantastic - that makes sense now. Thanks for explaining.

PaulClarke left a reply on Changes To Php.ini Not Being Reflected On Forge Server

@Nash Thank you - I cannot believe I didn't spot that setting. It worked, although I still cannot understand why changing the php.ini file directly wasn't working!

PaulClarke left a reply on Changes To Php.ini Not Being Reflected On Forge Server

I missed out that I have also updated the post_max_size in php.ini

PaulClarke started a new conversation Changes To Php.ini Not Being Reflected On Forge Server

Dear Everyone,

I have an issue with file uploads being refused, not due to validation in my PHP code, which is working, but due to the upload_max_filesize setting in php.ini.

My forge server is running PHP 7.0 and so I have edited the setting in /etc/php/7.0/fpm/php.ini and I have used php_ini_loaded_file() to double check that I am amending the correct copy of php.ini which I am.

I have restarted the server and am still getting a 413 Request Entity too large error. However, when I tried this on my local machine, all I had to do was restart php artisan serve to get this working and everything does work correctly on my local machine.

So I am stumped - can anyone suggest any steps forward I can try?

Many thanks,

19 Sep
1 year ago

PaulClarke left a reply on [Vue Warn]: Failed To Mount Component: Template Or Render Function Not Defined.

I had a similar problem a while back and in my case it was fixed by adding "vue-template-compiler": "^2.4.2" to my dependencies. Perhaps it is worth a try to see if it helps?

08 Sep
1 year ago

PaulClarke left a reply on Update Total Count Laravel And Vue Js

I think KNietzsche is right, you need to add props: [ 'eventId' ] to accept the prop.

PaulClarke left a reply on Update Total Count Laravel And Vue Js

You could try:

<script>
  export default {

    mounted() {
        axios.get('/events/participant/count/' + this.eventId)
             .then(response => this.count = response.data);
    },
     
    data() {
        return{
               count: ''
        }
    }
  }
</script>
14 Aug
1 year ago

PaulClarke left a reply on Many To Many Query

You need to use whereHas in your query and then apply the constraints in a closure. Something like this:

public function searchtest(Request $request)
{          
return Company::with('categories')
            ->whereHas('categories', function($q) {
                $q->where('category', 'electronics')
                   ->orWhere('category', 'education');
            })
            ->get();
}

Obviously I am not sure what precisely your fields are called, but you might be able to adapt this.

11 Aug
1 year ago

PaulClarke left a reply on Laravel 5.4 Policies Not Working With Jwt

@masoudline It was just a placeholder to show that you could isolate the logic for whether or not the User has permission to access the resource.

If you want to perform the logic directly in the Policy then of course you can.

07 Aug
1 year ago

PaulClarke left a reply on Laravel 5.4 Policies Not Working With Jwt

@masoudline Ok sorry, so yes you would be authorising on view Roles. The RolesPolicy automatically receives the currently authorised user.

In your RoleController:

public function index(Request $request) { 

    $user = JWTAuth::toUser($request->token); 
    $this->authorize('view', Role::class); 

    $roles = Role::all();       
    $response = [ 'roles' => $roles ]; 

    return response()->json($response); 
} 

And in your RolePolicy :

public function view(User $user)
{
    return $user->canViewRoles();
}

Assuming your logic lives on the User Model.

If that isn't working are you certain the line $user = JWTAuth::toUser($request->token); is authenticating the user correctly?

PaulClarke left a reply on Laravel 5.4 Policies Not Working With Jwt

You need to pass the Model you are trying to authorise on.

If you are operating on an instance it would look like this:

$this->authorize('view', $user);

When you are authorising on 'create' and do not have an instance you can do it as follows:

$this->authorise('create', User::class);

Then in your Policy you determine whether the User has the appropriate roles.

22 Jul
2 years ago

PaulClarke left a reply on Many To Many Relations

@FREDMORAS I think your issues is the way you have set your relationships up.

You need to be more explicit with by including the name of your pivot table in the relationship and the foreign and local ids. If I have understood your relationship correctly that might be something like this...

On the ingredients model:

'public function Salades() { return $this->belongsToMany('App\Salade', 'ingredient_salade', 'ingredient_id', 'salade_id'); }'

On the salads model

'public function ingredients() { return $this->belongsToMany('App\Ingredient', 'ingredient_salade', 'ingredient_id', 'salade_id' ); }'

See if that helps.

21 Jul
2 years ago

PaulClarke left a reply on What Types Of Validations?

Even better - I didn't realise that!

20 Jul
2 years ago

PaulClarke left a reply on What Types Of Validations?

@Marins You could add a custom validator.

You can define them in the boot method of the AppServiceProvider.

Here is an example of one to only accept upper or lowercase alphabetical characters and spaces.

Validator::extend('no_special_characters', function ($attribute, $value, $parameters, $validator) { return preg_match("/^[A-Za-z ]+$/", $value); });

This then allows you to call like this in your example:

$this->validate($request, [ 'another' => 'required|string|max:255|no_special_characters',

Obviously you will need to adapt the regex to meet your needs.

Hope that works!