mabdullahsari

mabdullahsari

Member Since 3 Months Ago

Experience Points
17,170
Total
Experience

2,830 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
29
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 4
17,170 XP
Nov
13
4 weeks ago
Activity icon

Replied to Flip() Collection Between Model And Relations?

Why don't you simply iterate over the collection and create a Dictionary/Map like structure to group the entities?

The heated discussion above confused me more, so pardon the additional question.

Çalap sabır versin :)

Nov
11
1 month ago
Nov
09
1 month ago
Activity icon

Replied to Saving After Validation

No, you are updating UserData so you have to add the values to that model in this case.

Activity icon

Replied to Saving After Validation

Well, then it's probably mass assignment. Open up your UsersData model and take a look at fillable, the attribute names must be present in that array (unless you use guarded ofcourse, then the opposite is true).

Activity icon

Replied to Can I Write This Test Better ?

Within a single test's body, you should generally follow this pattern:

  1. Arrange: Prepare everything for step 2, in your case creating a new page
  2. Act: Carry out the action, in your case the request for creating a new page
  3. Assert: Make sure everything is what you'd expect after step 2.

If there is repetitive set up, you can use setUp to clean up your tests.

Apart from removing withoutExceptionHandling, I don't see any need for improvement. You are clearly implementing the 3 steps I mentioned above!

Activity icon

Replied to Saving After Validation

Could you try

$validated = $this->validate($request, $rules);

I don't think there is a validate method available on Illuminate\Http\Request.

Also, take a look at FormRequests https://laravel.com/docs/6.x/validation#form-request-validation

Activity icon

Replied to Saving After Validation

You need to clarify "does not work". Are you getting an exception (MassAssignmentException)?

Activity icon

Replied to Saving After Validation

Assuming that your request input params have the same name as your user's attributes, you can do the following:

$user->update($request->validated());
Nov
08
1 month ago
Activity icon

Awarded Best Reply on When To Use Config Variable Vs Accessing Env Variable Directly

I think it's generally accepted that you should never access env variables in app code without the use of the config helper (ie. having a configuration file)

Activity icon

Replied to When To Use Config Variable Vs Accessing Env Variable Directly

I think it's generally accepted that you should never access env variables in app code without the use of the config helper (ie. having a configuration file)

Activity icon

Replied to Opinions On Portfolio Development (Hosting Wise)

Gatsby/Gridsome is probably what you're looking for. I'm building my new portfolio site with Gatsby and it offers everything I'd need for such a site. Fully client-side app solution with routing & seamless SSR.

Especially Gatsby's GraphQL API is very powerful, meaning you can also host an entire blog if you'd like in the future without any hassle. (Dan Abramov's overreacted.io is a fine example).

I'm thinking about hosting my site with Netlify's free plan as it's more than enough for what I need and it has some easy to work with form submission solutions which you can also leverage with Gatsby.

But, yeah you need to know a little bit of React/Vue for these solutions :) Laravel seems very "overkill". GL!

PS: Waiting for your findings regarding route param injection in controllers ;)

Nov
07
1 month ago
Activity icon

Replied to How To Re-use Controllers For Polymorphic CRUD Actions?

@jaytee Being able to "ask" the app instance to inject a certain route parameter instead of passing them all one by one would immediately solve my problem, but I haven't had the time yet to delve into the framework code to see whether it is possible or not. Thanks!

Activity icon

Replied to How To Re-use Controllers For Polymorphic CRUD Actions?

@jaytee is adjusting the routes really the only way? Because, the last route parameter will always be the status and the one before that will be the statusable itself. That's why I thought I could dynamically inject the route parameters into the controller by type hinting (regardless of depth of route), but I guess that's not possible as is? A real bummer though if that is the case.

Activity icon

Replied to How To Re-use Controllers For Polymorphic CRUD Actions?

@jaytee I think you've misunderstood. Everything is working, I just have the problem I described in TL;DR.

Not going to undo anything now, it's pretty much done when I find a way to inject route parameters by type hinting...

Nov
06
1 month ago
Activity icon

Replied to How To Pass Pre Data To A View??

view accepts an associative array as its second parameter. Simply do:

return view('contemplado.uploads', compact('contrato'));
Activity icon

Replied to How To Re-use Controllers For Polymorphic CRUD Actions?

@jaytee Yeah, and those posts can belong to any model (ie. polymorphism).

Activity icon

Replied to How To Re-use Controllers For Polymorphic CRUD Actions?

@jaytee Yeah I see, my bad.

People can post "status updates" for a given event/project (à la facebook). So it consists of a title, description and optional images. Images have nothing to do with the issue I'm facing.

I have added a TL;DR at the top to summarize what I'd like to achieve.

Activity icon

Started a new Conversation How To Re-use Controllers For Polymorphic CRUD Actions?

TL;DR How can I arbitrarily inject any route parameter into a controller via type hinting, ignoring the order of bound route parameters?

Scenario: I have a Status model that can be used with any given model via polymorphism (models Project/Event can have many statuses and Status itself morphs to a statusable).

What I thought that would work:

  • Create a Contract called HasStatuses, every model that has statuses must implement it
  • Create a Concern for this contract, every model that has statuses must use it
  • Via explicit route model binding, resolve the right status when needed
  • Inject the Statusable into the controller using the HasStatuses interface so it stays model agnostic
  • When a new model needs statuses, just add the CRUD routes with right parameters and controllers => DRYness achieved

Example controller:

    // EditController.php

    public function __invoke(HasStatuses $statusable, Status $status)
    {
        $images = Image::collection($status->getMedia('images'));

        return view('status.edit', compact('images', 'statusable', 'status'));
    }
    

The code above works for the following route: events/{eventId}/statuses/{statusId}, but apparently does not for the following: charities/{charityId}/projects/{projectId}/statuses/{statusId} because the IoC container is injecting the route parameters relative to the order of parameters in the route and completely ignores the type hints? So for projects, this code crashes because the app passes a Charity instance as statusable which is definitely not what I want.

I tried binding the interface in the AppServiceProvider, but still it is injecting all parameters in the "right" order completely ignoring type hints.

    public function __invoke(Request $request)
    {
        $params = $request->route()->parameters();
        $status = array_pop($params);
        $statusable = array_pop($params);

        $images = Image::collection($status->getMedia('images'));

        return view('status.edit', compact('images', 'statusable', 'status'));
    }

I have temporarily settled with the solution above (so it would work), but it is in no way, shape or form the elegance I was striving for. I had to repeat this for all of my CRUD controllers...

How can I solve the injection problem? Any tips would be highly appreciated, because I cannot live with the current piece of code :/

Oct
21
1 month ago
Activity icon

Awarded Best Reply on PostTooLargeException

Do not forget to restart php and if you are using a web server such as nginx configuring php.ini might not be enough as the webserver also has a limit in place for POST calls.

Sep
23
2 months ago
Sep
22
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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
3 months 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';
    }
}