kovbo

kovbo

Member Since 1 Year Ago

Experience Points 1,130
Experience Level 1

3,870 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 7
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

06 May
1 month ago

kovbo left a reply on REST API Update Architecture Using Specific Actions

@MUSHOOD - Yeah, sure, in this case it could be just one service. However, I'm wondering how to deal with such situations in general. There can be dozens of different actions in a complex application.

Should I register a route for each action (it may mess up the code), or follow rest architecture somehow passing action name..

05 May
1 month ago

kovbo started a new conversation REST API Update Architecture Using Specific Actions

Hello guys, I want to ask for your advice with building rest API with Laravel. Especially, Update requests.

I use standard architecture to update records just passing new parameters via axios request.

But sometimes I need more specific logic. For example, dealing with User model I would like to send a specific request to block or activate or a user. Of course, I could make specific routes for this purpose:

/users/{id}/block
/users/{id}/activate

and create 2 dedicated controllers. But it seems that this approach does not follow rest principles.

What is the right approach to implement this? I'm thinking to create 2 dedicated service classes (BlockUserService and ActivateUserService) and inject them into User Controller. After that I could send a regular put request with an action name to the Update function of the User controller, and implement something like:

if($request->block)
{
return $this->block($user);
}

Not sure if it s right. And how to pass the action name to the controller in this case? Should I append hidden input with the action name, or use route like: PUT "/users/{id}?action=block"?

Maybe there are other best practices?

kovbo left a reply on Ordering Results By Relationship Field Without Fetching All Records

@DAVIDPETROV - Well, I don't know what exactly caused the error, it tried to get the relationship without success, but I fixed it selecting only one attribute from the joined table: ->select('users.*', 'age')

Now the final query looks like this:

User::join('profiles', 'users.id', '=', 'profiles.user_id')->select('users.*', 'age')
            ->orderBy('profiles.age')->paginate(10);

It joins only one field, and sorts table by this field. All other information from the profile can be loaded as nested relationship, so it will not break any front-end logic.

kovbo started a new conversation Ordering Results By Relationship Field Without Fetching All Records

Hello, I'm building an API using Laravel and facing a problem with ordering model results by relationship field.

Let's imagine I have a User model, and a Profile model. Profile belongs to a User. Profile table has an 'age' field.

Can I order Users by age field in Profile table and paginate result without fetching all Users from the database?

As for now, the only option I know is to use raw query with join:

Users::join('profiles', 'users.id', '=', 'profiles.user_id')
            ->orderBy('profiles.age')->paginate(10);

However, this option gives me an error because I have some appended accessors in my User model, invoked by $this->profile->age keywords.

I could also use ->get()->sortBy() function. But in this case pagination is not available, it will receive all records from the database.

Is there any way to order results by a relationship field using Eloquent?

15 Apr
2 months ago

kovbo left a reply on Api Routes In Non SPA Application.

@STEREOH - That's an interesting idea! I shall try both. POST requests usage for Vue calls sounds good to me. It may just confuse a little, because it receives a data breaking rest principals, but not creates.

kovbo started a new conversation Api Routes In Non SPA Application.

Hello, I'm working on a project with a basic Laravel architecture. It is not an SPA, however, some views are extracted into Vue components. These components receive their data through axios get requests. For example, <user-list> component calls "/users/all/" route to receive users data, and everything works fine.

However, if I visit this route using browser, it returns an array of data.

Is it a normal practice to keep such routes accessable via browser?

23 Sep
8 months ago

kovbo started a new conversation Delayed Jobs Vs Task Scheduling To Fire An Event.

Hi! I need to send an email notification when the deadline of my model has passed. Creating a model instance I can delay dispatching of the job based on the "deadline" field. But is it okay to delay execution of the job for several days? Maybe it is better to use Scheduling, and run a script each 5 minutes in order to find all the instances where the deadline has passed? What is better in terms of performance?

02 Jun
1 year ago

kovbo left a reply on Delete/Reject Multiple Items From Collection.

Oh, yes, you are right, it was just typo. This solution works great. One again, thank you for your help!

kovbo left a reply on Delete/Reject Multiple Items From Collection.

@Cronix Yes, thank you! It was exactly what I was looking for!

My users collection was mixed up, so I had to modify your code slightly.

        $newColection = $users->reject(function($user) use($ids) {
            return in_array($user->id, $unique);
        });

kovbo started a new conversation Delete/Reject Multiple Items From Collection.

Hello everyone. I have a collection of users. Also, I have an array of ID's.

How can I remove all users from the collection where user id == id from the array?

I tried to use reject method inside foreach loop, looping throw the array, but I cannot figure out how to save the result..

11 May
1 year ago

kovbo left a reply on Dynamic Accessors Alternatives.

@bobbybouwmann Thank you for your help!

I cannot call the function inside my view, since I'm using Vue.js.

But you are right, I can append that field using map() method!

$users = User::topUsers()->get();

            $result = $users->map(function (User $user) use ($category) {
                $user['category_rating'] = $user->getCategoryRating($category->id);
                return $user;
            });

I'm not sure if it is the most convenient way, but it works fine.

10 May
1 year ago

kovbo left a reply on Dynamic Accessors Alternatives.

@bobbybouwmann Of course, I understand it, I use getRandomAttribute in order to calculate general rating.

But in my case, I should calculate the rating attribute based on opened category. Each user will have different rating in each categoty.

It would be just perfect to use:

public function getRatingAttribute($category)
{
    // Calculation based on $category
}

For example, I can create 10 different accessors (for each category), and use something like this:

$users = User::topUsers()->get();

foreach ($Users as $user) { $user->append("Category{$category->id}Rating")->toArray(); }

But It requires a bunch of switch case statements in the view file in order to figure our what particular attribute should be displayed.

I can also pass an array into my accessor.

public function getRaitingAttribute()
    {
        $rating = collect([
            'Category1Rating' => //Calculation,
            'Category1Rating' => //Calculation,
        ... and so on
]);
        return $rating;
    }

But it requires tons of calculations.

kovbo started a new conversation Dynamic Accessors Alternatives.

As I know, it is not possible to pass any data into laravel accessors like:

getFooAttribute($variable)

Instead, we can use functions in order to calculate dynamic properties:

getFoo($variable)

But how can I append this field into my collections? How can we pass these data into Vue?

Let's say I have a blog, and I want to display top users in each category sorted by rating in this category.

If I have 10 categories, there should be 10 different rating values for each user. In my controller I want to append user's rating based on category id. Right now I can only sort my collection.

public function showCategory(Category $category) {

$users = User::topUsers()->get();

$sorted = $users->sortByDesc(function ($user) use ($category) { return $user->getCategoryRating($category->id); })->values()->all();

But I cannot append these values into my collection in order to access them from Vue.

Of course, I can add 10 additional columns into my db, but I do not think this is a good idea. Are there any other solutions?

11 Apr
1 year ago

kovbo left a reply on Laravel 5.6. The Page Has Expired Due To Inactivity Problem After Ajax Login.

Thank you, @Snapey , you are right.

Laravel has sendLoginResponse function which regenerates user's session.

protected function sendLoginResponse(Request $request) { $request->session()->regenerate();

    $this->clearLoginAttempts($request);

    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}

You can override this function inside LoginController.php, and either delete this line: $request->session()->regenerate();, or return the new token:

protected function sendLoginResponse(Request $request) { $request->session()->regenerate(); $this->clearLoginAttempts($request); if($request->ajax()){ // If request from AJAX return [ '_token' => Session::token(), ]; } else { // Normal POST do redirect return $this->authenticated($request, $this->guard()->user()) ?: redirect()->intended($this->redirectPath()); } }

kovbo left a reply on Laravel 5.6. The Page Has Expired Due To Inactivity Problem After Ajax Login.

@Snapey, for some reason it works when I downgrade my dependencies from 5.6 to 5.5, and when I register a new user.

But anyway, is there any chance to get the new csrf token from sessions after the user is logged in without refreshing the page?

10 Apr
1 year ago

kovbo started a new conversation Laravel 5.6. The Page Has Expired Due To Inactivity Problem After Ajax Login.

I created a form which is public. However, it requires the user to be logged in before it can be submitted.

Basically, I combined 2 forms on the same page: login form, and the main form.

I'm using AXAJ to authenticate user, and sending the main form on success without refreshing the page. Like this:

$(function(){ $('#login-form').submit(); $('#login-form').on('submit', function(e){ e.preventDefault(); }); });

                var loginForm = $("#login-form");
                loginForm.submit(function(e){
                    e.preventDefault();

                    var loginData = loginForm.serialize();

                    $.ajax({
                        type: "POST",
                        url:'/login',
                        data : loginData,
                        success : function(data){
                            
                            $("#main-form").submit();

                        }

                    });
                });

It works fine with Laravel 5.5, but Laravel 5.6 gives me "The page has expired due to inactivity" error. Authentication works fine, and the user is logged in after refreshing the page. But the form cannot be submitted without refreshing the page.

Of course, I'm using {{ csrf_field() }}.

Moreover, it works fine when I try to register a new user, and submit the form on success.

It also works fine if I add my main form route in the CsrfToken exception via VerifyCsrfToken class (protected $except).

But how can I solve this problem? Maybe I missed something?