thewebartisan7

thewebartisan7

Member Since 2 Years Ago

Experience Points
36,860
Total
Experience

3,140 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
166
Lessons
Completed
Best Reply Awards
29
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 8
36,860 XP
Oct
21
2 days ago
Activity icon

Replied to How To Modify Or Extends {{ }} Functionalities.

You could create a Blade directive.

In your App service provider register it like:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    // code commented for brevity

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('convert', function ($number) {
            return "<?php echo number_format($number, 2); ?>";
        });
    }
}

And then in blade use it:

@convert($var)

Check this package which has more examples:

https://github.com/appstract/laravel-blade-directives/blob/master/src/directives.php

Oct
20
3 days ago
Activity icon

Replied to Laravel 8 Forms Build Library

If you want something like laravel 8, with components, check this one https://github.com/protonemedia/laravel-form-components

It has support for bootstrap and tailwind, and livewire, binding and other helpers.

But if you are using jetstream then you can use their components see here https://github.com/laravel/jetstream/tree/1.x/resources/views/components

The package above offer more features.

Activity icon

Replied to Multi Auth With Roles And Permissions

Each auth has it's own Guard in Laravel when you setup multi auth.

Then in spatie you need to specify which guard name you want to use for that role or permission you create or check. See https://spatie.be/docs/laravel-permission/v3/basic-usage/multiple-guards

It's more simple to have just one auth and multiple roles/permissions that manage, and most probably is enough.

There are some package that can help you build multi auth skeleton in case you want go with it, see:

https://github.com/mtvbrianking/multi-auth

https://bitfumes.github.io/laravel-multiauth/

Oct
19
4 days ago
Activity icon

Replied to How To Build Ajax Registration And Login System In Laravel 8

With this vanilla js and axios you can process your login and register via ajax. Can and should be improved maybe instead of alert use some toast notifications. You could also display each single errors from server and/or add client side validation. In case you can also show validation errors appending after input. You don't need to change server code if you are using Laravel UI or Fortify. The response will be json when you make ajax request.

const formElement = document.querySelector('.js-ajax-form')

    formElement.addEventListener("submit", function (event) {
        event.preventDefault()

        const form = this

        const data = new FormData(form)
        const url = form.getAttribute('action')
        const method = form.getAttribute('method')

        axios({
            method: method,
            url: url,
            data: data,
            headers: {'Content-Type': 'multipart/form-data'}
        })

            .then(function (response) {
                
                alert('Successfully logged-in');

                // Reload page so you will be redirected to default page defined in Laravel
                window.location.reload()
            })

            .catch(function (error) {
                let message = 'An error occured.'; // Default error message

                if (typeof error.response !== 'undefined' && typeof error.response.data !== 'undefined') {
                    // Error message from server
                    if (typeof error.response.data.message !== 'undefined') 
                        message = error.response.data.message


                    // Access input errors using:

                    if (typeof error.response.data.errors !== 'undefined') {
                        let errors = error.response.data.errors
                        for (let input in errors) {
                            if (errors.hasOwnProperty(input)) {
                                //errors[input].join('<br/>')
                            }
                        }
                    }
                }
                alert(message);
            })
    })
Activity icon

Replied to Why Actions In Laravel 8?

I use also Spatie permissions package :) But I agree that it has unecessary features for my need (for avoid to use word abstractions :)... However, I refactor the Models of spatie permissions by removing guard and polymorphic relations, and using only constraint relation (users, roles, user_permissions, roles_permissions). I gain a bit in performance. Most of my package that I use are from spatie. And I customize a few to fit my need.

Oct
18
5 days ago
Activity icon

Replied to Why Actions In Laravel 8?

I'm glad we were able to understand each other.

From this I can see that you do not want to depend on packages and want to do as much is possible manually so you can have full control over it.

Yes but I don't want that you maybe misunderstand. I don't want that you think that I want re-invent the wheel. If I need a package, backend or frontend, I am more than happy to use it. But of course if I don't need it, then why I should keep it? Who want?

Now regarding your last questions regarding Livewire and Inertia. First about Livewire. Shortly, it's a good package for those who are not good with JS. It allow to create interactive page writing only PHP. But for a full stack developer who love frontend development like me, then is not solving any problem, rather is adding only new problem to solve. Many love concept of making interactive page without writing JS, and Caleb do good job delivering something that many need. But comparing it to original idea which it come from, which is Phoenix LiveView (https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html), Livewire is just ajax requests vs socket of Phenix LiveView. Totally two different world.

I make the same result of Jetstream with Fortify and now doing the same with Laravel UI, but even better since all page and forms (also auth forms) is loaded via ajax using axios and turbolinks. So the same interactive UI which aim to offer Livewire.

I also think that is still not mature project, but that is minor issue, considering it popularity it will become mature very soon. But at the current stage I would not use it in production.

Alpine has similar issue, I just don't like to put JS inside HTML and trying to get my head around how to solve something that I can quickly and more eleganty do with plain vanilla JS. There is another one which do similar things, https://htmx.org/ and it can be good for developers who can't work with JS.

In my opinion nowday developers must consider to learn also JS, and Livewire has potential to delay this if developer use it.

I could say more things specifically about Livewire that I found, but I think and hope you get my main points.

Inertia on other hand I like a bit more because you still write JS on frontend, and if you change backend, you can still use your frontend, while with Livewire you can't. If I have to choose between the two, then Inertia would be winner. But maybe I am a bit too conservative and still prefer old fashion with API on backend and routes via VueJS (my preferred).

Last thing not less important. I can't work with Tailwind. I really try but I can't. Maybe after so long time working with Bootstrap and other OOCSS I can't change my habit and switch to something so "low-level" to use Adam words. Maybe is only question of habit. I like the Adam TailwindUI, and I consider to use it, but for now I can do just with Bootstrap much faster what I can with tailwind. There are also several things that seem TailwindCSS can't solve. But that is another story.

Activity icon

Replied to Why Actions In Laravel 8?

Nope? In general both are first party packages that provide abstractions for problems they are solving.

We could now speculate with words, but I see Cashier solving 1 problem, extracting logic that can be re-used in several project. While a scaffolding, or boilerplate such as Jetstream doesn't solve 1 problem, has authentication, team, UI for 2 different frontend, etc. But taking into account your answer could be seen as the same.

So you are saying that Jetstream is an unnecessary abstraction and people should use laravel/ui instead if they do not plan to use Livewire/Inertia?

Seem that you finally get my point. Thanks God. I mean exactly that. IF they don't plan to use Livewire/Inertia BUT even if they plan to use Livewire or Inertia there is unecessary abstraction. Because they will use Livewire OR Inertia. Is necessary abstraction only if they use both.

So you are against it cause it makes you use Livewire or Inertia?

This will raise I think another discussion for another week, so I think is better for me to not comment this. It's that fine for you or you would like to hear my opinion regarding this?

Activity icon

Replied to Why Actions In Laravel 8?

@jlrdw I know that "secret". I am not sure to get your point. I am not saying anything against OOP or separation of code. Working with any MVC framework you are already forced to separate your code in very well manner. With Laravel you have also several others way to separate your logic (form requests, policies, middleware, service providers, resources, etc.).

@bugsysha if working with Laravel standard API is "procedural solution" then we have different view what is a procedural solution. Experienced developer make worry about abstraction when there is need to worry about abstractions. Where there is not, then keep it simple. The refactoring and abstraction stuff, ie polishing code, is something that I enjoy to do, is not something to fix, but rather something to improve. And what I see there is not a general abstraction right for any project, rather is something specific to application/project.

DRY in Jetstream is only to handle multiple frontend which I and most probably you and most of us will never need to manage. It's a solution dedicated to Jetstream. Is not a solution for any end application.

You can't compare Laravel Cashier with Jetstream, first is "an expressive, fluent interface to Stripe's subscription billing services." while second is "a beautifully designed application scaffolding for Laravel.".

Can you see difference?

Last, I am not saying Jetstream implementation is bad, but rather is not appropriate for common usage as what aim to be a "scaffolding application".

In my very first reply I didn't say "stay away from Jetstream, that is bad implementation", but I start with this word "I think that it depend on project that you are working.".

Activity icon

Awarded Best Reply on LV8 Jetstream /register: Set Default Value From Get-parameter

Inside component prop :value don't use {{ }}

 :value="old('code', request()->get('code'))"
Activity icon

Replied to LV8 Jetstream /register: Set Default Value From Get-parameter

Inside component prop :value don't use {{ }}

 :value="old('code', request()->get('code'))"
Activity icon

Replied to Why Actions In Laravel 8?

Point is that all apps tend to get bigger. So why postpone necessary?

I think that I implicit answer this questions in my 2 long answers after it. But for the sake of clarity, I will answer explicity.

I don't think that all apps tend to get bigger. I make for many customers web apps and mobile apps that simple remain as-is since first release, for years. Or they don't have cost for further development, or they close business for other reasons. Or they are happy with current stage. I have even my commercial social network application still running with PHP 5.x and PhalconPHP 1, still being used by several customers. Now nearly 2 years not updated apart minor fixes. Technology move fast, and I see that most of your application is more easy to refactor than upgrade to new one. This happen with an Angular 1 app, with several Ionic app, Phalcon PHP, and I think also for switching from Laravel 4 to 5.

I don't start a project thinking on abstractions immediately, I do that when in phase of polishing the code, when I see necessity of extraction of code. Refactoring is part of that process.

I think an inexperienced programmer starts thinking about abstractions at first, I used to do that too. But it is impossible to predict the evolution of the code unless you do a month of analysis with UML digrams and everything else. They raise development costs that customers are not happy to pay. I'm not saying they don't need to be done, on the contrary, in some projects they are essential. But in small to medium projects they are not. I prefer to keep the code as simple as possible at the beginning, even if that means repeating the code a few times. And only towards the end if I see the need I extract the code. But often this is not necessary.

Again, if you are large company working with many developers, then you may think differently. But being a solo developer or small team, you can't afford to work as a company.

Now, Jetstream/Fortify offer abstractions for handle 2 frontend, which I will never use. And this abstraction make code more complicated to manage. Something that I and other developers don't need make your starting point already complicated.

I hope that I did explain well myself.

May Jetstream be with you.

Oct
17
6 days ago
Activity icon

Replied to Why Actions In Laravel 8?

I've asked nicely but I've also tried to cut it short and avoid any conflict since as I said we have different standards.

Actually, you have not asked nothing :)

Quoting your message:

"@thewebartisan7 sorry since English is not my strong point I'm having really hard time understanding you. What you are saying is so confusing to me cause everything sounds inconsistent. You say one thing then the other."

No questions here :)

It's just that the way you write is confusing to me or maybe that is caused by my interpretation of what you are trying to say.

I agree that is a mix of two. English is not my primary language, but I think you are also making your own interpretation. Considering the belief that most of communication is body language, part is the tone of voice, and very small part is the actual words spoken, it's easy to get misunderstand via written communication such as this. It is said that about 10% is verbal, so we missed 90% of the communication. But try reading again, and see if you agree almost with Spatie quote. You can't disagre with that.

All best and may the Schwartz be with you.

It took me a while to understand where this sentence came from. But then I remembered... Spaceballs :) I like more the origin of this phrase, and is not "May the force be with you", but the original is "May the Lord be with you."

Bless

Oct
16
1 week ago
Activity icon

Replied to PSR-4 And Upgrading To Composer 2

For your Transaction package should be:

namespace Vendor\Transaction\Events;

If you are working for a company, then you can use as Vendor CompanyName or your name, or your project name, must be unique so that doesn't get in conflict with other vendor name.

SubNamespaceNames, in your case Transaction, MUST corresponds to at least one “base directory”. So in Transaction package the base directory is transaction, so is correct Transaction.

I suggest to read this page: https://www.php-fig.org/psr/psr-4/ is not long and has all specifications and examples.

Activity icon

Replied to PSR-4 And Upgrading To Composer 2

PSR-4 specification must have fully qualified class name in form:

<NamespaceName>(<SubNamespaceNames>)*<ClassName>

Your namespace missing a top-level namespace name, the vendor name.

Read full specification here: https://www.php-fig.org/psr/psr-4/

Activity icon

Replied to Livewire Components Rendor Method

With trait you have also somethinig like mount, like boot of eloquent model, see WithPagination, initalizeTraitName()

Activity icon

Replied to Livewire Components Rendor Method

I don't think you can return a component. But I would create a trait, something like trait Livewire\WithPagination where you add shared code between the two component.

So you have still 2 component, ClientsIndex and EmployesIndeex and one trait, example ResourceIndex, which you can include in both component, and both component return the same view.

Make sense?

Activity icon

Replied to Why Actions In Laravel 8?

@martinbean You can blaim Spatie, because this is their solutions, not mine.

Quote spatie:

"You might see a similarity between view models and Laravel resources. Remember that resources map one-to-one on a model, whereas view models may provide whatever data they want.

In our projects, we're actually using resources and view models combined:"

class PostViewModel
{
    // …
    
    public function values(): array
    {
        return PostResource::make(
            $this->post ?? new Post()
        )->resolve();
    }
}
Activity icon

Replied to Why Actions In Laravel 8?

@automica You can combine API Resource with view model, because you can also return the view model itself as JSON data, by implementing Responsable.

Example:

class PostViewModel
{
    // …
    
    public function values(): array
    {
        return PostResource::make(
            $this->post ?? new Post()
        )->resolve();
    }
}
Activity icon

Replied to Why Actions In Laravel 8?

I just notice that you seem not interested to understand. When I don't understand something, I ask specific things that I don't understand. When you reply "What you are saying is so confusing to me cause everything sounds inconsistent. You say one thing then the other." that doesn't say too much what you don't understand. So is hard for me to try explain everything again.

Let me try explain with an example. Not sure if you know Spatie package https://github.com/spatie/laravel-view-models which offer the so called view model pattern. Even if this may be good in large project, is unecessary for small project.

From Spatie blog about this view model pattern, quote:

"Now I know that this isn't a problem in small projects. When you're the only developer and have 20 controllers and maybe 20 view composers, it'll all fit in your head.

But what about the kind of projects we're writing about in this series? When you're working with several developers, in a codebase that counts thousands upon thousands lines of code, it won't all fit in your head anymore - certainly not on that scale."

I agree with this, and this resume of my points above, I think very clearly. Even a good pattern is not always required in all project.

Activity icon

Replied to Why Actions In Laravel 8?

I think that I was clear in my arguments. He who has ears to hear, let him hear. Bless

Activity icon

Replied to Why Actions In Laravel 8?

First you say that something that is more complex in your mind is simpler for me, and then you say that CRUD is complicated for me.

You are taking my words out of context and making allusions about what I wanted to say. For you is simpler Fortify/Jetstream vs Laravel UI is one thing. For you CRUD is something not "small", for me is something easy to do with 100 lines of code in controller, removing comments. This are two separated things. I then also point that (maybe) for you CRUD is complicated when working with package like Nova or Backpack. It was an assumption. There is not correlation, apart point out that such abstraction can only make things more complicated. Because Nova and Backpack has their use case in large project, and also Fortify/Jetstream has their use case. I am saying that in most small-medium project, such package like Nova/Backpack/Fortify/Jetstream are unecessary.

To explain a bit more what I am saying regarding CRUD being simple see this gist:

https://gist.github.com/thewebartisan7/99c9882dfaad0def42fd61e16ec5c19b

This is a generated controller with CRUD in admin for a dummy model. Removing comments and sorting/filtering/searching of query builder package, each methods has 2-3 lines of code, so maybe there are less than 100 lines of code.

Considering you have also API, then controllers will looks like: https://gist.github.com/thewebartisan7/1e1302e851088e9830b8b4ea8869c950

Also this very slim.

For reusable code logic I use packages which I can share even between project, but make reusable a few lines of code make things only complicated when you need to put some conditions.

Everything is mostly a muscle memory at this point.

This happen only when you create a logic like Fortify/Jetstream or Nova/Backpack. You don't need to use memory to understand similar small part of code such as above controllers or such as Laravel UI controllers. I never need to remember how to do something with Laravel UI, because it's there easy to find once you open controllers. While with Fortify, after working a few weeks ago on it, I already forgot how to do even simple task on it. Such abstractions is not bad, I am not saying that. It has their use case. But in some project it's not good at all. I guess if you are using the same logic for all your code like Fortify/Jetstream by adding interfaces, and features enable/disable for each features you add in code. I don't think so.

I was just trying to have a quality discussion, but I guess that is not possible since we have different standards.

There is not standards in code, the right answer is depend on project you are working on.

I would just conclude with one questions: what is more easy exctract logic of Laravel UI in actions if you need them, or make Fortify/Jetstream like Laravel UI? First thing is possible, second is not. So as starter point for an auth, Laravel UI is winner. You can do with it the same things if you need.

No hard feeling for me, I think much more was said already in web, especially in reddit about this debat, and I see two different views on this. I personally agree with above, it depend.

Glad that OP has help understand the direction where he need to go.

Oct
15
1 week ago
Activity icon

Replied to Why Actions In Laravel 8?

Haven't worked on a project that had absolutely no need for reusability.

Of course we re-use many codes across projects and inside projects, from frontend to backend.

But there is not need in all projects to split code in multiple class, interfaces, etc. in all projects that you are working on, that is my point. If for you Fortify/Jetstream is semplification compared to Laravel UI then we have different understanding of semplification.

Projects that have admin CRUD is already not a small project in my mind. And if API is added to the mix then that is truly not a small-mid project.

Admin that do CRUD can be very easy when you do that with standard MVC logic, even if you have dozens of models. For you maybe use a CRUD like Nova or Backpack maybe is a semplification following your logic with Fortify/Jetstream, but for me is complication. You do 80% in 20% and the rest missing 20% in 80%, the famous rule. If you think that CRUD is something complicated, then you can learn from Spatie what means beyond the CRUD: https://laravel-beyond-crud.com/

I have my own CRUD generator with a few click I build Edit, Update, Softdelete, Restore, Mass Actions, and much more with a single line of code or via browser UI, for admin and API, with Searching, Filtering, Autocomplete, etc. It generate files such as controllers, models, views, request, policies, etc. I am freelancer and I work on small-medium project mostly alone or with a small team of other freelancer, and I know very well most of patterns, and I try many of them. In the end you lose time thinking how to create the perfect abstraction, and come to a complexity that it's more hard to manage than re-create something similar.

I always create Request classes no matter what.

You don't use request classes with Foritfy, and I thnk you don't use in login. I also think that is unecessary to use in all forms, there are small case where you don't need them. There is no generic rule for everything.

Activity icon

Replied to Why Actions In Laravel 8?

that kind of structure does not make code reusable.

I point out that there is nothing to be re-used in most small-medium projects where you have admin, frontend and maybe API. Let's say user models, in admin area you do CRUD for all users, in frontend you allow logged-in user to edit profile. What is re-used is validation, that you can extract in Form Request. Something else can be placed in models, and in case you need to share logic you can create a Repository, or for example upload of avatar, you can create a Service class, Support or Helper, call it how you like. Same can be applied to any other models.

Taylor also said in video that this actions was created to handle multiple frontend, and in most project you have only 1 frontend. So is unecessary complexity added if you have just one frontend.

Activity icon

Replied to Why Actions In Laravel 8?

I think that it depend on project that you are working. In case of jetstream that has two frontend, livewire and inertia, actions is being used to share common logic.

In most small-medium project I think that is uncessary abstractions.

MVC is already a solid pattern, where you separated things, also Laravel offer Form Request which allow to share validations.

Most of time I have admin, frontend and maybe API. Validations are shared via Form Request, controllers are slim and most of logic is in Model and sometime in Repository.

For my small-medium project is pretty enough.

For other large project with many developers involved could make sense.

Activity icon

Replied to LinkenIn Login Using Socialite

I suppose you get this error https://github.com/laravel/socialite/issues/454

I get the same initially, then it's fixed after a few days, I think it takes some time for Linkedin to be approved.

Because the issue happen already a year ago when Linkedin changed their API in v2, see this issue:

https://github.com/laravel/socialite/issues/368

Oct
14
1 week ago
Activity icon

Replied to LinkenIn Login Using Socialite

You need to be an approved developer to be able to use the r_basicprofile scope. See https://docs.microsoft.com/en-us/linkedin/shared/integrations/people/profile-api

Activity icon

Replied to Jquery Tools Min Problems

If you need only for gallery try search on google, there are many.

Example https://1stwebdesigner.com/jquery-gallery/

It depend which feature you need, there are simple or complex.

Activity icon

Replied to Jquery Tools Min Problems

I even forgot that this existed... I use it something like 10 years ago... I would not use it, it's 8 years not updated, see https://github.com/jquerytools/jquerytools

Google jquery sliders or gallery, or whatever you need, there are many around.

Activity icon

Replied to Toastr Notification Not Working

Your problem was that you calling toastr before you include toastr js plugin, the same you are doing was jquery:

Wrong:

<script>
        $(document).ready(function() {
            $('#sidebarCollapse').on('click', function() {
                $('#sidebar').toggleClass('active');
            });
        });
        
    </script>
@if (session()->has('success'))
<script>
    toastr.success("{!! session()->get('success')!!}");
</script>
@endif
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> 
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Right:

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> 
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

// After including script add your script for jquery and toastr.
<script>
        $(document).ready(function() {
            $('#sidebarCollapse').on('click', function() {
                $('#sidebar').toggleClass('active');
            });
        });
        
    </script>
@if (session()->has('success'))
<script>
    toastr.success("{!! session()->get('success')!!}");
</script>
@endif


Oct
13
1 week ago
Activity icon

Replied to Load Data From Checkboxes Array Ajax

In controller the problem seem to be here:

 $services->each(function ($item) {
            $services  = ([
                'price' => $item->price,
                'name' => $item->name,
            ]);
        });

You are doing strange thing here, can you see?

On JS side your success method should looks something like:


 if(data.service) {

            $.each( data.service, function(item){
               
                    $(".display_services").append(
`<li class="list-group-item lh-condensed">
                            <div class="d-flex justify-content-between">
                                <span>${item.name}</span>
                                <span class="text-muted">${item.price}</span>
                            </div>
                        </li>`
)
                }
            });

                else{
                    $(".display_services").html('')
                }

I can't see the whole picture of your code, but there are several way to do this, and can be improved.

Maybe try to solve firstly how you can and in case you have some question, create new question, making it more specific.

Activity icon

Replied to Using A Modal To Delete A User

Try this:

// HTML button
<button class="delete" data-user="{{ $user->id }}">
       Delete
</button>

// JS
            $('.delete').click(function(){
                var userId = $(this).data('user'); 
                // Now you have user id in variable userId
                console.log(userId);
            });
Activity icon

Replied to Use ENUMS With Select2 And Send To A Database

That package has a method asSelectArray() which you can use to populate the select2, see https://github.com/BenSampo/laravel-enum#static-asselectarray-array

Another feature that you can consider is casting your model mail message with MailMessageType, see https://github.com/BenSampo/laravel-enum#attribute-casting

Activity icon

Replied to Laravel 8: Allow Trailing Slashes In URL Generator

Try with this package: https://github.com/illuminatech/url-trailing-slash

Maybe you get some right direction or use it.

Good luck

Activity icon

Replied to Laravel User Registration And Email Verification With AJAX

You don't need separated controller, just use the same /register endpoint, which will handle both ajax and non ajax request, so also email verification if enabled. This work both with Laravel UI and Fortify.

Activity icon

Awarded Best Reply on Adding Laravel Rule To Livewire $rules[]

There is method:

public function rules()
{
    return [
        'icao' => new AirlineScalesExist,
    ];

}
Activity icon

Replied to Adding Laravel Rule To Livewire $rules[]

There is method:

public function rules()
{
    return [
        'icao' => new AirlineScalesExist,
    ];

}
Oct
12
1 week ago
Activity icon

Replied to Best Way To Handle Import: CSV With Related Photos

Not sure if you are already using some library, but check this which may help you write code: https://laravel-excel.com/

It has nice API, and can make things easier.

Activity icon

Replied to How To Custom Response JSON Object Validator

Because you can have more than one validation messages, for this reasons is an array.

You can on client side loop over each messages and display all or only first.

If you want to handle this on server side, there is several way.

If you know upfront all field name, then you could:

return response()->json([
   'name' => $validator->errors()->first('name'),
   'password' => $validator->errors()->first('password'),
], 400);

Something more generic could be to convert first in a collection, and then you can build new errors array, see https://laravel.com/docs/8.x/collections

For example:

$errors = collect($validator->errors())
              ->reverse()
              ->mapWithKeys(function ($item, $key) {
            return [$key => $item[0]];
        });

But maybe there is better way with collection. I think reverse is required so that first message is not overriden by last.

To get first message on client side would be something like:

// Taking into account that you are using axios which return response in error.response.data
error.response.data.errors[Object.keys(error.response.data.errors)[0]]

And for loops all errors:

                       let errors = error.response.data.errors
                        for (let input in errors) {
                            if (errors.hasOwnProperty(input)) {
                             // First error
                             invalidFeedback.innerHTML = errors[input][0]
                            }
                        }
Oct
11
1 week ago
Activity icon

Replied to A Better Way To Update User Profile When No Passwords Are Updated

A better way first of all is that is not required to make additional query, you can access current user from $request->user() or Auth::user()

        $user = $request->user();
        $data = $request->only(['name', 'email', 'password']);

        if (empty($data['password'])) unset($data['password']);
        else $data['password'] = Hash::make($data['password']);

        $user->fill($data)->save();

Maybe add also validation would be good.

Activity icon

Replied to @props: Variable Value Is Always Equal To Initialized Value Inside Laravel Blade Component

Did you pass testclass prop via component? Can you show how?

If you need just add more classes you can also merge attributes with

$attributes->merge(['class' =>'bg-transparent hover:bg-blue-500' ])
Activity icon

Replied to How To Split Libraries In Multiple Files Across Privates Packages/components

Try add in webpack.mix.js

mix.autoload({
    jquery: ['$', 'jQuery'],
});

But I don't understand why load in separated file manually, you could have one app.js and one bootstrap.js where all vendor are loaded, then in webpack.mix.js:

// Extract in vendor.js
mix.extract([
    'jquery',
    'bootstrap',
    'popper.js'
]);

This will extract all your vendor in separated file.

Oct
09
2 weeks ago
Activity icon

Awarded Best Reply on Executing This Kind Of Query Possible?

Laravel DB facade return a collection, so instead of using ->get() you can use ->first() , example:

$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;

In your case should be something like:

$users = DB::table('project_stream')
            ->leftJoin('stream_users', 'stream_users.stream_id', '=', 'project_stream.stream_id')
            ->where('project_stream.project_id', $project->id)
            ->first();

Reference in doc:

https://laravel.com/docs/8.x/queries#joins

https://laravel.com/docs/8.x/queries#retrieving-results

Activity icon

Replied to Executing This Kind Of Query Possible?

Laravel DB facade return a collection, so instead of using ->get() you can use ->first() , example:

$user = DB::table('users')->where('name', 'John')->first();
echo $user->name;

In your case should be something like:

$users = DB::table('project_stream')
            ->leftJoin('stream_users', 'stream_users.stream_id', '=', 'project_stream.stream_id')
            ->where('project_stream.project_id', $project->id)
            ->first();

Reference in doc:

https://laravel.com/docs/8.x/queries#joins

https://laravel.com/docs/8.x/queries#retrieving-results

Activity icon

Replied to Vendor.js For Public And Admin

At the moment there is not a solution to handle this with mix, but there is a workaround, that I am also using.

  1. Install this extension https://www.npmjs.com/package/laravel-mix-merge-manifest. Because when building your application in multiple steps (first app.js, then admin.js), the mix-manifest.json will be overwritten.
npm install laravel-mix-merge-manifest --save-dev
  1. Create two separated webpack.mix.js, for example webpack.admin.mix.js and webpack.app.mix.js
// file webpack.admin.mix.js

const mix = require('laravel-mix');
require('laravel-mix-merge-manifest');

// Merge any existing manifest
mix.mergeManifest();
 
mix.js('resources/js/admin/admin.js', 'public/js/admin')
 .extract(['jquery', 'bootstrap', 'popper.js']);

// file webpack.app.mix.js

const mix = require('laravel-mix');
require('laravel-mix-merge-manifest');

// Merge any existing manifest
mix.mergeManifest();
 
mix.js('resources/js/app/app.js', 'public/js/app')
 .extract(['vue']);

  1. Update the existing webpack.mix.js with below code:
if (['admin', 'app'].includes(process.env.npm_config_section)) {
 require(`${__dirname}/webpack.${process.env.npm_config_section}.mix.js`)
} else {
 console.log(
   '\x1b[41m%s\x1b[0m',
   'Provide correct --section argument to build command: app or admin'
 )
 throw new Error('Provide correct --section argument to build command!')
}
  1. Now you can compile admin and app separately using:
// App
npm --section=app run dev

// Admin
npm --section=admin run dev

The manifest will be updated and not overriden, so you will find something like:

{
   "/js/admin/admin.js": "/js/admin/admin.js",
   "/js/admin/vendor.js": "/js/admin/vendor.js",
   "/js/admin/manifest.js": "/js/admin/manifest.js",
   "/js/app/vendor.js": "/js/app/vendor.js",
   "/js/app/app.js": "/js/app/app.js",
   "/js/app/manifest.js": "/js/app/manifest.js"
}

And you can include them:

// App
<script src="{{ mix('js/app/manifest.js') }}"></script>
<script src="{{ mix('js/app/vendor.js') }}"></script>
<script src="{{ mix('js/app/app.js') }}"></script>
 
// Admin
 
<script src="{{ mix('js/admin/manifest.js') }}"></script>
<script src="{{ mix('js/admin/vendor.js') }}"></script>
<script src="{{ mix('js/admin/admin.js') }}"></script>

Let me know how this work for you.

Additionally you can install https://www.npmjs.com/package/concurrently and then run both with single command.

Activity icon

Replied to @extends Not Working As Expected In 404 Error Page

I am sure that in errors page you can't get user. Even if user is logged-in, if you try to dd(auth()->user()) it will return null.

But if you are not in errors page, I think that you can't use multiple @extends like that you are doing.

It should works if you have single @extends and then add conditional views inside @extends, something like:

@extends( 
isset(Auth::user()->user_type1) ? 'layouts.app-user_type1' : 
(isset(Auth::user()->user_type2 ? 'layouts.app-user_type2' : 'layouts.app-admin' )
)

But if you have single column that define user type, you could something like:

@extends('layouts.app-'.Auth::user()->user_type)

Which is more readable.

Activity icon

Replied to @extends Not Working As Expected In 404 Error Page

You can't access current user in errors page. The errors is triggered before user is retrieved from database.

Oct
08
2 weeks ago
Activity icon

Replied to Get Title Value Of Role Collection

Or you can get all title of roles using below:

@foreach($users as $user)

// You can change separator in implode()
{{ $user->roles->pluck('title')->implode(' | ') }}

// Separate by comma:
{{ $user->roles->pluck('title')->implode(', ') }}

@endforeach 
Activity icon

Awarded Best Reply on RESTful API Many To Many

See here https://laravel.com/docs/8.x/eloquent-relationships#updating-many-to-many-relationships

$user->roles()->attach($roleId);
$user->roles()->detach($roleId);
$user->roles()->sync([1, 2, 3]);
$user->roles()->syncWithoutDetaching([1, 2, 3]);
$user->roles()->toggle([1, 2, 3]);

And there are others method.