fabricecw

fabricecw

Member Since 4 Years Ago

St. Gallen

at St. Gallen

Experience Points 26,935
Experience Level 6

3,065 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 188
Lessons
Completed
Best Reply Awards 16
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.

07 Jul
1 week ago

fabricecw left a reply on Complex Query Performance

This won't work since you can't use last() method in a query builder instance.

06 Jul
1 week ago

fabricecw started a new conversation Complex Query Performance

Hey!

I need to track statuses on an order model. It's a many to many relationship between order and status, since an order has multiple statuses and a status is used in many orders.

Now there is always the "current" and the "next" status of the order. The status sequence is controlled by a "step" integer in the pivot.

| order_id | status_id | step | completed_at | | ------------- | --------------| ------| ----------------| | 1 | 1 | 10 | 2019-0706 16:00 | | 1 | 2 | 20 | null | | 1 | 3 | 30 | null |

Status relationship

/**
 * Get the order's statuses.
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function statuses()
{
    return $this->belongsToMany('App\Status')->using('App\OrderStatus')->withPivot('completed_at', 'user_id', 'step')->orderBy('pivot_step');
}

Next status:

/**
 * The status of the order which is in progress.
 *
 * @return Status
 */
public function statusInProgress()
{
    return $this->statuses()->wherePivot('completed_at', null)->first();
}

Current status:

/**
 * The last completed status.
 *
 * @return Status
 */
public function lastCompletedStatus()
{
    return $this->statuses()->wherePivot('completed_at', '!=', null)->get()->last();
}

And obviously when it comes to filtering, users want filter by all orders which are in a specific status. How can I query the orders in a performant way?

Currently I have to loop over all the orders and check if the methods return is equal to the filtered status...

I have considered about the following approaches:

  • Store the current and next status id directly on the order -> redudant data
  • MySQL views

Is there a better approach to do that? Thanks for your help!

26 Jun
3 weeks ago

fabricecw left a reply on Password Validate Rules

For repetitive characters, you can use the following regex:

(.)\1{3,}

While the 3 stands for the minimum number of repetitive characters.

fabricecw left a reply on Reusing Called Accessor

I don't expect it in my code. But I don't know why Laravel itself doesn't write the value into the Model as an attribute when using an accessor. I'm talking about the framework functionallity.

25 Jun
3 weeks ago

fabricecw left a reply on @foreach Loop Not Working? Laravel 5.8.24 (WAMP) W10

The migration should also work like this:

public function up()
    {
        Schema::create('replies', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('thread_id');
            $table->integer('user_id');
            $table->text('body');
            $table->timestamps();
        });
    }

Are there any replies with the specific thread id if you take a look into your DB?

fabricecw left a reply on Reusing Called Accessor

Yeah sure. But (for me) this doesn't answer why Laravel doesn't store the value as an attribute when using an accesor the first time The next times it get's called, the accessor should check if the attribute already exists. This doesn't depend if the accessor loads a relationship or do something else.

fabricecw left a reply on How To Get A Method Working In Vue, The Same Way As It Does In The Backend

This package sends the form request via axios. So just use

this.user = response.data.user;
window.location = '/users/' + this.user.id

When everything is fine (no errors).

fabricecw left a reply on How To Get A Method Working In Vue, The Same Way As It Does In The Backend

You cannot use "redirect" on JSON requests. Laravel responses asynchronous to Axios (AJAX) - not to your "browser".

So a solution to make a redirect would be:

And your controller:

public function store(StoreContactRequest $request)
{
    $user = $this->userRepository->store($request);
    
    // Flash to session
    $request->session()->flash('flash', User successfully created.');
    
    return response()->json(compact('user'));
}

So, if axios get the created user successfully, it will redirect to the new user and flash the message.

fabricecw left a reply on @foreach Loop Not Working? Laravel 5.8.24 (WAMP) W10

Can you post the dump from a dd()?

public function show(Thread $thread)
    {
        dd($thread->replies);
        return view('threads.show', compact('thread'));
    }

fabricecw left a reply on How To Get A Method Working In Vue, The Same Way As It Does In The Backend

I'm not sure what you're really looking for... But for example...

Your Vue component:

axios
                    .post('/api/users', {
                        params: {
                            username: this.username,
                name: this.name,
                        }
                    })
                    .then(function(response) {
                        this.user = response.data.user.;
                    }.bind(this))
                    .catch(function(error) {
                        console.log(error)
                    }.bind(this));
            },

If you need a JSON response instead of a page:

if(request()->wantsJson()) {
    return response()->json(compact('user'));
}

fabricecw left a reply on Reusing Called Accessor

Thanks @snapey ! I think the class variable is the easiest approach and almost the same as the attribute.

Is there a reason why Eloquent doesn't write the attribute to the Model on the first time?

fabricecw started a new conversation Reusing Called Accessor

I'm using an accessor which loads a custom relationship field:

public function getHandoverDedicatedAreaAtAttribute()
    {
        $activity = $this->activities()->select('created_at')->where('status', 6)->first();

        if($activity) {
            return $activity->created_at;
        }

        return null;
    }

And in another accessor, I call the accessor above:

public function getIsOverdueAttribute()
    {
        return Carbon::parse($this->handover_dedicated_area_at) > Carbon::parse($this->delivery_at);
    }

But as I analyzed with Debugbar, if I call the is_overdue and handover_dedicated_area_at attributes, the query from getHandoverDedicatedAreaAtAttribute() is called twice.

Is there a way to reduce this to one query and use the attribute value from the Model once it's loaded?

28 Feb
4 months ago

fabricecw left a reply on Callback / Anonymous Functions

Sorry, the $like approach works correctly. I had a third array which wasn't valid. Now I'm calling the anonymous function this way:

('$' . $search['operator'])($search['filter'], $search['field']);

Is this a common approach or is there something better? ;-)

fabricecw started a new conversation Callback / Anonymous Functions

Hi

I try to understand callback / anonymous function but it still confuses me a lot... I tried to write callback functions for operational filters:

public function scopeSearch($query)
    {
        $like = function($value, $field) use($query) {
            $test = $value;
            $query->where($field, 'like', '%' . $test);
        };

        $match = function($value, $field) use($query) {
            $query->where($field, $value);
        };

        $searchable = [
            [
                'field' => 'client_reference',
                'operator' => 'like',
                'filter' => request()->filterClientReference
            ],

            [
                'field' => 'article_number',
                'operator' => 'like',
                'filter' => request()->filterArticleNumber
            ],

            [
                'field' => 'value_stream_id',
                'operator' => 'match',
                'filter' => function() {
                    if(request()->filterValueStream == 'auth') {
                        return auth()->user()->valueStream->id;
                    }
                    else if(isset(request()->filterValueStream)) {
                        return request()->filterValueStream;
                    }

                    return null;
                }
            ],
        ];

        foreach($searchable as $search) {
            if($search['filter']) {
                // Here it should call the right function... Hardcoded example:
        $like($search['filter'], $search['field']); // But this also isn't working...
            }
        }

        return $query;
    }

Maybe I'm on a totally wrong way.

26 Feb
4 months ago

fabricecw started a new conversation Fluent Pivot Scope

Hi

I try to keep my models as clean as possible. But when it comes to pivot scopes, I'm unsure what the cleanest approach could be.

I need to filter through a pivot column completed_at:

$this->statuses()->wherePivot('completed_at', null)->get();

But it would be much more readable this way:

```$this->statuses()->incomplete()->get();````

What's the best way to do make it this fluent? And should it be done this way?

Many thanks and regards,

20 Feb
4 months ago

fabricecw left a reply on Status Template Class

If better explanation would be helpful, let me know. :-)

19 Feb
4 months ago

fabricecw started a new conversation Status Template Class

Hey

I try to implement a clean progress handling for orders. A order has many statuses and they can be completed via a button in the frontend or an API request. But a status should contain:

  • Name

  • Logic policies: For example, the user can only complete a status "shipping" if a field "address" is defined in the order. Otherwise the status can't be completed.

  • Authorization policies: Like Laravel Policies, only authorized user for this status can complete it.

I thought about a custom PHP class, but I'm still unsure about the best approach.

An order has a status "template". When the order is created, all needed statuses will be created in a subtable in the right order. Because some orders need an approval, others can be executed directly.

We already have a order progress handling, but it's a mess: An order has a "status" integer field. The user completes the status by submitting a "complete_status" integer to an update function. In the update function, I check for each status if it can be completed:

public function updateStatus()
{
    if(request('complete_status') == $order->status) {
        // For example status 2 is the "start shipping" status
        if($order->status == 2) {
            if(! $order->addressAvailable) {
                abort(403, 'You can't start shipping with no address.');
            }

            if($order->needsApproval()) {
                $order->status = 3;
            } else {
                $order->status = 4;
            }
        }

        if($order->status == 3) {
            // Code for status 3...
        }
    
    } else {
        abort(403, 'This status can't be complete.');
    }
}

And in the frontend, I check the same logic to show/disable the buttons...

Any ideas or hints? Thanks in advance :-)

01 Feb
5 months ago

fabricecw left a reply on Testing Touches With More Performance

Oh great, didn't know about this Carbon method!

31 Jan
5 months ago

fabricecw started a new conversation Testing Touches With More Performance

Hi

I'm testing touches with the sleep function:

CommentTest:

/** @test  */
    public function it_touches_the_orders_timestamp()
    {
        $order = factory('App\Order')->create();

        sleep(1);

        $comment = $order->comments()->create(factory(OrderComment::class)->raw());

        $this->assertEquals($order->fresh()->updated_at, $comment->updated_at);
    }

But this means heavy time consumptions. Is there a way to "mock" the time?

30 Jan
5 months ago

fabricecw started a new conversation Create Multiple Records On Relationship With A Factory

I try to test a morphMany relationship:

/** @test */
    public function it_has_packagings()
    {
        $variant = factory(Variant::class)->create();

        $variant->packagings()->create(factory(Packaging::class, 10)->raw());

        $this->assertCount(10, $variant->packagings);
    }

But the factory outputs the records inside an array. What's the best way to create multiple records on a relation?

fabricecw left a reply on Ubuntu Server Doesn't Send Emails?

Please provide all the requested information above.

Per default, Laravel uses MAIL_FROM_ADDRESS and MAIL_FROM_NAME, not MAIL_ADDRESS. Do you overwrite that somewhere? And have you tried it with port 587?

29 Jan
5 months ago

fabricecw left a reply on Sending Email Notification To Users

Your User class (in the App directory) should have the Notifiable trait:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable; // <-- this one

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

fabricecw left a reply on Ubuntu Server Doesn't Send Emails?

Please post the email part of the .env file, the email class and how you fire it.

fabricecw left a reply on Ubuntu Server Doesn't Send Emails?

  1. Is the outgoing port open on the Forge server. You can check this by wget -qO- portquiz.net:<<port>> while the port is the SMTP port.

  2. Do you use queueable on your emails? Maybe the queue isn't working.

  3. Did you setup the .env correctly of your app on the Forge server? Maybe you have to youse SSL/TLS...

fabricecw left a reply on When Should I Use Polymorphic Relationships?

I'm totally with you @douglasakula. The questions require a long term analysis/thinking. Maybe there is only a Book class which is orderable for now, but in future it could be possible that there are some others. Thanks for your hint!

28 Jan
5 months ago

fabricecw started a new conversation When Should I Use Polymorphic Relationships?

Hey!

I'm a little bit confused of when I should use Polymorphic Relationships and when a normal relationship would be the better approach.

I've been thinking about a question which I could ask to myself. I got the following idea of the question's "syntax":

Is there anything else which is modelable?

As an example for a Ordermodel:

Is there anything else which is orderable?

Which could be a model Bookor Chair.

An other example would be a Comment:

Is there anything else which is commentable?

Do I get the right thoughts or is this mindset wrong? Thanks for your feedback!

27 Jan
5 months ago

fabricecw left a reply on Laravel Notification Email Queue With Amazon Sqs

Amazon SQS is "only" a Queue Service and isn't responsible to send the email. What happens if you change your Queue Connection to sync?

04 Sep
10 months ago

fabricecw left a reply on Updating Answer - Mention User

Yeah, it's just the auto-completion which doesn't work and I didn't receive a notification.

fabricecw started a new conversation Updating Answer - Mention User

Today, I noticed the following: If you update your answer, you can't mention an other user with the @somebody notation. Or is it just me?

fabricecw left a reply on Getting Distinct Data Based On Specific Columns

By default, latest() sorts the column by the created_atfield. If you don't select this field, latestisn't working. You also can pass the column, like latest('id') but you always have to fetch this field.

30 Aug
10 months ago

fabricecw left a reply on Mailable

You use the Queueable trait. Which queue driver do you use? Did you tried it with the sync driver?

10 Aug
11 months ago

fabricecw left a reply on Is It Possible To Have 2 Sites (1 Www And 1 Root) With Forge?

I think the ssl_redirect.conf is auto-generated when activating a certificate. Have you removed the "www" form the Let's Encrypt certificate?

08 Aug
11 months ago

fabricecw left a reply on Is It Possible To Have 2 Sites (1 Www And 1 Root) With Forge?

@awhite did you enable Let's encrypt or another SSL cert? Forge automatically adds the www subdomain into the "before" nginx configuration. You can checkout the config file in /etc/nginx/forge-conf/<<your site>>/before.

06 Aug
11 months ago

fabricecw left a reply on Passing Variable Between Two Functions In Same Controller

So if you dd($person_type) in the first function, you get a value but dd($test)in the second function returns null?

05 Aug
11 months ago

fabricecw left a reply on Displaying Label Of Select Field In Table

Ok @Tray2 was faster :-)

Note: Don't forget to setup your models right. Also checkout the docs for this.

fabricecw left a reply on Displaying Label Of Select Field In Table

Can you explain this a little bit more? Don't know what your goal is.

01 Aug
11 months ago

fabricecw left a reply on Load Large Data In Ubuntu

What is the PHP memory limit according to phpinifo();?

fabricecw left a reply on Load Large Data In Ubuntu

What type of error do you receive? Gateway timeout?

fabricecw left a reply on Laravel OnHover Link Popover Fetch Dynamic Data From DB W/AJAX

Ok, so please let us know which JS library you want to use.

If you want to use jQuery: https://api.jquery.com/mouseover/

fabricecw left a reply on Laravel OnHover Link Popover Fetch Dynamic Data From DB W/AJAX

Would be easy stuff with Vue.

Checkout this post: https://laracasts.com/discuss/channels/vue/handle-event-mouseover-on-vuejs

In the change method you can make an AJAX request with axios

fabricecw left a reply on Fingerprint Capture And Verification

Fingerprinters have their own system / application to handle and analyze the bio data. You have to find a vendor which provides an API to their fingerprinting system.

I'm not sure if it's even possible only with Laravel. Because then, the fingerprint would have to fire an API request on a scan event - you can't control an USB device out of Laravel because this is local client stuff.

Probably you need a local application (written in C# or whatever) which controls the fingerprint device and calls the API.

I found the following solution: https://www.bayometric.com/fingerprint-sdk-touch-n-go-fingerprint-software-api/

22 Jul
11 months ago

fabricecw left a reply on Blade Checking If Auth Admin Is Logged In

If you want to work with roles, for example an "Admin" role and so on, take a look at this package:

spatie/laravel-permission

fabricecw left a reply on Laravel Passport - X-RateLimit-Limit OAUTH API

If anyone is looking for a solution:

  1. Create a new middleware ThrottleRequests:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Middleware\ThrottleRequests as BaseThrottleRequests;

class ThrottleRequests extends BaseThrottleRequests
{
    /**
     * Handle an incoming request.
     * Customization: 600 attempts per minute instead of 60
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  int  $maxAttempts
     * @param  float|int  $decayMinutes
     * @return mixed
     */
    public function handle($request, Closure $next, $maxAttempts = 300, $decayMinutes = 1)
    {
        $key = $this->resolveRequestSignature($request);

        if ($this->limiter->tooManyAttempts($key, $maxAttempts, $decayMinutes)) {
            return $this->buildResponse($key, $maxAttempts);
        }

        $this->limiter->hit($key, $decayMinutes);

        $response = $next($request);

        return $this->addHeaders(
            $response, $maxAttempts,
            $this->calculateRemainingAttempts($key, $maxAttempts)
        );
    }
}

Set the maxAttemptsparameter to the required default rate limit.

  1. Update the throttlearray value from the routeMiddleware variable in the Kernel.php:
protected $routeMiddleware = [
        // ...
        'throttle' => \App\Http\Middleware\ThrottleRequests::class,
       // ...
    ];

Warning: All routes with the throttle middleware use the new rate limit. If anyone has a better approach, let me know. Thanks!

19 Mar
1 year ago

fabricecw left a reply on MySQL - Rounding

Thanks for your research! We're going to round the value in the applcation.

fabricecw left a reply on MySQL - Rounding

Yeah, only thought if I it's possible to define this in a Laravel migration I would prefer that way.

fabricecw started a new conversation MySQL - Rounding

Hi

Our Laravel application's database runs on a MySQL 5.7.21 server. We store some float values with up to 6 decimal places into a double field with 2 decimal places. MySQL automatically rounds the value to 2 decimals.

Now the rounding function rounds for example 6.025 to 6.02 instead of 6.03. But 5 should be rounded up (mathematically round). MySQL rounds 6.026 correctly to 6.03.

Anyone knows where or how I can fix this? Otherwise we will round the value before storing it to the DB.

Thanks and regards

24 Feb
1 year ago

fabricecw left a reply on 2nd DB Connection Crashes Site

Please defineprotected $connection = 'remote'. Than start Laravel tinker with and try to fetch some data from the model with $foo = App\Foo::all().

fabricecw left a reply on 2nd DB Connection Crashes Site

What happens if you define protected $connection = 'mysql' ?

fabricecw left a reply on Back() And Redirect()->back() Doesn't Work

redirect()->back()redirects you to the page where the requests comes from. From which site do you send the request?