mabdullahsari

mabdullahsari

Member Since 2 Months Ago

Experience Points
14,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
0
Lessons
Completed
Best Reply Awards
24
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 3
14,190 XP
Sep
23
3 weeks ago
Sep
22
3 weeks ago
Activity icon

Replied to Is There Are Elegant Way To Store Auth()->id() On Every Created/updated Method?

OK, my bad I did not read your post thoroughly. I adjusted my first response, that should do the trick.

Activity icon

Replied to Get More Infomation On Test Failure

No in this case (well at least an answer that literally tells you what's wrong), because no exception is being thrown. The code in itself is working, but according to your test it is not. So, by checking your implementation you have to figure out why it is not carrying out the actions you were expecting.

Activity icon

Replied to Is There Are Elegant Way To Store Auth()->id() On Every Created/updated Method?

You can make use of the saving event that fires when an Eloquent model is either being created or updated. However, I don't know why you'd want to repeat yourself by assigning it after an update?

Something like this in your model (Edited):

public static function boot()
{
    static::creating(static function ($model) {
        $model->created_by = Auth::id();
    });

    static::updating(static function ($model) {
        $model->updated_by = Auth::id();
    });
}
Activity icon

Replied to Validation And Duplicate Update() In Laravel

The unique validator also accepts a third parameter, namely the id of the record to ignore the validation for.

So, if I may assume that you retrieved a vehicle model:

'immatriculation' => 'required|string|max:15|min:6|unique:voitures,immatriculation,' . $voiture->id ,
'num_vehicule' => 'required|string|max:6|min:6|unique:voitures,num_vehicule,' . $voiture->id,

Keep in mind that you should only do this for updates, not for creations.

Activity icon

Replied to User Model Deleting Event

You are correct with your assumption, that line of code will never trigger the listeners because Eloquent is generating an ad hoc query to permanently delete the user record from the database, ie. there is no user model in the first place to fire the events for.

Change your code to (mind the removal of the parantheses):

$contact->user->forceDelete();

This time, Eloquent does retrieve the user model from the database so the events can fire.

PS: You can listen to the forceDeleting event, so you don't have to do that if-check ;)

Sep
21
3 weeks ago
Activity icon

Replied to Validation Not Working

I'm not sure if you can access route parameters directly like that.

Try $this->route('toy')->id

Activity icon

Replied to Should We Use Those Migrations Which They Are Only For Changing The Data

Those migrations have already run, so what I'd suggest is that you delete all of the current migrations you have and regenerate migrations for your current database schema using migrations-generator.

https://github.com/Xethron/migrations-generator

You will end up with a "couple" of files which will also speed up testing immensely.

Activity icon

Replied to Array In This Trace Function

It is not an array, it achieves the same thing as list, namely destructuring;

https://www.php.net/manual/en/function.list.php

Sep
19
3 weeks ago
Activity icon

Replied to OrderBy() Not Compatible With Distinct()

If I comprehend correctly, you'd like to retrieve all of the users who left a comment, but without "user duplicates" because he/she can obviously leave more than one comment?

Also, distinct should be avoided if possible because it has some performance implications. It won't work in this scenario either because each row from the result set will be different as a whole even if the user data is the same.

Sep
18
4 weeks ago
Activity icon

Replied to How To Get All Ratings For Specific Category?

You cannot go deeper than one relationship using Laravel's out-of-the-box solutions. Check out this package https://github.com/staudenmeir/eloquent-has-many-deep

Then, you can probably do the following:

public function ratings()
{
    return $this->hasManyDeep(Rating::class, [Product::class, ProductCategory::class]);
}
Activity icon

Replied to How To Split Up Responsibilities When Getting Data From An API

The Repository pattern is probably what you're looking for. I'd highly recommend this video for an introduction: https://www.youtube.com/watch?v=93ZhGkFIwbA

If later down the road you decide to completely ditch the API and use Eloquent for everything for example, it will be as easy as just swapping the repositories in the IoC container. You won't even have to touch your controllers.

Sep
16
1 month ago
Activity icon

Replied to Protected Fillable Not Working With Vue Axios Patch

That is still generating an ad hoc query, you are not retrieving the model.

Replace that piece of code with what @jlrdw has suggested and it should work.

$event->information->update($request->all())

Mind the removal of the parantheses!

Activity icon

Replied to Protected Fillable Not Working With Vue Axios Patch

You are not updating using the model itself... Eloquent is generating an ad hoc query to update the model in the database. You need to retrieve the model first and then update.

@jlrdw Has already suggested it and I'm pretty sure that's the cause.

Activity icon

Replied to Convert 'DD/MM/YYYY' Format To Timestamp

\Carbon\Carbon::createFromFormat('d/m/Y', $value)->timestamp
Sep
15
1 month ago
Activity icon

Replied to Best Laravel Eloquent Tutorial For Searching

You can consult the official docs about Laravel Scout. There is no official driver for ES, but this one is pretty good: https://github.com/babenkoivan/scout-elasticsearch-driver

Activity icon

Replied to Best Laravel Eloquent Tutorial For Searching

I'd recommend watching this video, as he clearly explains all of the gotchas

https://youtu.be/UPkqFvjN-yI

TL;DR Databases are not tailored for proper searching, use solutions such as Elastic or Algolia unless the searching is going to stay simple and limited.

Sep
08
1 month ago
Activity icon

Replied to Eager Load A Relation

Well, assuming you have gone with the custom userComments relationship, you can simply add it to the array after an if check.

$withCount = ['comments'];

if (auth()->check()) {
    $withCount[] = 'userComments';
}

Post::withCount($withCount)
...

No need to overthink

Activity icon

Replied to Send Some Routes In Laravel To Custom 404 Page

2 options:

throw new NotFoundHttpException;
abort(Response::HTTP_NOT_FOUND);
Activity icon

Replied to Eager Load A Relation

If I understand correctly, you can do something like this:

->withCount(['comments as user_comments_count' => static function ($exists) {
    $exists->where('user_id', auth()->id());
}])

Then in blade you simply check if user_comments_count is greater than 0, in that case the user has commented on that post.

@auth @if($post->user_comments_count > 0)
    You left comments on this post.
@endif @endauth 

Edit: You can also define a dedicated relationship for this case if you think you will re-use the logic, because in the end, what I provided will also achieve the same thing. It depends on you entirely :)

Activity icon

Replied to Eager Load A Relation

Can you clarify a bit further of what you'd ultimately like to achieve? What do you mean with boolean, is it a column you have in the database, or a computed value?

Activity icon

Replied to How Specific To Be With My Model Creation?

There are many ways to deal with this problem, but the most common one is to suffix the "duplicate" slugs with an integer value starting from 0.

There is a package published by Spatie called

spatie/laravel-sluggable

which can save you lots of repetitive work. Just use it and you are good to go (unless you really want to use your own implementation).

Activity icon

Replied to Model::Create Doesn't Return Model Id?

Take a look at the section Defining Custom Intermediate Table Models

You can always access the pivot model with $model->relationship->pivot

https://laravel.com/docs/6.0/eloquent-relationships#many-to-many

Activity icon

Replied to Model::Create Doesn't Return Model Id?

Okay, you are mistaken with the default value. That is a fixed default value saved in the database. Str::uuid() will only run once when migrating, that's it. New models won't have new UUIDs. You need to set up an Eloquent event handler for the creating event. I'd recommend to put these in a trait so it is only a matter of importing that trait if another model also needs to use UUIDs. Something like below:

use Illuminate\Support\Str;

trait HasUuid
{
    protected static function bootHasUuid()
    {
        static::creating(static function ($model) {
            if ($model->getKey() === null) {
                $model->setAttribute($model->getKeyName(), (string) Str::uuid());
            }
        });
    }

    public function getIncrementing()
    {
        return false;
    }

    public function getKeyType()
    {
        return 'string';
    }
}
Activity icon

Replied to Model::Create Doesn't Return Model Id?

Then I can assume that the column uuid in your table is the PK? $model->getKeyName() should return uuid.

Are you creating a brand new uuid when you create those models? Because Laravel won't do that for you. You should also return false in getIncrementing because you are not using AI PKs. Same thing with getKeyType which should return string.

public function getIncrementing()
{
    return false;
}

public function getKeyType()
{
    return 'string';
}
Activity icon

Replied to Model::Create Doesn't Return Model Id?

When you call create on a model, it doesn't return the id, but a brand new model with the id set in that model, so I'm a bit confused about that. Do you expect to receive an integer from create? You should call $model->getKey()

Your 2nd question, you can manually set the relation on the object so you don't have to hit the database. You already have the properties in this case, so inside your if statement:

$model->setRelation('properties', $request->get('properties'));
Sep
07
1 month ago
Activity icon

Replied to Eager Load With Only The First Element Of The Relationship

This question has been asked many times before, as a matter of fact, the most recent one is from a couple of hours ago.

https://laracasts.com/discuss/channels/code-review/hasmanythrough-cant-eager-load-with-a-take-limit-or-first

Activity icon

Replied to Laravel OrWhere()

Instead of chaining the orWhere after the where, try putting it inside the closure you pass into the where. Something like:

Auth::user()->orders()->where(function ($query) {
            $query->awaitingPayment()->orWhere->awaitingPaymentPaypal();
        })->get();
Activity icon

Replied to Call To A Member Function GetRoutes() On Array

You need to look deeper in the stack trace to catch that pesky bug.

I'm afraid noone can help you, since the information you've provided is very little.

Activity icon

Replied to Laravel SortBy() Based On String Values

You need to tell the database what kind of "weight" your string values have in order to properly order them.

Assuming you are using MySQL, you can use the FIELD function in order to do this easily. Something like this:

$builder->orderByRaw('FIELD(size, "SM", "MD", "LG", "XL", "XXL")');

You can read more about the particular function in this link https://www.w3resource.com/mysql/string-functions/mysql-field-function.php

Do note that if you are using SQLite for testing, this will cause you trouble. In that case, you will have to use CASE ... WHEN ... THEN in your order clause (because in the end, that's what the FIELD function does behind the scenes)

Activity icon

Replied to Call To Undefined Method Illuminate\View\Compilers\BladeCompiler::component

Components were added to Blade with L5.4, but you are using 2 versions prior?

Sep
06
1 month ago
Activity icon

Replied to Get Just Values In Array

Well, you just call values() on the collection.

Edit: array_values if after the array operation.

Activity icon

Replied to React Authentication Using Laravel Passport

There is no API authentication in "the React way". It is the same process for everything, regardless of the used rendering library/framework. You need to deal with the HTTP client.

Most React and Vue apps utilize Axios as the client and Angular comes with its own implementation.

Long story short, any tutorial that is applicable to Vue is also applicable to React and vice versa.

Sep
05
1 month ago
Activity icon

Replied to Select Limit Of Items In Hasmany

I edited my response above, but chances are you missed it so I'll explain your issue.

When eager loading relations, Eloquent generates a similar query as below:

select * from "product_images" where "product_images"."category_id" in (1, 2, 3, 4) limit 4

So, you are correctly retrieving all relationships, but then limit the whole thing. This is a limitation of eager loading, and the only way (with barebones Laravel) to fix this is by looping over each category and executing a query for each of them which eliminates the purpose of eager loading.

You can use the package (which is a rejected PR actually) above to still leverage true eager loading.

Activity icon

Replied to Select Limit Of Items In Hasmany

Trying prefixing and suffixing your code with 3 backticks ``` so it is more readable.

This package from staudenmeir (core Laravel contributor) might be of help

https://github.com/staudenmeir/eloquent-eager-limit

Activity icon

Replied to Maatwebsite Export Data Base On Selected Value.

It says literally what you have to do if you'd like to customize your query below the first title...

https://docs.laravel-excel.com/3.1/exports/from-query.html#customizing-the-query

Sep
04
1 month ago
Activity icon

Replied to [security] Creating Instance From POST Data

You can tidy things up by putting all of that logic in a Form Request and encapsulate your commentable validation in a custom rule. The controller should not worry about validating the data, it should only process it.

https://laravel.com/docs/6.0/validation#using-rule-objects

https://laravel.com/docs/6.0/validation#form-request-validation

Activity icon

Replied to Can You Create/save A New Model From Another Model's Boot Method?

Can you show the contents of the updating handler?

Activity icon

Replied to How To Underline Task When Click On It

Why are you double posting? You have a very similar topic already.

Activity icon

Replied to Reverse Certain Job

No, you cannot unless you use event projection because the old state is lost at that point.

You could wrap your code in a DB transaction, but what you've described is a valid operation and semantically correct, it's just not what you desired.

https://github.com/spatie/laravel-event-projector

Activity icon

Replied to Eloquent Relationship Coding Error

The name change is only to make it clearer for yourself, the relationship is still going to return a collection of users.

You need to loop over the users and put them in a ul or something or you can stitch them together with commas like

$institution->users->map->name->join(', ');

(Assuming the user has a name attribute)

Activity icon

Replied to In Like System Is It Okay If Use $guard = [] ?

@untymage I answered that in my previous reply as well. He/she cannot

Activity icon

Replied to Eloquent Relationship Coding Error

The relationship is a hasMany. Perhaps you should rename it to users instead of its singular form to avoid confusion. xxxMany relationships return a collection of the provided entity. So, in your case you will have a collection/list of users and not one single user.

What are you trying to achieve exactly?

Activity icon

Replied to In Like System Is It Okay If Use $guard = [] ?

Honestly, this is preference. I always set $guarded to an empty array (ie. disabling mass assignment protection) because I never pass request parameters as is, only after validating the request.

Disabling mass assignment is telling Laravel

"Hey, I know what I'm doing. You need not interfere."

Answering your question: no. Only if you do silly things like

$user->update($request->all())