sbkl

sbkl

Member Since 3 Years Ago

Experience Points 61,300
Experience Level 13

3,700 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 657
Lessons
Completed
Best Reply Awards 0
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.

22 Jun
3 weeks ago

sbkl left a reply on Laravel Migration: Drop View With DB::statement Doesn't Work

@tray2 just put your answer as the correct one. Sorry for the delay!

20 May
1 month ago

sbkl left a reply on Laravel Migration: Drop View With DB::statement Doesn't Work

@tray2 thank you for your answer but it didn't change anything. I fixed the problem by adding IF NOT EXISTS to the up DB statement instead. Looks like the down statement is completely ignored:

CREATE VIEW IF NOT EXISTS

(using MariaDB)

19 May
2 months ago

sbkl started a new conversation Laravel Migration: Drop View With DB::statement Doesn't Work

Hi,

One of my migration is creating a dynamic view calculating stock. This is the DB statement in my Up function:

public function up() { DB::statement("CREATE VIEW product_variation_stock_view AS SELECT product_variations.product_id AS product_id, product_variations.id AS product_variation_id, COALESCE(SUM(stocks.quantity) - COALESCE(SUM(product_variation_order.quantity),0),0) as stock, CASE WHEN COALESCE(SUM(stocks.quantity) - COALESCE(SUM(product_variation_order.quantity),0),0) > 0 then true else false END in_stock FROM product_variations LEFT JOIN ( SELECT stocks.product_variation_id AS id, SUM(stocks.quantity) as quantity FROM stocks GROUP BY stocks.product_variation_id ) AS stocks USING(id) LEFT JOIN ( SELECT product_variation_order.product_variation_id AS id, SUM(product_variation_order.quantity) AS quantity FROM product_variation_order GROUP BY product_variation_order.product_variation_id ) AS product_variation_order USING(id) GROUP BY product_variations.id, product_variations.product_id "); } This is working great.

Here is the down function: public function down() { DB::statement("DROP VIEW IF EXISTS product_variation_stock_view"); }

When I run the query inside Sequel Pro, this is working well.

But when I run the migrate:fresh command, Laravel just ignore it and therefore the table is not dropped before to attempt to create this view again and fail because it already exists.

Any idea what I am doing wrong for the down function to work?

Thank you.

28 Apr
1 year ago

sbkl left a reply on Laravel Passport 500 Internal Server Error When Using Subdomain

my bad. just forgot to run that command on the server for that specific domain

php artisan passport:keys
27 Apr
1 year ago

sbkl started a new conversation Laravel Passport 500 Internal Server Error When Using Subdomain

Hi,

Using laravel passport on my local machine and domain http://myapp.test, I have no problem.

When I push the code to my server on my main domain https://myapp.com, again no problem.

However, I have a sudomain used for my live test (pre-production) before to push to the main domain in production. If I use https://dev.myapp.com, then I get a 500 internal server error.

Any idea how to fix it?

This is the guzzle call I'm doing:

$http = new GuzzleHttp\Client;

$response = $http->post('https://dev.myapp.com/oauth/token', [
    'form_params' => [
        'grant_type' => 'password',
        'client_id' => 'client_id',
        'client_secret' => 'client_secret_key',
        'username' => '[email protected]',
        'password' => '123456',
        'scope' => '',
    ],
]);

return $response;

If I change the url to my local or production website (changing the passport key and making sure the same user exists), it works properly.

17 Apr
1 year ago

sbkl left a reply on BroadcastServiceProvider Conditional Middleware For Auth Guard According To Route Request

Simply provide multiple guards to the auth middleware so it will know which guard using for authentication:

Broadcast::routes(['middleware' => ['web', 'auth:admin, master']]);
15 Apr
1 year ago

sbkl started a new conversation BroadcastServiceProvider Conditional Middleware For Auth Guard According To Route Request

Hi,

I want to implement multiple auth guard for the broadcasting routes.

One specific guard is listening on one specific route and this is the reason why I was thinking to use the path request to define which auth guard should be used.

The implementation below doesn't work. I don't get any error message. No feedback at all. The private channel doesn't work.

If I pass the string 'auth:admin' instead of the $guard variable, it works.

When I dd the attributes from the broadcastmanager, the result seems the same if I pass the string or the variable.

Any idea what I am doing wrong?

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Broadcast;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {

        $guard = \Request::path() === 'home' ? 'auth:admin' : 'auth:master';

        Broadcast::routes(['middleware' => ['web', $guard]]);
        
        require base_path('routes/channels.php');
    }
}
29 Oct
1 year ago

sbkl left a reply on WhereHas Checking Latest Record Of A Relationship Only

Thanks for your answer @Talinon . I wanted to avoid to filter through after the get() method as I understand it could have performance issue in case a large records.

Another idea I have is to set an active column on the status stable. This way I can use the whereHas with Requested status and an active value set to true.

Which means each time I create a new status, I need to set the previous status active field to false.

Would that be something ok in term of performance ?

sbkl started a new conversation WhereHas Checking Latest Record Of A Relationship Only

Hi,

I have Order and Status models as follow:

Order Model:

class Order extends Model
{
    public function statuses()
    {
        return $this->hasMany(OrderStatus::class);
    }

    public function latestStatus()
    {
        return $this->hasOne(OrderStatus::class)->latest();
    }

    public function scopeOpen($query)
    {
        return $query->whereHas('latestStatus', function($status) {

            $status->where('status','Requested');
        });
    }
}
Order table columns: id, user_id, order_number

Status Model:

class Status extends Model
{

    public function order()
    {
        return $this->belongsTo(Order::class);
    }
}
Status table columns: id, order_id, status, timestamps

One single Order got many Status in the lifecycle of an order that I want to keep track.

The query scope is here to help me fetching open orders only. The criteria to define an open order being that the latest status record of an order got the value 'Requested' in the status column.

If I have an order with two status record:

  • first record is created with the status 'Requested'
  • later, a second record is created with the status 'Completed'

Meaning the latest status record is 'Completed'.

When calling:

Order::with('latestStatus')->get()

The latest status only show the status 'Completed' for the order mentioned above and ignore the status record with 'Requested'. So here, it works as expected.

When I call the query scope Open of the Order model with the whereHas statement on the 'latestStatus' relationship as follow:

Order::open()->get()

Then, this query will still return the order even if its latest status is 'Completed' and not 'Requested'.

Any idea what I am missing?

20 Oct
1 year ago

sbkl left a reply on Laravel Intervention Image Upload To Amazon S3

Thanks @w1n78 Issue was about reencoding.

I used the stream() method on the image instance to do so instead of encode('jpg').

From the documentation: 'Encodes the current image in given format and given image quality and creates new PSR-7 stream based on image data.'

19 Oct
1 year ago

sbkl started a new conversation Laravel Intervention Image Upload To Amazon S3

Hi,

WHen I use the code below to resize an image with intervention image and then upload it to S3:

        $image = Image::make(request()->file('image'))->resize(400, 300);

        $path = Storage::disk('s3')->put('/public/items/test.jpg', $image->__toString());

Then the file is created in my S3 bucket but the file is empty (size 0 kb).

What am I doing wrong here?

Thanks

11 Oct
1 year ago

sbkl left a reply on WhereDate With Applying Specific Timezone To Created_at Field Before Filtering

Hi guys,

Not sure it is the best way but I set the carbon today's date parameter to the desired timezone and then convert it back to UTC to make the query and I get the desired result:

$latestOrderNumber = $user->orders()->whereDate('created_at', '=', Carbon::today('Asia/Hong_Kong')->timezone('UTC')->toDateString())->latest()->first();

Good enough for me.

10 Oct
1 year ago

sbkl started a new conversation WhereDate With Applying Specific Timezone To Created_at Field Before Filtering

Hi,

My default timezone is UTC in laravel config and I want to be able to manage dates according to the user location and timezone.

How could I apply a specific timezone to a created_at field before filtering with whereDate clause?

$latestOrderNumber = $user->orders()->whereDate('created_at', '=', Carbon::today('Asia/Hong_Kong')->toDateString())->latest()->first();

Try to set a getter by default but the whereDate clause ignore it and just take the initial value:

    public function getCreatedAtAttribute($value)
    {
        return Carbon::parse($value)->timezone('Asia/Hong_Kong');
    }

My project is international and the timezone above would be defined dynamically. I just pick one timezone to illustrate the example.

Thank you.

10 Sep
1 year ago

sbkl started a new conversation Npm Run Watch Not Working - Error: Spawn EACCES - @ Watch: `cross-env NODE_ENV=development Node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`

Hi,

Here is the error below I get when running npm run dev/watch since today (both current project and when I create a new one).

Deleted my node modules and ran 'npm install'. I also updated manually "vue-template-compiler": "^2.4.2" to match the vue version as I had an error message related to this.

Any idea?

Package.json:

{
  "private": true,
  "scripts": {
    "dev": "npm run development",
    "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
    "watch-poll": "npm run watch -- --watch-poll",
    "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
    "prod": "npm run production",
    "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
  "devDependencies": {
    "axios": "^0.15.3",
    "cross-env": "^5.0.5",
    "laravel-mix": "0.*",
    "lodash": "^4.17.4",
    "vue": "^2.4.2"
  },
  "dependencies": {
    "animate.css": "^3.5.2",
    "autosize": "^3.0.20",
    "bulma": "^0.5.1",
    "cropperjs": "^1.0.0-rc.3",
    "laravel-echo": "^1.3.2",
    "moment": "^2.18.1",
    "pusher-js": "^4.1.0",
    "query-string": "^4.3.4",
    "vue-js-toggle-button": "^1.1.2",
    "vue-scrollto": "^2.7.5",
    "vue-template-compiler": "^2.4.2",
    "vuejs-datepicker": "^0.9.11"
  }
}

Webpack.mix.js:

const { mix } = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.sass', 'public/css');

Error:

> @ watch /Users/sbkl/code/test
> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

 10% building modules 1/1 modules 0 active                                    . Webpack is watching the files…

 95% emitting

 DONE  Compiled successfully in 3920ms                                                                                                                                        6:46:07 PM

internal/child_process.js:319
    throw errnoException(err, 'spawn');
    ^

Error: spawn EACCES
    at exports._errnoException (util.js:1050:11)
    at ChildProcess.spawn (internal/child_process.js:319:11)
    at exports.spawn (child_process.js:378:9)
    at Object.exports.execFile (child_process.js:143:15)
    at Object.module.exports.fileCommand (/Users/sbkl/code/appero/node_modules/node-notifier/lib/utils.js:53:13)
    at NotificationCenter.notify (/Users/sbkl/code/appero/node_modules/node-notifier/notifiers/notificationcenter.js:66:11)
    at module.exports.WebpackNotifierPlugin.compilationDone (/Users/sbkl/code/appero/node_modules/webpack-notifier/index.js:62:18)
    at Compiler.applyPlugins (/Users/sbkl/code/appero/node_modules/tapable/lib/Tapable.js:61:14)
    at Watching._done (/Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:92:17)
    at /Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:75:18
    at Compiler.emitRecords (/Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:362:37)
    at /Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:58:19
    at /Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:355:11
    at next (/Users/sbkl/code/appero/node_modules/tapable/lib/Tapable.js:154:11)
    at Compiler.compiler.plugin (/Users/sbkl/code/appero/node_modules/webpack/lib/performance/SizeLimitsPlugin.js:99:4)
    at Compiler.applyPluginsAsyncSeries1 (/Users/sbkl/code/appero/node_modules/tapable/lib/Tapable.js:158:13)
    at Compiler.afterEmit (/Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:352:8)
    at Compiler.<anonymous> (/Users/sbkl/code/appero/node_modules/webpack/lib/Compiler.js:347:14)
    at /Users/sbkl/code/appero/node_modules/webpack/node_modules/async/dist/async.js:421:16
    at iteratorCallback (/Users/sbkl/code/appero/node_modules/webpack/node_modules/async/dist/async.js:998:13)
    at /Users/sbkl/code/appero/node_modules/webpack/node_modules/async/dist/async.js:906:16
    at /Users/sbkl/code/appero/node_modules/graceful-fs/graceful-fs.js:43:10
    at FSReqWrap.oncomplete (fs.js:114:15)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ watch: `cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
18 Jul
2 years ago

sbkl left a reply on Foreach Array Only Get The First Record

Now working after restating my mac. Weird...

sbkl started a new conversation Animation On Scroll - Just Discovered AOS Library

Just to share if anyone looking for implementing this animation.

A client requested an animation to display boxes on scroll.

Just discovered AOS library and implemented a fadeIn fadOut animation in few minutes. Didn't go further but it looks great!

github:

https://github.com/michalsnik/aos

setup

npm install aos --save

app.sass

@import "~aos/dist/aos.css"

They are quite a few animations available out of box (check documentation) but you can still implement your own animation. Below an example with fade animation:


[aos="fade"]
  opacity: 0
  transition-property: opacity

[aos="fade"].aos-animate
  opacity: 1

bootstrap.js

window.AOS = require('AOS');
AOS.init();

in any blade or vue file:

<div data-aos="fade" data-aos-duration="1000">
    <h1>hello world</h1>
</div>

What do you use @JeffreyWay for Laracasts?

Let me know if this was useful!

17 Jul
2 years ago

sbkl started a new conversation Foreach Array Only Get The First Record

Hi,

I'm doing an ajax request as follow passing an array of objects to an axios post call.

When I use foreach to loop through the array, the loop only works for the first object and ignore the others completely.

Any idea?

Let me know if it is not clear. Thanks.

Axios call:

let order = [{item_id: 1, qty: 1}, {item_id: 2, qty: 3}];

axios.post('orders', {order: order});

Route

Route::post('orders', '[email protected]');

Controller

    public function store()
    {
        foreach(request()->order as $order) {

            auth()->user()->orders()->create([
            'item_id' => $order['item_id'],
            'qty' => $order['qty']
        ]);
        }

        return ['message' => 'Completed'];
    }
06 Jul
2 years ago

sbkl left a reply on Laravel Passport With Pusher: Private Channel Authentication Using React Native

The thing is I need to use the broadcast routes for both web and api guards. How would you manage that?

30 Jun
2 years ago

sbkl left a reply on Laravel Passport With Pusher: Private Channel Authentication Using React Native

Actually, for external app, an auth route should be setup and return a token from pusher library.

Documentation below

https://pusher.com/docs/authenticating_users#implementing_private_endpoints

27 Jun
2 years ago

sbkl started a new conversation Laravel Passport With Pusher: Private Channel Authentication Using React Native

I want to setup a private channel with pusher for broadcasting events between my laravel app and my react native app.

I'm using laravel passport for the oauth server.

And here is what I have implemented:

react native pusher channel subscription:

let token = 'oauthUserToken';

    var pusher = new Pusher('pusher_key', {
        authEndpoint: 'http://url.com/broadcasting/auth',
        auth: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + token
            }
        },
        cluster: 'ap1',
        encrypted: true
    });

var channel = pusher.subscribe('private-hello');

Event class:

class HelloPusher implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;

    public function __construct($message)
    {
        $this->message = $message;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('hello');
    }
}

routes/channels.php:

Broadcast::channel('hello', function () {
    return true;
});

BroadcastingServiceProvider is commented out in the config/app.php.

And I keep having Pusher : Couldn't get auth info from your webapp : 500.

When I use laravel Echo and Vue on the webapp, private channel subscription is working properly.

I believe it is related to the fact the Broadcast event can't find any user logged in. Any way to use the oauth authorization from laravel passport instead?

Thank you

19 Apr
2 years ago

sbkl left a reply on ES6 - .find Doesn't Work

Just need to add the type 'text/bable' to the script tag and no more error from phpStorm.

<script type="text/babel">
12 Apr
2 years ago

sbkl left a reply on Access Public Variable From Notification To Markdown Mail

Finally got how this is working.

Markdown don't have the same scope than blade templates. Therefore, you can't access the variables the same way. At least, this is what I understood after some research.

This is how to achieve what I wanted to do:

5- Notification

    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('Contact request received')
                    ->greeting('Hello ' . $this->contact->firstName . ',')
                    ->markdown('mail.contact.confirmationToUser');
    }

6- Markdown template

@component('mail::message')
# {{ $greeting }}

This is to acknowledge the reception of your contact request.

I will get in touch with you ASAP.

Best regards,<br>

@endcomponent
11 Apr
2 years ago

sbkl started a new conversation Access Public Variable From Notification To Markdown Mail

Hello,

I'm working on a contact page for my app.

The process I follow:

1- The contact controller create the message from the user $contact = Contact::create(request(['firstName', 'lastName', 'email', 'message'])); 2- The contact controller submit an event event(new ContactCreated($contact)); 3- The listener associated dispatch a new job dispatch((new QueueEmailConfirmation($event->contact))->onQueue('email')); 4- The job makes the notification $this->contact->notify(new EmailConfirmationToUser($this->contact)); 5- Here is the notification markdown public function toMail($notifiable) { return (new MailMessage)->markdown('mail.contact.confirmationToUser'); } 6- In the markdown template, I try to access the variable {{ $contact->firstName }} but the email doesn't work. When I remove the $contact variable, all is working. ` @component('mail::message')

Hello {{ $contact->firstName }}

This is to acknowledge the reception of your contact request.

I will get in touch with you ASAP.

Best regards,

@endcomponent `

Regarding the $contact variable, I make it public and add it to the constructor for the job and the notification like so: ` public $contact;

public function __construct(Contact $contact) // Contact model is added to the top
{
    $this->contact = $contact;
}

`

Any idea?

Thanks.

29 Jan
2 years ago

sbkl left a reply on Laravel Controller Specifying The Resource Model AND Migration?

@Snapey thanks for the answer. Still this is not taking advantage of the new resourceful controller command.

sbkl started a new conversation Laravel Controller Specifying The Resource Model AND Migration?

Laravel 5.4 provides the useful way to create a model related to controller all together.

php artisan make:controller PhotoController --resource --model=Photo

A very handful way of creating a migration related to a model was to use

php artisan make:model Photo -m

The '-m' parameter enabling to create the related migration file to the model created.

Is there a command to create the controller, model and migration all together?

22 Nov
2 years ago

sbkl left a reply on ES6 - .find Doesn't Work

My bad. Error not related to this function. it's working properly.

The only issue is that phpstorm still gives me issues about the company variable and the arrow syntax even if I have set ES6 as javascript language in my preferences...

sbkl left a reply on ES6 - .find Doesn't Work

thanks @BakriMoharram but still same result.

sbkl started a new conversation ES6 - .find Doesn't Work

Hello,

I want to use the following function using vue and ES6:

find_company(object)
{
    return this.companies.find(company => company.id == object.id)
}

However, phpstorm mentions it cannot find the variable company and I have the same feedback when testing this function.

Any idea?

20 Nov
2 years ago

sbkl started a new conversation Thank You Jeffrey For Your Work!

Glad to share my first live web app since I joined laracasts a year ago to support a charity initiative: www.bubblespirit.run

Thank you @JeffreyWay for your work.

08 Nov
2 years ago

sbkl left a reply on Props Issue With Vue 2

@prasinoulhs Thanks

:active-user="{{ Auth::User() ? Auth::User() : "''" }}" did the trick. Was missing the '' inside the quote.

07 Nov
2 years ago

sbkl left a reply on Props Issue With Vue 2

@ejdelmonico Thanks.

It is related with the fact that interpolation has been been removed within attributes.

So within vue template, no problem. I can adapt with the new way of doing.

However, this new rule is in conflict with blade statement to send php variables to vue components.

Anyone having the same issue here?

06 Nov
2 years ago

sbkl started a new conversation Props Issue With Vue 2

Hello,

With vue.js 1, I used to get my current user in my blade template within a props as follow:

<my-component :active-user="{{ Auth::User() ? Auth::User() : '' }}"></my-component>

This is still working only if an user is authenticated. If not, the template cannot load.

I have the following workaround:

<my-component :active-user="[{{ Auth::User() ? Auth::User() : '' }}]"></my-component>

which is not ideal as it returns an array of object where it is supposed to be a single object. For instance:

  • Check if activeUser

v-if="activeUser" becomes v-if="activeUser.length > 0"

  • Access user data

{{ activeUser.firstName }} becomes {{ activeUser[0].firstName }}

Doesn't feel right to me.

Any idea how to fix this?

Thank you.

05 Nov
2 years ago

sbkl started a new conversation Import Css File From Node_modules To Resources/assets/css

Hello,

For instance, I have installed the normalize.css library through npm.

Now, I would like to import it to my resources/assets/css/app.css file just like we can import bootstrap-sass into the resources/assets/sass/app.scss with

@import "node_modules/bootstrap-sass/assets/stylesheets/bootstrap";

In my app.css, I put the following line:

@import "../../../node_modules/normalize.css/normalize.css";

Then I run gulp (detail below), I can see the app.css file is included in the process. But nothing from the library is compiled.

Any idea?

For all my js libs, I require them in my app.js file. And I would like to do the same for css libs as well.

My gulp config:

const elixir = require('laravel-elixir');

require('laravel-elixir-vue-2');

elixir((mix) => {
    mix.sass('app.scss')
    .styles([
        'app.css'
    ], 'public/css/app.css')
    .webpack('app.js');
});
02 Nov
2 years ago

sbkl left a reply on How To Use Highlight.js With Laravel 5.3 And Vue

Solved as follow: Using v-for to add a pre/code tags pair in the DOM each time I update the text value and then only display the latest div.

template:

<div v-for="(item, index) in items">
    <pre v-if="index == items.length - 1">
        <code class="html">{{ text }}</code>
    </pre>
</div>

script:

var hljs = require('highlight.js');

export default
{
    data()
    {
        return{
            text:'',
            items:[]
        }
    },
    mounted()
    {
        hljs.initHighlightingOnLoad();
    },
    watch:
    {
        text(text)
        {
            var item = {item:text};
            this.items.push(item);
            this.$nextTick(function () {
                hljs.initHighlighting.called = false;
                hljs.initHighlighting();
            });
        }
    }
}
31 Oct
2 years ago

sbkl left a reply on How To Use Highlight.js With Laravel 5.3 And Vue

In fact, I needed to require and call highlight.js in my component instead of my root file.

It is now working on page load.

However, can't still make the color highlight on textarea change.

Tried to use @change and a watcher with

hljs.initHighlighting.called = false;
hljs.initHighlighting();

But nothing happens.

sbkl left a reply on How To Use Highlight.js With Laravel 5.3 And Vue

@WebKenth Thanks. Now I have some progress. I get the tag with the class 'html hljs' expected. However, it is not processing the text inside to split it in different span with highlight.js classes.

sbkl started a new conversation How To Use Highlight.js With Laravel 5.3 And Vue

Hello,

Cannot figure out how to make work highlight.js inside my laravel application.

installed highlight.js through npm.

Anything I am doing wrong here?

in my app.js

var hljs = require('../../../node_modules/highlight.js/lib/highlight');

const app = new Vue({
    el: '#app',
    ready()
    {
        hljs.initHighlightingOnLoad();
    }
});

html

<pre>
    <code class="html">{{ text }}</code>
</pre>
28 Oct
2 years ago

sbkl left a reply on Csrf Token Encryption From IOS To Submit Form To Laravel App.

@firemaps

Now using laravel 5.3 with passport new feature. Works perfectly.

Follow the doc here: https://laravel.com/docs/5.3/passport#installation (Front end quick start is not necessary)

Once all the steps done, your laravel app is now ready with a oauth 2.0 config using Password Grant.

The command

php artisan passport:install

has created 2 oauth clients in your oauth_clients.

Let's say your laravel app folder is called 'laravel'.

The one you can use for your iOS app is the one with the id of 2 with a name of: laravel Password Grant Client

client_id:2 client_secret: thisIsMyClientSecretEntry

client_secret being under the column 'secret'.

In my iOS app, using swift 3 with Alamofire and SwiftyJSON libraries, here is a simplified code to make the login request - - laravel.dev being the base url of your laravel app

  • /oauth/token is route coming from
Passport::routes();

setup in the AuthServiceProvider.

func login(email: String, password: String) {
        
    let url = "laravel.dev/oauth/token"
        
    let params = [
                  "grant_type":"password",
                      "client_id": "2",
                      "client_secret": "thisIsMyClientSecretEntry",
                      "username": email,
                      "password": password]
        
    Alamofire.request(url, method: .post, parameters: params).responseJSON { response in
            
        switch response.result {
                
        case .success(let data):
                
            let json = JSON(data)

            print("token:\(json)")
    }
}

You should receive the long life token, token refresh and expiry date. No csrf issues.

Hope this helps.

25 Oct
2 years ago

sbkl left a reply on Animate An Object Along A Circle: Not Centered On Safari

Ok fixed. The issue is about the position:absolute. With Chrome, it is enough to center the objects in the middle of the wrapper with flex while it is necessary to center the images "manually" for safari.

I have added:

  • "position:relative" to the wrapper => this way the absolute position of the images refers to the wrapper. Not the full screen.
  • Then I have added top and left parameters to center the objects in the middle on the wrapper

Works perfectly now.

Here is the final code:

HTML:

                <div class="wrap">

                    <img  class="object_img" src="/images/bubble.png"> // image in the center of the circle.

                    <div class="object" style="animation-delay:-40s">

                        <img  class="object_img first_img" src="/images/Xavier.png">

                    </div>

                    <div class="object" style="animation-delay:-30s">

                        <img  class="object_img" src="/images/David.png" style="animation-delay:-30s">

                    </div>

                    <div class="object" style="animation-delay:-20s">

                        <img  class="object_img" src="/images/Fred.jpeg" style="animation-delay:-20s">

                    </div>

                    <div class="object" style="animation-delay:-10s">

                        <img  class="object_img" src="/images/Valentin.png" style="animation-delay:-10s">

                    </div>

                </div>

CSS:

    .wrap
    {
        border-radius:50%;width:200px;height:200px;        
        display:flex;
        align-items:center;
        justify-content:center;
        position:relative;
    }
    .object
    {
        border-radius:50%;width:60px;height:60px;
        position:absolute;top:70px;left:70px;
        animation: rotate 40s infinite linear;
        transform: translateX(100px);
    }

    .object_img
    {
        border-radius: 50%;width:60px;height:60px;
        animation: zrotate 40s infinite linear;
        animation-direction: reverse;
    }

    @keyframes rotate {

        from {
            transform: rotate(0deg) translateX(100px);
        }
        to {
            transform: rotate(360deg) translateX(100px);

        }
    }

    @keyframes zrotate {

        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }

Note that the -webkit- prefix is not even necessary here.

24 Oct
2 years ago

sbkl left a reply on Laravel 5.3 Install - Ubuntu Lemp On 16.04 - Php7

Hello @balistikbill , Good question!

I was seeing the homepage from digitalocean. After checking more in detail, the issue is that my nginx file 'default' in sites-available was not duplicated inside the folder sites-enabled! Which was the case before by default.

I have made the duplication and remove digitalocean html page and it is now working!

Stupid issue that took me 5 hours to solved.

sbkl started a new conversation Animate An Object Along A Circle: Not Centered On Mobile Safari

I have worked on this animation (object moving along the edge of a main circle) and it is working well on desktop.

https://laracasts.com/series/whatcha-working-on/episodes/6

However on safari mobile, I cannot figure out how to keep the pictures following the edge of the main circle.

I guess the issue has something to do with the translateX part as the animation is working and making a circle. It is just not centered.

I have already added the webkit prefix and it doesn't change anything: HTML:

        <div class="wrap">

            <div>
                <h3>The team</h3>
            </div>
            <div class="object" style="animation-delay:-40s">

                <img  class="object_img first_img" src="/images/Xavier.png">

            </div>

            <div class="object" style="animation-delay:-30s">

                <img  class="object_img" src="/images/David.png" style="animation-delay:-30s">

            </div>

            <div class="object" style="animation-delay:-20s">

                <img  class="object_img" src="/images/Fred.jpeg" style="animation-delay:-20s">

            </div>

            <div class="object" style="animation-delay:-10s">

                <img  class="object_img" src="/images/Valentin.png" style="animation-delay:-10s">

            </div>

        </div>

CSS: note I have two keyframes with rotation animation. One for the image wrapper (object) going around the circle. One for the image which is doing the rotation animation in a reverse way so the image stays in the right direction.

    .wrap
    {
        background:blue;
        width:200px;
        height:200px;
        border-radius:50%;
        display:flex;
        align-items:center;
        justify-content:center;
    }
    .object
    {
        width:60px;
        height:60px;
        border-radius:50%;
        animation: rotate 40s infinite linear;
        position:absolute;
        -webkit-transform: translateX(100px);
        transform: translateX(100px);
    }
    .object_img
    {
        border-radius: 50%;width:60px;height:60px;
        animation: zrotate 40s infinite linear;
        animation-direction: reverse;
    }
    @keyframes rotate {

        from {
            -webkit-transform: rotate(0deg) translateX(100px);
            transform: rotate(0deg) translateX(100px);


        }
        to {
            -webkit-transform: rotate(360deg) translateX(100px);
            transform: rotate(360deg) translateX(100px);

        }
    }

    @keyframes zrotate {

        from {
            -webkit-transform: rotate(0deg);
            transform: rotate(0deg);
        }
        to {
            -webkit-transform: rotate(360deg);
            transform: rotate(360deg);
        }
    }
23 Oct
2 years ago

sbkl left a reply on Laravel 5.3 Not Sending Emails In AWS EC2 Ubuntu 16.04

ipv6 issue? ran into issue with a gmail account to send emails and used this workaround for linux:

sudo nano /etc/gai.conf

Uncomment the following line (remove the #):

precedence ::ffff:0:0/96 100

Source: https://www.digitalocean.com/community/questions/how-to-disable-ubuntu-14-04-ipv6

sbkl started a new conversation Laravel 5.3 Install - Ubuntu Lemp On 16.04 - Php7

Hello,

I have succeed to install a laravel project on ubuntu 16.04 lemp server with php7.

The last step I have done is to give the writable permissions to storage and bootstrap/cache folders as requested in the laravel documentation as follow:

sudo chmod -R 775 storage bootstrap/cache

However, I'm still not able to see the laravel homepage.

Any idea?

29 Sep
2 years ago

sbkl started a new conversation Use Javascript Modules Installed Through Npm

Hello,

Let's take the example of one recent video from Jeff related to autosize package.

I've done the 'npm install autosize' command to install the package.

In my app.js, I put the following code:

import autosize from 'autosize';

The "from 'autosize'" part is underlined in red and the warning message from phpstorm says that the module is not installed.

How do I fix that and get access to javascript modules installed though npm?

Thank you.

23 Sep
2 years ago

sbkl started a new conversation Laravel Echo Redis Socket.io : Echo Doesn't Catch The Event

Hello,

I try to use laravel echo with redis and socket.io.

It seems Echo doesn't catch my event.

Any idea about what I am doing wrong?

If I listen the event the old way, it is working properly.

var socket = io('http://192.168.10.10:3000');
        socket.on("message-channel:App\\Events\\MessageSent", function(message){
            console.log('listening');
        });

But with laravel echo like below, nothing happens.

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: 'http://192.168.10.10:3000'
});

window.Echo.channel('message-channel')
    .listen('MessageSent', (e) => {
        console.log('Listening');  //No log appears on the console.
    });

Below my config:

Package.json

{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "bootstrap-sass": "^3.3.7",
    "gulp": "^3.9.1",
    "jquery": "^3.1.0",
    "laravel-elixir": "^6.0.0-9",
    "laravel-elixir-browserify-official": "^0.1.3",
    "laravel-elixir-vueify": "^2.0.0",
    "lodash": "^4.14.0",
    "vue": "^1.0.26",
    "vue-resource": "^0.9.3"
  },
  "dependencies": {
    "express": "^4.14.0",
    "ioredis": "^2.3.0",
    "laravel-echo": "^1.0.5",
    "pusher-js": "^3.2.1",
    "socket.io": "^1.4.8"
  }
}

socket.js file

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var Redis = require('ioredis');
var redis = new Redis();
redis.subscribe('message-channel', function(err, count) {
});

redis.on('message', function(channel, message) {
    console.log('Message Received: ' + message);
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

http.listen(3000, function(){
    console.log('Listening on Port 3000');
});

Event class

<?php

namespace App\Events;

use App\Message;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class MessageSent implements ShouldBroadcast
{
    use InteractsWithSockets, SerializesModels;

    public $message;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return [
            'message-channel'
        ];
    }
}

Message controller:

<?php

namespace App\Http\Controllers;

use App\Message;
use App\Events\MessageSent;
use Illuminate\Http\Request;
use App\Http\Requests;

class MessagesController extends Controller
{
    public function index()
    {
        $messages = Message::all();
        
        return view('messages.index', compact('messages'));
    }

    public function store(Request $request)
    {
        $message = Message::create($request->all());

        broadcast(new MessageSent($message));

        return $message;
    }
}
21 Sep
2 years ago

sbkl left a reply on Gulp Doesn't Compile Changes With Laravel 5.3

It is about js files. I started a complete new project with laravel 5.3 using browserify and seems to work fine now. I guess went wrong when I did my migration...

10 Sep
2 years ago

sbkl left a reply on Gulp Doesn't Compile Changes With Laravel 5.3

I put laravel-elixir 5 back until the v6 is more stable.

09 Sep
2 years ago

sbkl started a new conversation Gulp Doesn't Compile Changes With Laravel 5.3

Hello,

Anyone encounters this issue?

I run gulp with no error. Once completed, the file version is not updated with the new code nor the standard app.js.

Here is my gulp file:

const elixir = require('laravel-elixir');

require('laravel-elixir-vue');
require('laravel-elixir-vueify');

elixir(mix => {
    mix.sass('app.scss').styles(['vendor/lity.min.css'], 'public/css/vendor.css');

    mix.scripts([
        'vendor/jquery.js',
        'vendor/bootstrap.js',
        'vendor/socket-io.min.js',
        'vendor/vue.js',
        'vendor/vue-resource.js',
        'vendor/lity.min.js'
    ],'./public/js/vendor.js')
        .browserify('main.js','./public/js/app.js')
        .version([
            'public/css/app.css',
            'public/css/vendor.css',
            'public/js/vendor.js',
            'public/js/app.js'
        ]);
});