Corbin

Corbin

Member Since 4 Years Ago

Experience Points
34,190
Total
Experience

810 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
352
Lessons
Completed
Best Reply Awards
1
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.

Level 7
34,190 XP
Jan
25
2 days ago
Activity icon

Replied to How Do I Test Encrypted Database Fields?

@bugsysha I think I'm starting to see what you're getting at:

Okay for the assertDatabaseHas I changed that to be assertJsonFragment:

PostController

public function store(Request $request)
{
    $this->validate($request, [
        'title' => 'required|max:255',
    ]);
    
    $post = Post::create([
        'title' => $request->input('title'),
    ]);

    return response(new PostResource($post),201);
}

PostTest

/** @test */
public function a_user_can_create_a_post_record()
{
    //$this->withoutExceptionHandling();
    $this->actingAs($creator = factory('App\User')->create());

    $post = factory('App\Post')->make(['user_id' => $creator->id]);

    //You can't use $post->toArray() because toArray() encrypts fields.
    $decryptedPost = [
        'title' => $post->title,
    ];

    $response = $this->json('POST', '/api/posts', $decryptedPost )
        ->assertStatus(201);

    $response->assertJsonFragment(['title' => $post->title]);
}

You got me thinking that I should probably be testing to see if values have been encrypted. That's where using this at the top of my code comes in:

$this->mock(Crypt::class, function ($mock) {
    $mock->shouldReceive('encrypt')->times(1)->andReturn('encrypt-value');
    $mock->shouldReceive('decrypt')->times(1)->andReturn('decrypt-value');
});

Is that true?

Activity icon

Replied to How Do I Test Encrypted Database Fields?

@bugsysha, I'm still moderately confused. I'm trying to read up on mockery and watch videos to catch up, but shouldn't I be mocking the Post model and not the Crypt class? Then after mocking the post model I should receive the methods in the encryptable trait?

Also I would avoid dynamic assertion values for following

 $this->assertDatabaseHas('posts', [
        'title' => $post->title, // replace with a string
    ]);

Since the code might now show you errors that you have with code and it is easier to debug.

The problem is that I don't know what that string is since the title gets encrypted.

Thanks for helping me so far. I swear I'm sitting here reading and watching videos about mockery trying to grasp it. I think I'm getting closer.

Jan
24
3 days ago
Activity icon

Replied to How Do I Test Encrypted Database Fields?

@bugsysha no I haven’t, this is a new concept to me. After reading the docs I’m kinda confused as to how I would implement that? Like would I use object mocking? Is there any pseudo code you can share with me to grasp this?

Activity icon

Started a new Conversation How Do I Test Encrypted Database Fields?

I'm encrypting database fields using a custom Encryptable trait:

Encryptable.php

<?php
namespace App;

use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decrypt($value);
            return $value;
        } else {
            return $value;
        }
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
} 

This allows me to specify in my model what fields I would like encrypted:

Post

use Encryptable;

protected $encryptable = ['title'];

I've learned that Crypt doesn't create a reproducible hash which makes it problematic in my assertDatabaseHas() assertions:

CreatePostTest.php

/** @test */
public function a_user_can_create_a_thought_record()
{
    //$this->withoutExceptionHandling();
    $this->actingAs($creator = factory('App\User')->create());

    $post = factory('App\Post')->make(['user_id' => $creator->id]);

    //You can't use $post->toArray() because toArray() encrypts fields.
    $decryptedPost = [
        'title' => $post->title,
    ];

    $response = $this->json('POST', '/api/posts', $decryptedPost )
        ->assertStatus(201);

    $this->assertDatabaseHas('posts', [
        'title' => $post->title,
    ]);
}

As said this doesn't work:

$this->assertDatabaseHas('posts', [
        'title' => $post->title,
 ]);

What other test can I use to assert that the posts title is the same in the database as what I'm sending through the request and how do I do this?

Jan
01
3 weeks ago
Activity icon

Awarded Best Reply on Not Sure If I Hit A Laravel Bug With API Resources: Using API Resource Switches Php Artisan Localhost Port On Save

The problem was in my UserResource I called the ActivityResource and in the ActivityResource I called Resources that would call the UserResource. It made an infinite loop.

public function toArray($request)
    {
        return [
            'name' => $this->name,
            'username' => $this->username,
            'slug' => $this->slug,
            'bio' => $this->bio,
            //'activity' => new ActivityCollection($this->activity()->latest()->paginate(1)),  
        ];
    }
Activity icon

Replied to Not Sure If I Hit A Laravel Bug With API Resources: Using API Resource Switches Php Artisan Localhost Port On Save

The problem was in my UserResource I called the ActivityResource and in the ActivityResource I called Resources that would call the UserResource. It made an infinite loop.

public function toArray($request)
    {
        return [
            'name' => $this->name,
            'username' => $this->username,
            'slug' => $this->slug,
            'bio' => $this->bio,
            //'activity' => new ActivityCollection($this->activity()->latest()->paginate(1)),  
        ];
    }
Activity icon

Started a new Conversation Not Sure If I Hit A Laravel Bug With API Resources: Using API Resource Switches Php Artisan Localhost Port On Save

I'm following along with the Let's build a forum series here on laracsts. What I'm trying to do is make an activity feed for posts and comments and use API resources to output the JSON. The problem I keep getting is when I try and form the activity for Posts and Comments using their own resource the post on my server switches from 8000 to 8001 and then when I try and load the activity in the browser. Then when I try and use http://127.0.0.1:8001/profile/fbins/activity/ the port will switch to 8002 like so:

php artisan serve
Laravel development server started: http://127.0.0.1:8000
[Wed Jan  1 19:55:46 2020] 127.0.0.1:49613 [200]: /favicon.ico
Laravel development server started: http://127.0.0.1:8001
Laravel development server started: http://127.0.0.1:8002
Laravel development server started: http://127.0.0.1:8003

ActivityResource

class ActivityResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        if($this->type === 'create_comment'){
            return new CommentResource($this->subject);
        } elseif ($this->type === 'create_post'){
            return new PostResource($this->subject);
        }
    }
}

Activity Collection

class ActivityCollection extends ResourceCollection
{
    /**
     * The resource that this resource collects.
     *
     * @var string
     */
    public $collects = 'App\Http\Resources\ActivityResource';

    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
        ];
    }
}

Activity Model

class Activity extends Model
{
    protected $guarded = [];

    protected $with = ['subject'];

    public function subject()
    {
        return $this->morphTo();
    }
}

ProfileController

    public function activity(User $user)
    {
       return new ActivityCollection(Activity::where(['user_id' => $user->id])->latest()->paginate(1));
    }

When I change my activity resource just to output $this->subject everything works just fine, except for the fact that the json output isn't customized with an API resource.

class ActivityResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->subject;
    }
}

I have no idea what's breaking and no idea how to figure this out. I use resources in other resources all of the time for example:

Working Example Comment Resource

class CommentResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'creator' => new UserResource($this->creator),
            'content' => $this->content,
            'children' => new ChildCommentCollection($this->children),
        ];
    }
}

I guess my question is why is this broken and how do I fix it?

Edit

I've tried changing the name of the ActivityResource, I've tried adding resources that didn't have polymorphic relations:

ActivityResource

return [
            'id' => $this->id,
            'creator' => new UserResource($this->creator),
];

And I've tried running: composer dump-autoload, php artisan clear-compiled, and composer clear-cache

Still same error. Only on the activity resource and collection

edit 2

Now when I run phpunit I'm getting

.........Segmentation fault: 11

edit 3

Commenting out my ActivityResource output stops the Segmentation fault

public function toArray($request)
    {
        /*return [
            'id' => $this->id,
            'creator' => new UserResource($this->creator),
        ];*/
        
        /*if($this->type === 'create_comment'){
            return 'comment';//new CommentResource($this->subject);
        } elseif ($this->type === 'create_post'){
            return 'post'; //PostResource($this->subject);
        }*/
    }
Dec
31
3 weeks ago
Activity icon

Started a new Conversation How Do I Paginate My Activity Feed Relationship In A JSON Resource API?

I'm building a JSON API profile activity feed that includes both posts and comments. What I'm trying to do is paginate the latest activity.

User Model

    public function activity()
    {
        return $this->hasMany('App\Activity');
    }
    
    public function latestActivity()
    {
        return $this->activity()->latest()->paginate(1);
    }

ProfileController

    public function show(User $user)
    {
        $user->load(['activity']);
    
        return new UserResource($user);
    }

I've tried both $user->load(['activity']); and $user->load(['latestActivity']); Both different errors:

1.) $user->load(['latestActivity']);

Call to undefined relationship [latestActivity] on model [App\User].

    public function activity()
    {
        return $this->hasMany('App\Activity')->latest()->paginate(1);
    }

2.) $user->load(['activity']);

I changed the activity relationship in the user model to be: return $this->activity()->latest()->paginate(1); and the UserResource to 'activity' => new ActivityCollection($this->whenLoaded('activity')),

Method Illuminate\Database\Eloquent\Collection::addEagerConstraints does not exist.

I eager load the subjects of my activity in the Activity model:

Activity Model

protected $with = ['subject'];

UserResource

    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'username' => $this->username,
            'slug' => $this->slug,
            'bio' => $this->bio,
            'activity' => new ActivityCollection($this->whenLoaded('activity')),  
        ];
    }

This works, but it doesn't show the pagination in the JSON output:

class UserResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'username' => $this->username,
            'slug' => $this->slug,
            'bio' => $this->bio,
            'activity' => new ActivityCollection($this->activity()->latest()->paginate(2)),  
        ];
    }
}

I'll probably have to create another Resource called profile resource for that though, since that would lead to an n+1 when the UserCollection is called.

How do I paginate my activity feed in a JSON API?

Dec
30
4 weeks ago
Activity icon

Replied to ErrorException: Trying To Get Property 'id' Of Non-object [Following Let's Build A Forum (activity) Series]]

@nakov Also, just checking the Let's Build A Forum Series github repo, it doesn't look like Jeffrey is testing to see if a guest can edit a post I'm still pretty much in agreeance though that you probably should run a test for that.

Activity icon

Replied to ErrorException: Trying To Get Property 'id' Of Non-object [Following Let's Build A Forum (activity) Series]]

@nakov thanks soo much for the help. Sorry, this doesn't work:

$this->withoutEvents();

Should I take this to another thread and give you the answer or should we stay on this one?

Activity icon

Replied to ErrorException: Trying To Get Property 'id' Of Non-object [Following Let's Build A Forum (activity) Series]]

Just to clarify, you would add the guest_users_may_not_update_posts() too?

Is there a way where I don't have to use auth?

This is kinda not making sense to me because in the boot method I'm using the create event:

static::created(function($post){
        Activity::create([
            'user_id' => Auth::user()->id,
            'type' => 'created_post',
            'subject_id' => $post->id,
            'subject_type' => 'App\Post'
        ]);
}

It shouldn't hit on a PATCH request I'm using $this->json('PATCH', '/post/'. $post->slug, ['title' =>'New title','content' => "Updated Content"])

Also, I'm creating a JSON API, so I'm not sure I can easily redirect.

Sorry if I'm a little incoherent, I'm a little tired

Activity icon

Replied to ErrorException: Trying To Get Property 'id' Of Non-object [Following Let's Build A Forum (activity) Series]]

Thanks @nakov, that seems like the answer. Just a question:

I'm testing to see if an a guest can edit posts:

EditPostTest.php

public function guest_users_may_not_update_posts()
{
    //$this->actingAs(factory('App\User')->create());
    $post = factory('App\Post')->create(['user_id' => factory('App\User')->create()]); 
    $this->json('PATCH', '/post/'. $post->slug, ['title' =>'New title','content' => "Updated Content"])
    ->assertStatus(401);
}

I can't use auth to test that. Is that test, guest_users_may_not_update_posts(), redundant when I have a test that use a policy to to check if an authenticated user is the owner of a post?

EditPostTest.php

/** @test */
public function a_user_can_not_update_post_that_is_not_theirs()
{
    $this->actingAs(factory('App\User')->create());

    $creator = factory('App\User')->create();

    $post = factory('App\Post')->create(['user_id' => $creator->id]);

    $response = $this->json('PATCH', '/post/'. $post->slug, ['title' =>'New title','content' => "Updated Content"])
        ->assertStatus(403);

}

PostPolicy.php

public function update(User $user, Post $post)
{
    return $post->user_id == $user->id;
}

Thanks, I'm still trying to learn testing.

Activity icon

Started a new Conversation ErrorException: Trying To Get Property 'id' Of Non-object [Following Let's Build A Forum (activity) Series]]

I'm following along with the Let's Build A Forum Series here on Laracasts and making something custom to what Jeffrey has built with similar features, one of them being an activity feed. I've gotten to episode 25 How to Construct an Activity Feed with TDD

I implemented:

Post Model

protected static function boot()
{
    parent::boot();

    static::created(function($post){
        Activity::create([
            'user_id' => Auth::user()->id,
            'type' => 'created_post',
            'subject_id' => $post->id,
            'subject_type' => 'App\Post'
        ]);
    }); 
}

and ran my test and almost every test that was using the post model factory broke with the same error:

ErrorException: Trying to get property 'id' of non-object

I changed the 'user_id' => Auth::user()->id, in Post model to be 1 instead of the auth id and I'm back to greens. I opened up a terminal and tested factory('App\Post')->create(); in tinker and got a similar error:

PHP Notice: Trying to get property 'id' of non-object in /Applications/MAMP/htdocs/final-community/app/Post.php on line 34

It's odd because line 34 is 'subject_id' => $post->id, and changing $post->id to 1 does nothing. It's a problem with 'user_id' => Auth::user()->id,

Here's my post model factory:

PostFactory.php

$factory->define(App\Post::class, function (Faker $faker) {
    
    $title = $faker->sentence;
    
    return [
        'title' => $title,
        'slug' => Str::slug($title, '-'),
        'channel_id' => function () {
            return factory('App\Channel')->create()->id;
        },
        'user_id' => function () {
            return factory('App\User')->create()->id;
        },
        'content' => $faker->paragraph,
    ];
});

Does anyone know how to fix this?

Dec
20
1 month ago
Activity icon

Started a new Conversation Cannot Redeclare RandomPostType() [Custom Function On Model Factory]

I have a PostsFactory that uses a function to randomly generate a "post type" and embed_code

PostFactory

$factory->define(App\Post::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence,
        'slug' => $faker->slug,
        'content' => $faker->paragraph,
        'post_type' => randomPostType(),
    ];
});

function randomPostType(){

    $post_type = ['forum','video','image','article'];
    $random_key = array_rand($post_type, 1);
    return $post_type[$random_key];
}


function randomEmbedCode(){

    $embed_code = [
        '<iframe class="embedly-embed-1"></iframe>',
        '<iframe class="embedly-embed-2"></iframe>',
        '<iframe class="embedly-embed-3" ></iframe>'
    ];
    $random_key = array_rand($embed_code, 1);
    return $embed_code[$random_key];
}

When I run vendor/bin/phpunit I get:

PHP Fatal error: Cannot redeclare randomPostType() (previously declared in /Applications/MAMP/htdocs/final-community/database/factories/PostFactory.php:26) in /Applications/MAMP/htdocs/final-community/database/factories/PostFactory.php on line 29

Is there anywhere I can put this function so I don't get this error and have my tests go green?

Thank you

Dec
12
1 month ago
Activity icon

Replied to Do You Guys Test Auth?

Thanks for the input guys. So writing a feature or unit test for the registration and login page, or anything that comes with composer require laravel/ui --dev is kinda useless since the code is already built? I added two database fields on registration and didn't add anything on login.

@nakov , I've watched a few test videos. Struggling on figuring out what I should test and what type of test I should do for a pretty big project.

@jlrdw I agree. I still always do a real world test. I'm totally gonna follow your advice.

Activity icon

Started a new Conversation Do You Guys Test Auth?

When working on authentication and adding various fields like username and slug to your users table do you guys test it? Why or why not? I'm trying to get better at development and I want to do this project that I have properly. Should I skip the tests for this knowing that so many things will change later in the project? Or maybe not?

Just looking for insights. Thanks guys.

Nov
23
2 months ago
Activity icon

Replied to Log File Permissions Error On AWS Elastic Beanstalk With Laravel 6:

Actually I just got it!

sudo chown $USER:webapp ./storage -R

find ./storage -type d -exec chmod 775 {} \;

find ./storage -type f -exec chmod 664 {} \;

If you think everything looks good I'll give you the best answer, since you pointed out that

AWS AMI uses webapp as the web user, not apache or ec2-user

Thank you so much!

Activity icon

Replied to Log File Permissions Error On AWS Elastic Beanstalk With Laravel 6:

@claudsonm

AWS image

PHP 7.3 running on 64bit Amazon Linux/2.9.0

Is it always this hard dealing with AWS in general? I've had nothing but problems.

So do I just have to give webapp access 775 permissions to the storage/logs folder? Or do I have to create an .ebextensions file and some how tell AWS to give permissions to webapp? Is there anything in the docs or any StackOverflow threads about this?

Sorry, I'm just a little bit confused.

Nov
22
2 months ago
Activity icon

Started a new Conversation Log File Permissions Error On AWS Elastic Beanstalk With Laravel 6:

I got the following error when entering my site on a production server:

The stream or file "/var/app/current/storage/logs/laravel-2019-11-22.log" could not be opened: failed to open stream: Permission denied

I ran chmod -R 775 storage/logs/ and composer dump-autoload and I was able to get onto the home page of my site without any errors. After surfing around the site a bit more I was getting the same error in various areas and not in others:

php artisan cache:clear
php artisan config:clear
php artisan config:cache
php artisan optimize:clear
composer dump-autoload

Again same error

The stream or file "/var/app/current/storage/logs/laravel-2019-11-22.log" could not be opened: failed to open stream: Permission denied

I reran my migrations and now I can't access the home page with out the permissions error.

I deleted the following files and ran php artisan cahce:clear:

I then tried to change the owner on the files and set the permissions on the directory and files in the storage:

sudo chown $USER:apache ./storage -R

find ./storage -type d -exec chmod 775 {} \;

find ./storage -type f -exec chmod 664 {} \;

The log files permissions

drwxrwxr-x 2 ec2-user apache 4096 Nov 22 00:44 logs
-rw-rw-r-- 1 ec2-user apache 14544 Nov 22 22:53 laravel-2019-11-22.log

I'm lost. I don't know what is going on, or what to do.

Edit

I tried deleting the files in the logs. Still the same error.

Nov
16
2 months ago
Nov
13
2 months ago
Activity icon

Replied to How Do I Pass A Blade Variable As A Vue Methods Property?

@tykus I don't think I can do that because it's within a vue instance:

Vue

//Vue initializes on app
const app = new Vue({
    el: '#app',
});

Blade

<div id="app">

    @foreach($entries as $entry)

        <script>
            window.raw_markdown = {{$entry->content}}
        </script>
        <a href="/entry/{{$entry->id}}"><h3>{{ $entry->created_at->format('M d Y') }}</h3></a>
        <div> @{{this.markdown(window.raw_markdown) }} </div>
        <hr>
    @endforeach

</div>

Error

Uncaught ReferenceError: smsa is not defined
    at entries:90
entries:99 Uncaught SyntaxError: Unexpected identifier
app.js:41078 [Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

63 |                  <div class="card-body">
64 |                                              
65 |                          <script>
   |                          ^^^^^^^^
66 |                              window.raw_markdown = smsa.mdsads
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
67 |  
   |  
68 |  hi
   |  ^^
69 |                          </script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
70 |                              <a href="/entry/2"><h3>Nov 09 2019</h3></a>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
71 |                              <div> {{this.markdown(window.raw_markdown) }} </div>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
72 |                              <hr>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
73 |                          
   |  ^^^^^^^^^^^^^^^^^^^^^^^^
74 |                          <script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
75 |                              window.raw_markdown = A lot happen today!!
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
76 |                          </script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
77 |                              <a href="/entry/1"><h3>Oct 31 2019</h3></a>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
78 |                              <div> {{this.markdown(window.raw_markdown) }} </div>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
79 |                              <hr>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
80 |                                                              </div>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
81 |              </div>
   |  ^^^^^^^^^^^^^^^^^^
82 |          </div>
   |  ^^^^^^^^^^^^^^
83 |      </div>
   |  ^^^^^^^^^^
84 |  </div>
   |  ^^^^^^
85 |          </main>
   |  ^^^^^^^^^^^^^^^
86 |      </div>
   |  ^^^^^^^^^^

(found in <Root>)
warn @ app.js:41078
app.js:41078 [Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

72 |                              <hr>
73 |                          
74 |                          <script>
   |                          ^^^^^^^^
75 |                              window.raw_markdown = A lot happen today!!
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
76 |                          </script>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
77 |                              <a href="/entry/1"><h3>Oct 31 2019</h3></a>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
78 |                              <div> {{this.markdown(window.raw_markdown) }} </div>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
79 |                              <hr>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
80 |                                                              </div>
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
81 |              </div>
   |  ^^^^^^^^^^^^^^^^^^
82 |          </div>
   |  ^^^^^^^^^^^^^^
83 |      </div>
   |  ^^^^^^^^^^
84 |  </div>
   |  ^^^^^^
85 |          </main>
   |  ^^^^^^^^^^^^^^^
86 |      </div>
   |  ^^^^^^^^^^

(found in <Root>)
warn @ app.js:41078
app.js:41078 [Vue warn]: Property or method "window" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

(found in <Root>)
warn @ app.js:41078
app.js:41078 [Vue warn]: Error in render: "TypeError: Cannot read property 'raw_markdown' of undefined"

(found in <Root>)
warn @ app.js:41078
app.js:42341 TypeError: Cannot read property 'raw_markdown' of undefined
    at Proxy.eval (eval at createFunction (app.js:52072), <anonymous>:1:356)
    at Vue._render (app.js:43989)
    at Vue.updateComponent (app.js:44505)
    at Watcher.get (app.js:44916)
    at new Watcher (app.js:44905)
    at mountComponent (app.js:44512)
    at Vue../node_modules/vue/dist/vue.common.dev.js.Vue.$mount (app.js:49482)
    at Vue../node_modules/vue/dist/vue.common.dev.js.Vue.$mount (app.js:52367)
    at Vue._init (app.js:45450)
    at new Vue (app.js:45516)

Activity icon

Started a new Conversation How Do I Pass A Blade Variable As A Vue Methods Property?

I'm trying to pass a blade variable to a vue method so it can be converted to git flavoured markdown using marked.js.

@foreach($entries as $entry)
    <a href="/entry/{{$entry->id}}"><h3>{{ $entry->created_at->format('M d Y') }}</h3></a>
    <div> @{{this.markdown({{ htmlentities($entry->content) }}) }} </div>
    <hr>
@endforeach
const marked = require('marked');

const app = new Vue({
    el: '#app',

    methods: {
        markdown(input){
            return marked(input, { sanitize: true })
        }
    }
});

Error

app.js:41078 [Vue warn]: Error compiling template:

invalid expression: Unexpected token '{' in

    " "+_s(this.markdown({{$entry->content)+") }} "

  Raw expression: {{this.markdown({{$entry->content}}) }}


63 |                  <div class="card-body">
64 |                                                                          <a href="/entry/2"><h3>Nov 09 2019</h3></a>
65 |                              <div> {{this.markdown({{$entry-&gt;content}}) }} </div>
   |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66 |                              <hr>
67 |                                                      <a href="/entry/1"><h3>Oct 31 2019</h3></a>

(found in <Root>)
warn @ app.js:41078
(anonymous) @ app.js:52125
compileToFunctions @ app.js:52124
./node_modules/vue/dist/vue.common.dev.js.Vue.$mount @ app.js:52348
Vue._init @ app.js:45450
Vue @ app.js:45516
./resources/js/app.js @ app.js:52507
__webpack_require__ @ app.js:20
0 @ app.js:52808
__webpack_require__ @ app.js:20
(anonymous) @ app.js:84
(anonymous) @ app.js:87
app.js:41078 [Vue warn]: Error compiling template:

invalid expression: Unexpected token '{' in

    " "+_s(this.markdown({{$entry->content)+") }} "

  Raw expression: {{this.markdown({{$entry->content}}) }}


66 |                              <hr>
67 |                                                      <a href="/entry/1"><h3>Oct 31 2019</h3></a>
68 |                              <div> {{this.markdown({{$entry-&gt;content}}) }} </div>
   |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
69 |                              <hr>
70 |                                                              </div>

(found in <Root>)
Nov
10
2 months ago
Activity icon

Started a new Conversation [Laravel]: Error Compiling Template: Invalid Expression: Invalid Or Unexpected Token In Markdown(' '). Htmlentities Problem? [marked.js]

I'm using marked.js to add git flavoured markdown to my Laravel app.

index.blade.php

@foreach($entries as $entry)
    <a href="/entry/{{$entry->id}}"><h3>{{ $entry->created_at->format('M d Y') }}</h3></a>
    <div v-html="markdown('{{ htmlentities($entry->content) }}')"> </div>
    <hr>
@endforeach

app.js

const marked = require('marked');

const app = new Vue({
    el: '#app',

    methods: {
        markdown(input){
            return marked(input, { sanitize: true })
        }
    }
});

When I run this and add words like "break", "for" or even just basic new paragraph (return), I get an error in the browser console and none of the content shows up.:

app.js:41078 [Vue warn]: Error compiling template:

invalid expression: Invalid or unexpected token in

markdown('smsa.mdsads

hi')

Raw expression: v-html="markdown('smsa.mdsads

hi')"

63 | 64 |

Nov 09 2019

65 |

| ^^^^^

(found in )

Note

I'm pretty sure this isn't a marked.js problem since I'm using marked in my vue components on so JSON, and it works great. Example:

RecordComponent.vue that works

<div  v-for="(record, index) in records">
    
    <h4>Content</h4>
    <div v-if="record.content" v-html="markdown(record.content)"></div>
    <p v-else style="color: #d02105;">Please fill out later</p>

    <hr>
            
</div>

How do I get marked to work in blade like it does in an vue component? What problem am I running into here? I think it might be an html entities problem or something.

Edit

This doesn't seem to have much to do with marked.js. But seems to have everything to do with passing a strange string through

v-html="markdown('smsa.mdsads

 hi')"

Edit 2

Turns out I can't use v-html unless passing a data() property from the vue instance.

What I'm trying to figure out is how to pass a blade variable to a vue method like so:

@foreach($entries as $entry)
    <a href="/entry/{{$entry->id}}"><h3>{{ $entry->created_at->format('M d Y') }}</h3></a>
    <div> @{{this.markdown({{$entry->content}}) }} </div>
    <hr>
@endforeach
Nov
09
2 months ago
Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck, Oh wait, I added an extra semi colon in Request::Request::HEADER_X_FORWARDED_AWS_ELB; changed it and everything seems to work great! Thank you!

Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck That seems like it's working! However now I have a new error:

The stream or file "/var/app/current/storage/logs/laravel-2019-11-09.log" could not be opened: failed to open stream: Permission denied`

I'm not sure what to set the permissions to

Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck

That looks like the proper answer. The only thing that I'm a little bit confused on is

If you are using AWS Elastic Load Balancing, your $headers value should be Request::HEADER_X_FORWARDED_AWS_ELB. For more information on the constants that may be used in the $headers property, check out Symfony's documentation on trusting proxies.

In the symfony link:

Some reverse proxies (like AWS Elastic Load Balancing) don't have a static IP address or even a range that you can target with the CIDR notation. In this case, you'll need to - very carefully - trust all proxies.

So what I'm confused about now is what to put in the protected $proxies = [];

Do I just leave it blank and set the header to: protected $headers = Request::Request::HEADER_X_FORWARDED_AWS_ELB; ?

Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck I also tried setting my APP_URL=https://mysite.ca but it didn't work.

Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck this is on a production server, using aws elastic beanstalk

Activity icon

Replied to Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

@sinnbeck

APP_URL=http://localhost

Do I change that to https?

When I run php artisan config:cache I'm getting:

The stream or file "/var/app/current/storage/logs/laravel-2019-11-09.log" could not be opened: failed to open stream: Permission denied

Nov
08
2 months ago
Activity icon

Started a new Conversation Laravel 6.0 Enforce HTTPS (Elastic Beanstalk)

I've built small project with Laravel 6. I'm using elastic beanstalk and load balancers with a AWS SSL Certificate.

The problem I'm having is when I go to mysite.ca it's loads via http, when I go to https://mysite.ca the style sheets don't load and I get a "Your connection is not fully secure." from chrome. I think I've also seen index.php pop up in my url while clicking around the site.

curl -v https://mysite.ca

* Rebuilt URL to: https://mysite.ca/
*   Trying 18.xxx.xxx.xxx...
* TCP_NODELAY set
* Connected to mysite.ca (18.xxx.xxx.xxx) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/cert.pem
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS change cipher, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES128-GCM-SHA256
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=mysite.ca
*  start date: Nov  4 00:00:00 2019 GMT
*  expire date: Dec  4 12:00:00 2020 GMT
*  subjectAltName: host "mysite.ca" matched cert's "mysite.ca"
*  issuer: C=US; O=Amazon; OU=Server CA 1B; CN=Amazon
*  SSL certificate verify ok.
> GET / HTTP/1.1
> Host: mysite.ca
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 302 Found
< Cache-Control: no-cache, private
< Content-Type: text/html; charset=UTF-8
< Date: Sat, 09 Nov 2019 03:49:13 GMT
< Location: http://mysite.ca/login
< Server: Apache
< Set-Cookie: XSRF-TOKEN=xxxx; expires=Sat, 09-Nov-2019 05:49:13 GMT; Max-Age=7200; path=/
< Set-Cookie: laravel_session=xxx; expires=Sat, 09-Nov-2019 05:49:13 GMT; Max-Age=7200; path=/; httponly
< Content-Length: 340
< Connection: keep-alive
< 
<!DOCTYPE html>

curl -v http://mysite.ca

* Rebuilt URL to: http://mysite.ca/
*   Trying 3.xx.xx.xx...
* TCP_NODELAY set
* Connected to mysite.ca (3.xx.xx.xx) port 80 (#0)
> GET / HTTP/1.1
> Host: mysite.ca
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 302 Found
< Cache-Control: no-cache, private
< Content-Type: text/html; charset=UTF-8
< Date: Sat, 09 Nov 2019 03:56:09 GMT
< Location: http://mysite.ca/login
< Server: Apache
< Set-Cookie: XSRF-TOKEN=xxxx; expires=Sat, 09-Nov-2019 05:56:09 GMT; Max-Age=7200; path=/
< Set-Cookie: laravel_session=xxxx expires=Sat, 09-Nov-2019 05:56:09 GMT; Max-Age=7200; path=/; httponly
< Content-Length: 340
< Connection: keep-alive
< 

On the server end, I've followed all of the steps and I believe everything is working correctly. Here's the steps:

  1. Open the Elastic Beanstalk console.

  2. Navigate to the management page for your environment.

  3. Choose Configuration.

  4. On the Load balancer configuration card, choose Modify.

    Note

    If the Load balancer configuration card doesn't have a Modify button, your environment doesn't have a load balancer.

  5. On the Modify load balancer page, the procedure varies depending on the type of load balancer associated with your environment.

    Classic Load Balancer

    • Choose Add listener.

    • In the Classic Load Balancer listener dialog box, configure the following settings:

      • For Listener port, type the incoming traffic port, typically 443.

      • For Listener protocol, choose HTTPS.

      • For Instance port, type 80.

      • For Instance protocol, choose HTTP.

      • For SSL certificate, choose your certificate.

    • Choose Add.

I've been getting help from a sysadmin that's been checking over everything as well. He thinks Laravel is the area where I'm getting the problem and I agree.

I also noticed in the .env the APP_ENV constant is set to "prod".

Thanks for any help I get. I've been stuck on this for two weeks.

Oct
30
2 months ago
Activity icon

Replied to How Do I Decrypt An Encrypted Mutator In A JSON Output?

Awesome, thank you. I created an API resource and it worked great.

Oct
29
2 months ago
Activity icon

Started a new Conversation How Do I Decrypt An Encrypted Mutator In A JSON Output?

What I'm trying to do is encrypt and decrypt data using mutators. The problem I'm having is that I am trying to have my value decrypt on output for a JSON api. The problem is when I output these values in the controller they're still encrypted. I was trying to figure out how to use transform on the collection, but gave up. I'm not sure I can use transform if I intend to paginate the out put as well.

Encryptable.php

<?php

namespace App;

use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable)) {
            $value = Crypt::decrypt($value);
            return $value;
        } else {
            return $value;
        }
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable)) {
            $value = Crypt::encrypt($value);
        }

        return parent::setAttribute($key, $value);
    }
}

Model

class Patient extends Model
{
    use Encryptable;

    protected $encryptable = [
        'blood_type',
        'medical_conditions',
        'allergies',
        'emergency_contact_id',
    ];
}

Controller

public index(Patient $patient)
{
    return $patient->orderBy('created_at','DESC')->get();
}

Thanks for any help

Oct
09
3 months ago
Activity icon

Started a new Conversation Switching From Tailwind Version 0.6.5 To 1.1.2 Having Problems With Classes And Not Sure How To Make A Smooth Transition?

So I've created a vue project that is using tailwind. What I have to do is port my Laravel projects vue frontend to a vue project. The original project uses Tailwind version 0.6.5 and the new project is using version 1.1.2. It seems like the color pallets classes like bg-grey and text-gray-darker have switched to bg-gray 500 and text-gray-900 is there anyway to quickly port these over without having to do a find and replace for every single color class? I have dozens of different colors that I'm using like this making this port pretty hard.

Also where is the old configuration tailwind.js where I can configure all of the colors? All the tailwind.config.js contains now is this:

module.exports = {
  theme: {
    extend: {}
  },
  variants: {},
  plugins: []
}

Am I screwed and have to essentially spend the week porting all of these colors over? Or is there an easier way to accomplish this?

Thank you

Sep
18
4 months ago
Activity icon

Replied to Composer: File Could Not Be Downloaded: Php_network_getaddresses: Getaddrinfo Failed: Nodename Nor Servname Provided, Or Not Known Failed To Open Stream:

@resin I totally can. It brings up JSON object with a bunch of hashes, but the packages array is empty: "packages":[]

Activity icon

Started a new Conversation Composer: File Could Not Be Downloaded: Php_network_getaddresses: Getaddrinfo Failed: Nodename Nor Servname Provided, Or Not Known Failed To Open Stream:

I'm trying to run composer require laravel/ui --dev and I keep getting:

The "https://repo.packagist.org/packages.json" file could not be downloaded: failed to open stream: Operation timed out Retrying with degraded mode, check https://getcomposer.org/doc/articles/troubleshooting.md#degraded-mode for more info

The "http://repo.packagist.org/p/provider-6.json" file could not be downloaded: php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known failed to open stream: php_network_getaddresses: getaddrinfo failed: nodename nor servname provided, or not known http://repo.packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date

[Composer\Downloader\TransportException] The "http://repo.packagist.org/p/laravel/ui%24687d9aece51281fb3e1f474fc56d17c91950485e557 c29774d39ed244b54b288.json" file could not be downloaded: php_network_getaddresses: getad drinfo failed: nodename nor servname provided, or not known failed to open stream: php_network_getaddresses: getaddrinfo failed: nodename nor servnam e provided, or not known

Does anyone know what's going on and how to fix this? I just installed php 7.2 using brew. So it could be something there, but I'm really not sure.