Chris1981

Chris1981

Member Since 2 Years Ago

Experience Points 15,430
Experience
Level
Lessons Completed 125
Lessons
Completed
Best Reply Awards 0
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.

08 Nov
1 month ago

Chris1981 left a reply on Adding ACL To A Laravel API

Anyone? Please :)

07 Nov
1 month ago

Chris1981 started a new conversation Adding ACL To A Laravel API

Hey Guys,

Im using Laravel 5.7 as an API for an app im building, which is using JWT-Auth for authentication.

At this stage i would like to add an ACL to the mix.

Can anyone recommend a good ACL which works nicely with JWT-Auth.

Cheers,

12 Oct
2 months ago

Chris1981 left a reply on Returning A Generated Token In A Test

Thanks guys, thats worked now :)

Much appreciated for all your help, sorry about the back and forth.

Chris1981 left a reply on Returning A Generated Token In A Test

@D9705996 Sorry to be a pain, but thats also erroring out.

ErrorException: json_decode() expects parameter 1 to be string, object given

@tykus im also getting an error from this

ErrorException: Illegal string offset 'data'

Chris1981 left a reply on Returning A Generated Token In A Test

@tykus that doesn't check to see if there is a value in the token though does it?

Chris1981 left a reply on Returning A Generated Token In A Test

@D9705996 damn, now im getting the following;

PHPUnit\Framework\Exception: Argument #2 (No Value) of PHPUnit\Framework\Assert::assertCount() must be a countable or iterable

My whole test is as follows;

public function it_logs_a_user_in()
{
    $user = factory(User::class)->create([ 'password' => Hash::make('foobar') ]);
    $payload = [ 'email' => $user->email, 'password' => 'foobar' ];

    $response = $this->json('POST', '/api/login', $payload);
    $response->assertStatus(200)
        ->assertJsonFragment([
            'success' => true,
            'message' => 'Yehhh Boiiiii'
        ])
        ->assertJsonCount(1, 'data.token');
}

Chris1981 left a reply on Returning A Generated Token In A Test

@D9705996 thats ok .. This is what i am getting using dd($response)

+original: array:3 [
    "success" => true
    "message" => "Yehhh Boiiiii"
    "data" => array:1 [
        "token" => "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3RcL2FwaVwvbG9naW4iLCJpYXQiOjE1MzkzMzM0NjMsImV4cCI6MTUzOTMzNzA2MywibmJmIjoxNTM5MzMzNDYzLCJqdGkiOiJscTNMVE00Q2FIbkJiUTlUIiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.2ufSUEmW6FwxirRHrPU5tyb-Y9zrBss4ap0oIHxny2Y"
    ]
]

The token is there, but I just cant seem to get it into the assert statement

Chris1981 left a reply on Returning A Generated Token In A Test

@D9705996 I get the following error

BadMethodCallException: Method Illuminate\Http\JsonResponse::toArray does not exist.

Chris1981 started a new conversation Returning A Generated Token In A Test

Hey Guys,

Im trying to write a test to check if a user gets successfully logged into our system

For some reason, its not seeing the token generated by the login endpoint.

I want to assert 3 things in my test.

  1. That the success flag is true .. This is currently working
  2. The message is set .. This is currently working
  3. The token gets returned .. This is the bit that i cant seem to get going.

My test is as follows;

public function it_logs_a_user_in()
{
    $user = factory(User::class)->create([ 'password' => Hash::make('foobar') ]);
    $payload = [ 'email' => $user->email, 'password' => 'foobar' ];

    $response = $this->json('POST', '/api/login', $payload);
    $response->assertStatus(200)
    ->assertJsonFragment([
        'success' => true,
        'message' => 'Yehhh Boiiiii'
    ]);
}

Looking at the response in Postman, i get the following;

{
    "success": true,
    "message": "Yehhh Boiiiii",
    "data": {
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9qb2JtYW5oZWxpb3MudGVzdFwvYXBpXC9hcGlcL2xvZ2luIiwiaWF0IjoxNTM5MzIyODcyLCJleHAiOjE1MzkzMjY0NzIsIm5iZiI6MTUzOTMyMjg3MiwianRpIjoiaXpQc2pvM0QxNm1SZ0VlayIsInN1YiI6MSwicHJ2IjoiMjNiZDVjODk0OWY2MDBhZGIzOWU3MDFjNDAwODcyZGI3YTU5NzZmNyJ9.ny4BKt0gcUCDiQ1a5bvsfwvcQfdV3nEPZAWVzBvziHo"
    }
}

Whatever i do, i cant seem to get the token returned.

Any help would be grand :)

05 Oct
2 months ago

Chris1981 left a reply on Moving Validation Into A Form Request But Use Custom Response

@martinbean Im using the league/fractal package and am following the 'build apis you wont hate' book, in there, all the response methods are put in the base controller.

Chris1981 left a reply on Moving Validation Into A Form Request But Use Custom Response

@D9705996 Thats not a bad idea actually, that way i could use it in my middleware as well instead of just controllers right?

Chris1981 left a reply on Moving Validation Into A Form Request But Use Custom Response

@D9705996 Hey thanks for that, im building an API so i kind of need it all in the backend.

If my formatResponseObject method was in my base controller, would i just need to use App\Http\Controllers\Controller; in my form request to access that method?

Chris1981 started a new conversation Moving Validation Into A Form Request But Use Custom Response

Hey,

I want to move my validation rules out of my controller into a custom form request thingo, if the validation fails at the moment, it have it calling a custom method.

Can I still do this with a form request?

This is what i have at the moment

$validator = Validator::make($request->all(), [
    'name' => 'required|string',
    'email' => 'required|string',
    'password' => 'required|string'
]);

if($validator->fails()){
    return $this->formatResponseObject($validator->errors()->first());
}

Is this possible using a form request?

04 Oct
2 months ago

Chris1981 left a reply on Suggestions For JSON API Response Package

@mykola is that exactly what the Fractal package does?

Chris1981 left a reply on Suggestions For JSON API Response Package

Hey @bobbybouwmann ... I am going to change my answer, as im currently reading 'Build APIs you wont hate' and it seems as if the Fractal package is actually developed by the author of the book.

Chris1981 left a reply on Suggestions For JSON API Response Package

@bobbybouwmann thank you for that, it looks like the cloudcreativity package is the one that fits the specifications right.

Nice one :) Thanks

Chris1981 started a new conversation Suggestions For JSON API Response Package

Hey Guys,

I was wondering if anyone could suggested a good package they have used to format their JSON API responses as close as possible to JSON-API (http://jsonapi.org/) specifications?

Cheers all

30 Aug
3 months ago

Chris1981 left a reply on Must Be An Instance Of Illuminate\Http\Request, Instance Of StdClass Given

Im thinking that might be the best option sujancse

Chris1981 left a reply on Must Be An Instance Of Illuminate\Http\Request, Instance Of StdClass Given

@tisuchi It's already there.

My controller imports are as follows;

namespace App\Http\Controllers;

use JWTAuth;
use App\Models\User;
use JWTAuthException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Exceptions\JWTException;

Chris1981 started a new conversation Must Be An Instance Of Illuminate\Http\Request, Instance Of StdClass Given

Hey Guys,

I'm having a bit of an issue figuring out how to pass a Request object from my javascript application to my laravel backend.

In my javascript framework i am doing the following;

var formData = new FormData();
formData.append("email", username);
formData.append("password", password);

and then passing the formData to my laravel endpoint.

My authenticate function is just a standard;

public function authenticate(Request $request)

The problem is that everytime i try to run my code, i am getting;

Argument 1 passed to App\Http\Controllers\AuthController::authenticate() must be an instance of Illuminate\Http\Request, instance of stdClass given

Does anyone know how I can solve this?

26 Jul
4 months ago

Chris1981 started a new conversation Mapping A Site To A Folder Of Another Site In Homestead

Hey Guys,

I currently have a javascript framework being spooled up on a URL thats mapped in Homestead.yaml just as an example, lets say www.mysite.test

I am building the API in Laravel for the JS framework to get its data from.

I want to be able to have that at www.mysite.test/api

Is there any way to achieve this using the Homestead.yaml, or would this require some in depth messing around?

Thanks

12 Jul
5 months ago

Chris1981 left a reply on Am I Testing The Logout Correctly.

@tykus hey again hahaha .. I think i may need to hire you hahaha

I am using the following; "tymon/jwt-auth": "dev-develop" in my composer.json.

This is my route;

    Route::group(['middleware' => 'auth.jwt'], function () {
        Route::get('user', '[email protected]');
    Route::get('logout', '[email protected]');
    });

Im using the request for the logout method as well.

I know this is a big ask, but i used the following tutorial to learn to implement it, is it a bad tutorial? https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/

It doesn't use the Authorization header at all

Chris1981 started a new conversation Am I Testing The Logout Correctly.

So im new to testing, and i want to make sure im doing it right.

I'm using JWT-Auth for my API token generation, i want to test that a user gets logged out properly.

Could someone have a look at the following and let me know if its any good, i kind of feel like its not the right thing, but i dont know how to make it better

    public function it_logs_out_properly()
    {
        $user = factory(User::class)->create([ 'password' => bcrypt('foobar') ]);
        $payload = [ 'email' => $user->email, 'password' => 'foobar' ];

        $token = JWTAuth::fromUser($user);

        $this->json('GET', '/api/user', ['token' => $token])->assertStatus(200);
        $this->json('GET', '/api/logout', ['token' => $token])->assertStatus(200);

        $this->json('GET', '/api/user', ['token' => $token])->assertStatus(401);
    }

The /api/user endpoint routes to the following method;

    public function getAuthUser(Request $request)
    {
        // Check for a token in the request
        $this->validate($request, [
            'token' => 'required'
        ]);

        // Get the user details based on the token
        $user = JWTAuth::authenticate($request->token);

        return response()->json(['user' => $user]);
    }

Any guidance would be greatly appreciated.

Chris1981 left a reply on AssertJson Isn't Seeing The Json That Is Being Returned

hahaha don't facepalm, the assertJsonFragment you suggested has made my testing so much easier now ... Much respect!

Chris1981 left a reply on AssertJson Isn't Seeing The Json That Is Being Returned

Hey @tykus thanks for that, i didnt know assertJsonFragment existed, i had to add brackets around the messages though, but it worked ... The final working function is as follows;

    public function it_requires_name_and_email_and_password_to_register()
    {
        $response = $this->post('/api/register');
        $response->assertStatus(422)
            ->assertJsonFragment([
                'name' => ['The name field is required.'],
                'email' => ['The email field is required.'],
                'password' => ['The password field is required.'],
            ]);
    }

Chris1981 started a new conversation AssertJson Isn't Seeing The Json That Is Being Returned

I'm trying to write a simple test to make sure the authentication is working correctly ( Laravel 5.6 ) as seen below;

public function it_requires_name_and_email_and_password_to_register()
{
    $response = $this->post('/api/register');
    $response->assertStatus(422)
        ->assertJson([
            'name' => 'The name field is required.',
            'email' => 'The email field is required.',
            'password' => 'The password field is required.',
        ]);
}

But for some reason its failing even though the request has the required information.

The following is what phpunit is returning;

There was 1 failure:

1) Tests\Unit\AuthenticationTest::it_requires_name_and_email_and_password_to_register
Unable to find JSON:

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

within response JSON:

[{
    "message": "The given data was invalid.",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "email": [
            "The email field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}].


Failed asserting that an array has the subset Array &0 (
    'name' => 'The name field is required.'
    'email' => 'The email field is required.'
    'password' => 'The password field is required.'
).
--- Expected
+++ Actual
@@ @@

         )

-    [name] => The name field is required.
-    [email] => The email field is required.
-    [password] => The password field is required.
 )

Am i missing something?

08 Jul
5 months ago

Chris1981 left a reply on Dealing With Redirections In Testing Environment

Hey Guys,

Thanks for the answers, but how do i change the property value in the test?

If I do something like;

public function it_registers_successfully()
{
    $loginAfterSignUp = false;

    $user = factory(User::class)->create([ 'password' => bcrypt('foobar') ]);

    $payload = [ 'name' => $user->name, 'email' => $user->email, 'password' => 'foobar' ];

    $response = $this->post('/api/register', $payload);
    $response->assertStatus(200);
}

I still get the same result

Chris1981 left a reply on Dealing With Redirections In Testing Environment

@lostdreamer_nl thanks for that ... But how would I change the value of loginAfterSignUp in a test if i move it to config?

Chris1981 started a new conversation Dealing With Redirections In Testing Environment

I am using Laravel 5.6 with the JWT-Auth package, I have a simple test which checks a user is able to be registered, as follows;

public function it_registers_successfully()
{
    $user = factory(User::class)->create([ 'password' => bcrypt('foobar') ]);

    $payload = [ 'name' => $user->name, 'email' => $user->email, 'password' => 'foobar' ];

    $response = $this->post('/api/register', $payload);
    $response->assertStatus(200);
}

When i run the test i am receiving the following;

Expected status code 200 but received 302.
Failed asserting that false is true.

I am new to testing, but i think the problem is that the register function checks to see if the user should be logged in on a successful register and then does it, hence the redirection.

I know this is defeating the purpose and going backwards to how its meant to be done, but i would like some advice on how to deal with the redirection and see the 200 status.

The function is as follows;

public $loginAfterSignUp = true;

public function register(RegisterAuthRequest $request)
{
    // Build new user collection
    $user = new User();
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = bcrypt($request->password);

    // Save user
    $user->save();

    // Check if user should be automatically logged in
    if ($this->loginAfterSignUp) {
        return $this->login($request);
    }

    return response()->json([
        'success' => true,
        'data' => $user
    ], 200);
}
24 May
6 months ago

Chris1981 started a new conversation Purely API Implementation

Hey Guys,

I'm setting up a purely API implementation on my Laravel install, I will also be using JWT for authentication and all that bollocks.

As i will be writing all new authentication logic, can i delete the Controllers/Auth directory that ships with Laravel or will that make things go tits up?

Is there anything else i can get rid of being a API only implementation?

I hope that makes sense.

Cheers,

12 Mar
9 months ago

Chris1981 left a reply on Passport + Auth

Anyone?

10 Mar
9 months ago

Chris1981 started a new conversation Passport + Auth

Hey Guys,

Before i go ahead with setting everything up, im wondering if its possible to use Laravel Passport and the standard Laravel Auth on the same project.

So that i can offer an API to people and also have members access for my frontend.

Cheers,

01 Feb
10 months ago

Chris1981 left a reply on Homestead Script For Installing Nginx On Centos

@bobbybouwmann .. Sorry to bug you .. But if i take the installation scripts from the homestead provision script and place it in a scripts/install-nginx.sh will that run on every vagrant up? or just when i do a vagrant provision --reload

Chris1981 left a reply on Homestead Script For Installing Nginx On Centos

Ohhh ... I can use that to rip out the install scripts ... I didnt think of that, doiiiiii.

Thanks @bobbybouwmann

Chris1981 left a reply on Homestead Script For Installing Nginx On Centos

@bobbybouwmann that just provisions Ubuntu doesnt it? ... I need it for CentOS

Chris1981 started a new conversation Homestead Script For Installing Nginx On Centos

Hey Guys,

Im trying to replicate the Homestead vagrant box on CentOS 7, im using the centos/7 box and it doesnt come pre installed with Nginx like Homestead does.

In the git repo for Homestead there is a scripts folder which configures all the services.

Has anyone built a create-nginx.sh or does anyone know how the commands to go through for Nginx with PHP7.2

Any help would be greatly appreciated.

Thank you

06 Dec
1 year ago

Chris1981 started a new conversation Laravel, TDD And ExtDirect

Hey Guys,

Im wondering if anyone here uses ExtJS, and specifically ExtDirect.

Im curious to know peoples approach to testing their Laravel API when Ext Direct only uses one endpoint.

Any advice would be awesome

24 Nov
1 year ago

Chris1981 started a new conversation Laravel Vs Lumen

Hey guys,

I want to build a single page JS app using ExtJS. To build my API i want to build it in Laravel, but ive just also come across Lumen. Is Lumen just a Laravel app without views? Would i be better to build my API with Lumen?

Any thoughts would be great

Cheers

Chris1981 left a reply on ExtJs 5 And Laravel 5

This is a little old, but did you ever find any resources? ... Im looking at building in both as well

11 Oct
1 year ago

Chris1981 started a new conversation Sharing One Codebase Over Multiple Domains

Hey Guys,

I was wondering if anyone could shoot me some advice.

Is there any way to share one codebase over multiple domains and also extend that to the authentication.

For example, lets say I have 3 domains, domainone.com, domaintwo.com and domainthree.com

I want one installation of Laravel to serve content to these 3 domains, also, if someone log's in on domainone.com they are automatically logged in on the other domains, same for logout etc

Im hoping someone has come across this before.

Any help would be greatly appreciated.

Cheers,

15 Aug
1 year ago

Chris1981 started a new conversation Telling Vagrant Which Box To Run

Hey Guys,

I was wondering if someone could help me.

Im trying to install 2 different homestead boxes for my projects ( PHP5.6 and 7 ).

I have downloaded the boxes and which i hit up vagrant box list i get the following output

laravel/homestead (virtualbox, 0.3.3)
laravel/homestead (virtualbox, 3.0.0)

Obviously 0.3.3 is the 5.6 box and 3.0.0 is 7.

But when i go into the directory for the 5.6 install and do a vagrant up, i get the following;

[2.0][~/Homestead/PHP5.6]$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'laravel/homestead'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'laravel/homestead' is up to date...
A VirtualBox machine with the name 'homestead' already exists.
Please use another name or delete the machine with the existing
name, and try again.

Is there a way i can tell each install to run a specific box?

12 Aug
1 year ago

Chris1981 left a reply on Help With Mutator

The answer has been revealed.

In my model i did the follwing;

    public function getCreatorNameAttribute()
    {
        if ($this->creator) {
            return $this->creator->name;
        }

        return 'Anonymous';
    }

Then in the view

{{ $gallery->creatorName }}

Very very close all.

Thanks for all your input

Chris1981 left a reply on Help With Mutator

@edoc Hmmmm .. im getting the same error

ErrorException: Trying to get property of non-object

Chris1981 left a reply on Help With Mutator

@edoc Yeh, i can do that, but it means i have to do that throughout the app, I would like to learn how to take care of this automatically with the Mutators.

Chris1981 started a new conversation Help With Mutator

Hey Guys,

I was wondering if someone could give me a bit of help.

I want to write a mutator that returns a users name as Anonymous if no user_id is present on the gallery table, but im not sure how to go about it

On my blade template I have the following;

<a href="#">{{ $gallery->creator->name }}</a>

The controller looks like this;

    public function show(Gallery $gallery)
    {
        return view('galleries.show', compact('gallery'));
    }

and the creator method in the Gallery model is as follows;

    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

Basically, every gallery a user_id field, but for the people not logged in, that field is set to null.

Any help would be awesome

11 Aug
1 year ago

Chris1981 left a reply on Anybody Hitting An Endpoint Can Add A Thread

Beautiful ... Alright, once again, onwards and upwards .. Its all learning :)

Thanks again and again and again hahaha

Chris1981 left a reply on Anybody Hitting An Endpoint Can Add A Thread

ok ... I needed to create the user

This is what i have come up with .. is this good?

    /** @test */
    public function a_gallery_has_a_creator()
    {
        $user = factory('App\User')->create(['id' => 1]);

        $gallery = factory('App\Gallery')->create(['user_id' => 1]);

        $this->assertInstanceOf('App\User', $gallery->creator);
    }

Chris1981 left a reply on Anybody Hitting An Endpoint Can Add A Thread

If i dd the $thread .. It spits out a user with an id of 1