DavidPetrov

DavidPetrov

Member Since 1 Month Ago

Experience Points 650
Experience Level 1

4,350 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 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.

18 May
1 day ago

DavidPetrov left a reply on Know If The Limit Has Reached For Plan

$exceeded = $user->city->users()->whereHas('plan', function($query) use ($plan){
    $query->where('id', $plan->id)
})->count() > $plan->limit; //count the users from the same city having that plan (assuming that `User` blongsToMany `Plan` and vice versa) and check if it's above the limit
17 May
2 days ago

DavidPetrov left a reply on Auth::logout() Not Working As Expected

@MTHOMAS - Yeah, it's better this way and actually worked out! I thought on the same principle that I can simply redirect to the route to the index instead to the action of the controller, which shall generate one more request and thus have the same effect, but seems it doesnt... That's what mislead me. So logging out works perfectly now! Thank you!

DavidPetrov started a new conversation Auth::logout() Not Working As Expected

Again, I may be misconcepting something, but anyway. Point is I'm trying to develop a /dev route which shall make me from admin user (where I'm logged in) to a guest (where I'm incoming with a company's hash as a completely unknown new guest user). So basically what I need from the /dev route is to log me out and redirect me to a link with the company's hash. That's how it looks:

Route::get('/dev', function(){
    return redirect()->to(route('guest', ['companyHash' => \App\Company::first()->hash]));
});

    Route::get('/guest/company-{companyHash}', '[email protected]')->name('guest');

And that's the [email protected] method:

public function incomingGuest(Request $request, $companyHash)
    {
        Auth::logout(); //seems to not work

        try
        {
            $id = decrypt($companyHash);
        }
        catch(\Illuminate\Contracts\Encryption\DecryptException $ex)
        {
            //logger('No company with hash '.$companyHash);
            return redirect()->action('[email protected]');
        }
        
        $company = \App\Company::find($id);
        session()->put('company', $company);
        
        Cookie::queue(cookie()->forever('company_id', $id));
        
        return redirect()->action('[email protected]');
    }

[email protected] handles the request based on whether the user has been recognized as a guest or not. Problem is that Auth::logout() changes nothing and when I've been logged in, I'm not getting logged out and redirected but rather the controller sends me to my logged in home page. I also tried resending the request after logout, because I thought it may need a refresh of the request, but with no success.

Could that be a middleware issue? Something looping somewhere. Or is that just how Auth::logout() works and I'm misusing it. Ideas? Thanks!

16 May
3 days ago

DavidPetrov started a new conversation Laravel Cookie Forever Expires

So either I don't seem to correctly grasp the concept of cookies and sessions or there's something wrong. What I'm strangely experiencing is the following: I've got a very crucial token I need to save for the user when they log in from a special link containing the token, so for that matter I'm using a cookie and am setting it forever.

Here's the code:

public function index(Request $request)
    {
        $company = company(); //fetches company from the cookie and several other instances if it's not present there
        
        if(!$company)
        {
            return redirect()->action('[email protected]');
        }
        
        clearConfiguratorSession();
        Auth::login($company->users->first(), true); //works, don't bother
        Cookie::queue(cookie()->forever('is_guest', true)); //that's a crucial cookie, but it's getting emptied
        
        return view('dogrami.select');
    }
    
    public function incomingGuest(Request $request, $companyHash)
    {
        try
        {
            $id = decrypt($companyHash);
        }
        catch(\Illuminate\Contracts\Encryption\DecryptException $ex)
        {
            //logger('No company with hash '.$companyHash);
            return redirect()->action('[email protected]');
        }
        
        $company = \App\Company::find($id);
        session()->put('company', $company); 
        
        Cookie::queue(cookie()->forever('company_id', $id)); //that's the other crucial cookie
        
        return redirect()->action('[email protected]');
    }

However, when the session has been open for longer than its lifetime (which by default is 120 minutes), this cookie is getting emptied alongside the session, so the user can refresh and loses his identification functionality. Is that a desired behaviour and if not, how can I sustain eternal cookies? :D Thanks a lot in advance!

14 May
5 days ago

DavidPetrov left a reply on Verify And Obtain User Data At Application Level

Yes, you would have no problem registering a global middleware for logged in users checking that condition. If it's not fulfilled, redirect to the desired page. It's the same way the auth middleware works.

13 May
6 days ago

DavidPetrov left a reply on Validation Date

There's a prebuilt date rule, have you checked it out? https://laravel.com/docs/5.8/validation#rule-date There's also a plenty of optional rules and customizable rules, so I guess you might be interested.

08 May
1 week ago

DavidPetrov left a reply on Multiple Models To Same Table

@FORRESTEDW - Currently facing the same issue. But I guess that's a compromise that you'll have to accept, after all your custom class only filters retrieved results from the parent class... I'm also on the search for a more intuitive approach!

07 May
1 week ago

DavidPetrov left a reply on Laravel File View Response - Download Prompted With File Name As Last Part Of Route

@NAKOV - What looked like a method not setting headers was actually my browser caching the file view for some reason. I still don't know if it was laravel at fault or my browser, but nothing seemed to change about the whole route where the file was displayed... (figured it out when I actually deleted the whole method from the controller and it still kept displaying). Sorry for the false alarm and thanks for the response anyway!

05 May
2 weeks ago

DavidPetrov started a new conversation Laravel File View Response - Download Prompted With File Name As Last Part Of Route

It's a quite simple problem but I can't find anything on the topic online, only a couple of posts with the same problem but no solution. Baiscally, I've got a controller method which returns a file to the user to view:

    public function viewFile(Request $req)
    {
        return response()->file(Storage::disk('files')->url(urldecode($req->rel_path)));
    }

The url is the following: https://myserver.com/viewFile?rel_path=order%2F5366%2FIMG_20190415_093933.jpg and the file is getting displayed properly. But when a user prompts to download it, browsers suggest the last part of the route (in this case - viewFile) as the file's name instead of its real name. So the data is kinda lost (or a user has to type the name in manually from the link), which is not such a big matter but it's overcomplicating things.

I tried setting filename in the header as suggested [url=https://stackoverflow.com/a/43491469/5885062]here[/url], but without success.

Any ideas? Thanks in advance!

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

The example you provided should do the work for you. What is the essence of the error you're getting? What's exactly wrong with your accessor using the relation's attribute?

DavidPetrov left a reply on Populating Default Pivot Attributes By One Of The Related Models

@NAKOV - This sure is a nice idea, but it's a different matter. What I was talking about turned out to be employed in v5.8 of the framework, so it seems I'm going to be upgrading as soon as possible! Thanks anyway!

04 May
2 weeks ago

DavidPetrov left a reply on Weird Behaviour On Paginating With Join And `having` Clause

@ROBSTAR - Jeez, you saved my life here. Now that I've found the problem and you have linked me to some resources I see it's a common issue since a while, probably marked as wontfix due to incompatibility. Anyway, you saved my life here! I guess a simple compromise with the pagination links is worth the results! Using simplePaginateas of right now!

DavidPetrov left a reply on Weird Behaviour On Paginating With Join And `having` Clause

@AGILASADI - I'm sorry for that, really forgot to get rid of the absolute value stuff. Updating the question. It's just really that people always ask for the real code so after gathering some experience I've really stopped removing even obviously innocent parts of code because problems often tend to hide namely there :D

DavidPetrov started a new conversation Populating Default Pivot Attributes By One Of The Related Models

Situation is the following: I've got two tables: orders and articles which are many to many related. For the sake of easier usage I'm using a custom pivot model OrderArticlePivot as described in the documentation. My pivot table has custom attributes: count, price, time. Same attributes are present in the articles table. I'd really like to somehow tell my custom pivot model to inherit those attributes from the Article instance being attached to an order without having to everytime pass the attributes to the attach() method. Is there any way of achieving that? The documentation on custom pivot models is really brief and I couldn't find anything on the topic. Thanks!

DavidPetrov started a new conversation Weird Behaviour On Paginating With Join And `having` Clause

So after continuosly trying a lot of options related to a query I've come to a very strange matter I'd consider a problem with the query builder... since I can't find any other logical explanation.

Basically I've got two tables: orders and revenues. Order has many Revenues and I want to only load the orders whose price is greater than the sum of the paid revenues, in other words - orders with hanging debts on them. Building my query I've come to a very strange situation:

This works perfectly just as expected:

$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
                ->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
                ->groupby('orders.id')
                ->get();

Whereas this:

$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
                ->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
                ->groupby('orders.id')
                ->paginate(10);

throws a very odd error:

Column not found: 1054 Unknown column 'price_to_customer' in 'having clause' (SQL: select count(*) as aggregate from `orders` left join `revenues` on `orders`.`id` = `revenues`.`order_id` and `revenues`.`is_paid` = 1 group by `orders`.`id` having price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > 0)

So it comes that ->paginate() leads to an existing table column not being recognized by the query? Any ideas as of what could be causing this behaviour?

DavidPetrov left a reply on Use SUM Of Value In Related Table In Where Clause

@JLRDW - Thank you both for your responses! I've opened a thread here: https://laracasts.com/discuss/channels/eloquent/select-sum-of-realtions-attributes-in-query?page=1#reply=508744 I've come to a weird conclusion... Having actually works fine just the way I stated it, but what causes the issue is the paginator! That means, that error is only being thrown when I add ->paginate(10) instead of ->get() at the end of the query... Any ideas why? Here's the query. Works perfectly:

$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
                ->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
                ->groupby('orders.id')
                ->get();

Doesn't work:

$orders = App\Order::leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
                ->havingRaw('price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > ?', [0])
                ->groupby('orders.id')
                ->paginate(15);

Error thrown:

Column not found: 1054 Unknown column 'price_to_customer' in 'having clause' (SQL: select count(*) as aggregate from `orders` left join `revenues` on `orders`.`id` = `revenues`.`order_id` and `revenues`.`is_paid` = 1 group by `orders`.`id` having price_to_customer - (case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) > 0)

I didn't want to invade this topic, we can continue anew in my thread. Thank you a lot for your support!

DavidPetrov left a reply on Select Sum Of Realtion's Attributes In Query

@ADCADE - Thank you for the suggestion, I do actually already have an attribute getter set up for the purpose. Didn't think whether the $appends clause would change anything but it appears (as stated in the documentation) that it only modifies the loaded model serialization to array (adds the custom attributes), so it can't affect the query builder.

02 May
2 weeks ago

DavidPetrov left a reply on Use SUM Of Value In Related Table In Where Clause

@KIMMER - That's actually the strange problem I'm encountering... The aggregate sum is working fine, but what's actually a real column in my orders table is not being recognized by the query builder... I read a couple of documentation statements saying that different cores for sql had different treatment of the having clause, hence some only allowed aggregates and selected columns to be used, but even after selecting the column manually I still get the same error... So I'm stuck.

DavidPetrov left a reply on Intercepting Laravel Login Error

I wouldn't recommend intercepting with the vendor's logic, but where the actual magic happens is in the trait AuthenticatesUsers that's being used by your default LoginController, more exactly in the sendFailedLoginResponse method. Unfortunately, the only feedback you get on a failed login attempt is a thrown error with a message, which gets returned to the login page, so you either use the given error key in your view or you modify/override the function in your controller.

DavidPetrov left a reply on Use SUM Of Value In Related Table In Where Clause

@KIMMER - Thank god I found that post! Helped me a lot! I've only got one question regarding your working query:

$tracks = Track::query()->leftJoin('votes', 'tracks.id', '=', 'votes.track_id')
                ->select('tracks.*', 'votes.track_id')
                ->selectRaw('sum(votes.vote) as score')
                ->havingRaw('SUM(vote) < ?', array(0))
                ->groupby('tracks.id')
                ->get();

How is ->havingRaw('SUM(vote) < ?', array(0)) working? Shouldn't it be ->havingRaw('score < ?', array(0)) since you've already selected your sum as score? I'm trying to do exactly the same kind of filtering but the having clause keeps failing (either a syntax error or not filtering at all)... Here's my example:

App\Order::query()->leftJoin('revenues', function($j){ return $j->on('orders.id', '=', 'revenues.order_id')->where('revenues.is_paid', true);})
                ->select('orders.*', DB::raw('(case when abs(sum(revenues.price)) < 1 then null else sum(revenues.price) end) as paid_from_customer'))
                ->having('paid_from_customer', '>', 0)
                ->groupby('orders.id');

Which throws an error unknown column 'paid_from_customer'. Tried many variations and can't seem to make it work. Ideas?

DavidPetrov left a reply on Call To Undefined Relationship [videolikes] On Model [App\Videopost].

In thewith() method you need to refer the relation by the method it's been declared in your parent and not the foreign key column. So what you'd need would be ->with('hasVideoLikes') (or whatever the method's name shall be in your Videopost model. Anyway, I think you're misconcepting the relations judging by their names, so your question is a bit hard to understand. Hope you got what I had to say, I would also advise you to take a look at the documentation ;)

DavidPetrov started a new conversation Select Sum Of Realtion's Attributes In Query

I really can't figure it out although it's fairly simple... I've got two tables: orders and revenues and I want to add a global scope to my Order modal to load the sum of its paid revenues as an attribute. I tried joining and selecting the sum but nothing seems to change. The closest I've come to building the query was the following:

static::addGlobalScope('withPaidFromCustomer', function($builder){
            $builder->leftJoin(DB::raw('select order_id, is_paid, sum(price) as paid_from_customer FROM revenues'), function($j){
                $j->on('revenues.order_id', '=', 'orders.id')->where('revenues.is_paid', true);
            });
        });

I hope it's clear. I just want to get the paid_from_customer attribute in my model after querying. Thansk in advance!

29 Apr
2 weeks ago

DavidPetrov left a reply on Laravel Maintenance Mode Troubles

@NAKOV - Thanks a lot, I was able to solve the message issue. Otherwise I'm overall considering migrating to the newest 5.8 anyway... but I'll have another look at the support of the command. Thanks a lot again, I'll update if anything new appears!

28 Apr
3 weeks ago

DavidPetrov left a reply on L5.6 - Php Artisan Down --allow=... Not Working

Is there anything new about the issue? I'm having the same problem with laravel 5.6.18. Seems so irational to me...

25 Apr
3 weeks ago

DavidPetrov left a reply on Laravel Maintenance Mode Troubles

@NAKOV - The command is absolutely classical: php artisan down --allow=127.0.0.1, the outpus states The "--allow" option does not exist.. I found an exception trait in the logs, but I don't think it could be of much use in that case. There it is anyway:

[2019-04-25 13:03:45] local.ERROR: The "--allow" option does not exist. {"exception":"[object] (Symfony\Component\Console\Exception\RuntimeException(code: 0): The \"--allow\" option does not exist. at /home/mydomain/mysite.com/vendor/symfony/console/Input/ArgvInput.php:217)
[stacktrace]
#0 /home/mydomain/mysite.com/vendor/symfony/console/Input/ArgvInput.php(151): Symfony\Component\Console\Input\ArgvInput->addLongOption('allow', '127.0.0.1')
#1 /home/mydomain/mysite.com/vendor/symfony/console/Input/ArgvInput.php(82): Symfony\Component\Console\Input\ArgvInput->parseLongOption('--allow=127.0.0...')
#2 /home/mydomain/mysite.com/vendor/symfony/console/Input/Input.php(55): Symfony\Component\Console\Input\ArgvInput->parse()
#3 /home/mydomain/mysite.com/vendor/symfony/console/Command/Command.php(210): Symfony\Component\Console\Input\Input->bind(Object(Symfony\Component\Console\Input\InputDefinition))
#4 /home/mydomain/mysite.com/vendor/laravel/framework/src/Illuminate/Console/Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#5 /home/mydomain/mysite.com/vendor/symfony/console/Application.php(865): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#6 /home/mydomain/mysite.com/vendor/symfony/console/Application.php(241): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Foundation\Console\DownCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#7 /home/mydomain/mysite.com/vendor/symfony/console/Application.php(143): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#8 /home/mydomain/mysite.com/vendor/laravel/framework/src/Illuminate/Console/Application.php(89): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#9 /home/mydomain/mysite.com/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#10 /home/mydomain/mysite.com/artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#11 {main}
"} 

The problem with the message is strange though... no output, nothing seems to throw an error. It just doesn't update the message, the first input remains.

24 Apr
3 weeks ago

DavidPetrov started a new conversation Laravel Maintenance Mode Troubles

I checked my laravel version and it's 5.6.18, somehow anyway the attributes for the down command are not working properly. First, it says option --allow does not exist and secondly, I can't update the message. The first time I tested with the documentation's example Be right back! and now no new input is accepted. What could cause this overall odd behaviour?

19 Apr
1 month ago

DavidPetrov left a reply on Using Laravel Policy To Filter Eloquent Query

@JLRDW - Thank you for the detailed answer! I'm already aware of everything you mentioned and that's my current approach. I was more likely imagining something as simple as App\Document::whereCan('view')->get() to filter the documents query the way I mentioned: only get the documents which the curret user can view similarly to the way policies function (if($user->can('view', $document)). But I guess there's no such SO simple way to achieve that...

18 Apr
1 month ago

DavidPetrov started a new conversation Using Laravel Policy To Filter Eloquent Query

So I recently just got into the concept of gates and policies and totally loved it. However, a natural question that appeared alongside my work was if I could somehow simply use similar logic to filter my eloquent queries based on access constraints defined in policies, because that would really optimise my infrastructure and boost performance.

I can, however, see that policies are made to work with implicit model binding and are using fetched instances. Would there be an analogy for such an approach when building queries anyway?

A modest example would be the following: I've got two models, Role and DocumentCategory that share a belongsToMany relationship. Every User has a role and I want to only fetch the documents for the use to see, whose categories belong to the user's role. Policies work like a charm and I realize filtering my query would not be that simple.

Any Ideas? Thanks in advance!