DavidPetrov

DavidPetrov

Member Since 3 Months Ago

Experience Points 6,490
Experience Level 2

3,510 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 10
Lessons
Completed
Best Reply Awards 8
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.

18 Jul
1 day ago

DavidPetrov left a reply on Where Are You All From?

Stara Zagora, Bulgaria. About to study abroad in Karlsruhe, Germany!

17 Jul
2 days ago

DavidPetrov left a reply on Method Illuminate\Mail\Mailer::from Does Not Exist.

I think you're supposed to use the Mail facade instead of the Mail\Mailer class. Double check if Mail is referencing to Illuminate\Support\Facades\Mail, it should be a common alias, but at the place where you're using your code this might be overriden.

DavidPetrov left a reply on Pivot Table For 3 Models?

That's of course an approach but it's already an infrastructural matter and depens on how similar exactly Gear and Motor are in their role as Product for the application and hence how unifiable they are. If they require extendedly different functuality as separate classes, then that won't suit up that good. Otherwise your suggesstion is definitely worth a thought as an option! But yet again, we can't know how things look within the bigger picture, so it's up to the OP.

DavidPetrov left a reply on Pivot Table For 3 Models?

Then that's exactly what you need! Your pivot table (preferably named product_supplier) will then look like this:

product_type
product_id
supplier_id
price

Accordingly, the Models. You will find it all there!

DavidPetrov left a reply on Pivot Table For 3 Models?

Is there an unique combination of motor and gear you need the price of? If so, three sided pivot table is the way to go. But if you need either a motor or a gear to have a price from a given supplier, then you need a polymorphic many to many relationship: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many-polymorphic-relations Everything is described in thorough detail there, if you need further assistance anyway, you can always ask here! Happy coding!

16 Jul
3 days ago

DavidPetrov left a reply on Is There A Without Relationship?

Yes, if you have for example protected $with = ['author', 'store']; you can avoid loading the author by using the without() method:

Book::without('author')->get(); //loads  the books without retrieving the authors
15 Jul
4 days ago

DavidPetrov left a reply on Placeholder In String

$placeHolders = ['name', 'date']; //let's presume you know all the keys you're going to be replacing
$name = "George"; //whether a variable or a key in array, you can access that vale in your foreach loop
$date = "yesterday";
$sentence = 'Hello :name, we have not seen you since :date.'; //I'd adives to use the ':key' syntax since things tend to get quite messy with curly brackets in strings.

foreach($placeHolders as $ph)
{
    $sentence = str_replace(":$ph", ${$ph}, $sentence);
}

echo $sentence; //Output: "Hello George, we have not seen you since yesterday."
14 Jul
5 days ago

DavidPetrov left a reply on How Can I Sort Storage File

Check this out: https://stackoverflow.com/questions/40384545/sort-files-by-date-added-laravel-php

Also, there are plenty of solutions out there. Try to look better!

DavidPetrov left a reply on Relationship BelongsTo Two Columns

There's a ready conception for that purpose, you don't need that third model. What you need is a two sided many to many relationship with a pivot table attribute. The third table results you have shown is exactly 1:1 the pivot table of the file-field many to many relationship. Check out the documentation: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many you'll find examples.

11 Jul
1 week ago

DavidPetrov left a reply on Get Full Key From Multidimensional Array

That's a classical recursion taks. I've explained everything, hope it's clear:

public function lookUpArray($arr, $desiredKey, $carry = null)
    {
        $fullKeys = []; //that's the initial array we'll be returning
        foreach($arr as $key => $val) //begin looping first level of array
        {
            if($key == $desiredKey) //if that's our desired key, add it to the carry (in case it's present) and save in te array
            {
                $fullKeys[] = $carry ? "$carry.$key" : $key;
                continue;
            }
            else if(is_array($val)) //else we'll do recursion
            {   
                //our function returns an array, so we'll merge the results with the results previously gathered in our $fullKeys array
                //our new array to search is the $val array, so we put that in
                //if we had a carry as the key from a previous iteration, just concat it with the current key (add a dot if needed) and that's our new carry!
                $fullKeys = array_merge($fullKeys, $this->lookUpArray($val, $desiredKey,  $carry ? "$carry.$key" : $key));
            }
        }
        
        return $fullKeys;
    }

What you then simply need is:

    $arr = [
            'a' => [
                'b' => [
                    'c' => 1,
                    'd' => 2,
                ],
                'e' => [
                    'f' => 3,
                    'g' => 4
                ],
                'h' => [
                    'i' => [
                        'j' => 5
                    ],
                ],
                'j' => [
                    'k' => 2
                ]
            ]
        ];

        $fullKeys = $this->lookUpArray($arr, 'j'); //or whenever you define it, call it accordingly

Otput is:

["a.h.i.j","a.j"]
10 Jul
1 week ago

DavidPetrov left a reply on Doubt On How To Define Model For Team-Athletes-Sports Relationsships

What you need is a three-sided many to many relationship, meaning you'll have a team_athlete_sport table containing the three id colums at once. Then you can define a many to many relationship between each two of them that you need and use a custom pivot model TeamAthleteSportPivot. You can refer to the documentation on that matter. Now every time you retrieve the relation of player A playing sport B, you can then retrieve the sport C on that db entry via the custom pivot model's relationships (you'll need respectively three of them).

09 Jul
1 week ago

DavidPetrov left a reply on Function Is Not Defined Showing In Console But Function Is Exists In File

Your function must be defined in the global scope and I doubt it is since I'm noticing a little }); closing tag under its definition, which suggests to me that it's been defined inside a $(function(){}); tag.

08 Jul
1 week ago

DavidPetrov left a reply on Sum Of Model Attributes With Same ID

Let's presume your chosen ids are stored in a collection: $chosenIDs = collect([2, 3, 5, 3, 9, 10, 10]);

Then you must retrieve a corresponding volume_flow for each of those IDs to further sum, so you'll still need $systems = System::whereIn('id', $chosenIDs->unique())->pluck('volume_flow', 'id'), which will be equivalent to a collection like collect([$id1 => $flow1, $id2 => $flow2])//etc...

For your sum you can then optimally do like $sum = $chosenIDs->reduce(function ($sum, $id) use ($systems){ return $sum + $systems->get($id); });

07 Jul
1 week ago

DavidPetrov left a reply on Complex Query Performance

Yeah, my mistake, I got mislead by what was provided. In order to obtain the last completed status you can instead use ->latest()->take(1) for the query. Haven't tested, but should fit into the concept.

06 Jul
1 week ago

DavidPetrov left a reply on Laravel Maintenance Mode Troubles

Well, for some reason the --allow parameter was not present in my version. After I upgraded to 5.8 it was working fine, closing the thread!

DavidPetrov left a reply on Problems To Modify Table Attribute In Migrations, Laravel 5.5

Execute the command php artisan make:migration --table=users

Then a migration will be loaded with your table already set up. Inside the table() function you may alter columns using the ->change() method at the end of your call. Basically what you need is to specify all the characteristics of your columns as if it were a new one but just call change() at the end of the chain. Like this: $table->string('mail')->after('other_example_column')->nullable()->change()

But be careful - if the new data type does not match the old one, you might loose data. In addition, there is a module that needed to be included to laravel in order to modify columns, but it was a long time ago when I last had to enable that functionality so I forgot the details... but there was something exceptional!

Hope that narrows it down for you.

DavidPetrov left a reply on Complex Query Performance

Firstly, your lastCompletedStatus() is not conventional and does not return a relationship, but a retrieved model instead. In order to increase efficiency, you need the conventional approach:

public function lastCompletedStatus()
{
    return $this->statuses()->wherePivot('completed_at', '!=', null)->last();
}

Then, you might simply query your orders by last completed status using Eloquent's whereHas() method:

$orders = $user->orders()->whereHas('lastCompletedStatus', function($query){
    $query->where('name', 'given_status_name'); //or however you define a certain status
})->get();

This will retrieve all of the user's orders having their last completed status's 'name' column match the given value (in this case 'given_status_name'). You can change that accordingly.

Hope that answers your question!

28 Jun
3 weeks ago

DavidPetrov left a reply on Javascript: Adding A Single Function To Multiple Events

Can't you just specify your function as a variable and then register a listener for your event inside of a foreach loop using that function?

DavidPetrov left a reply on Query Scope Based On Multiple Conditions

If I understood correctly - if there's a discount_id, you want discounted price, if not - the normal price. If you didn't know, there's an inbound whereBetween method for laravel's query builder.

$query->whereHas('price', function($q) use ($min, $max){
    $q->where(function($q) use ($min, $max){
        $q->has('discount')->whereBetween('category_discounted_price', [$min, $max])
    })->orWhere(function($q) use ($min, $max){
        $q->doesntHave('discount')->whereBetween('price', [#min, $max]);
    });
})
27 Jun
3 weeks ago

DavidPetrov left a reply on Custom Pivot Table Not Being Respected?

@JOHNNYW2001 - It's not in the docs regarding the custom pivot model, but it is stated right in the chapter before. As shown, the using() method is an extension to the belongsToMany() method, where the specification of the intermediate table's name belongs.

DavidPetrov left a reply on Custom Pivot Table Not Being Respected?

The table is actually not to be specified in the custom pivot model, but rather as a second argument on the belongsToMany() method. Refer to the documentation: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

DavidPetrov left a reply on Getting User's Coordinates Using A Map In A Form

Definitely Google Maps' API, I've been using it for years and it works flawlessly and is incredibly easy accessible. I don't know to what extent it's free though, you'll have to check the conditions out. If I'm not mistaken though, I think JavaScript provides a native module function to prompt your browser to ask the user for their location, it might be sufficient for your needs.

20 Jun
4 weeks ago

DavidPetrov left a reply on Count The Number Of Entries For A Period Of Time

Provided that you have a model class Registration with start_date and end_date column attributes, you can easily query your count:

$todayRegCount = Registration::whereDay('start_date', today())->count();
if($todayRegCount > $maxCount)
{
    //max number of registrations for the day has been exceeded, do whatever you need
}
17 Jun
1 month ago

DavidPetrov left a reply on User Relationships

@EVERGREENWEBSYSTEMS - Yeah, everything's fine except I'm not sure about the id columns' type. bigIncrements does indeed generate an unsigned incrementing big integer, but again, idk if that's not going to cause any integrity trouble depending on how picky your DB engine is (InnoDB is quite picky in that regard :D). If it works, then it's fine, but I suspect the difference in length will be a problem.

16 Jun
1 month ago

DavidPetrov left a reply on User Relationships

Yes, your migrations seem just about right. I can only share a couple of notes from my experience:

  1. a tricky problem you might encounter depending on your database engine: initially the foreign keys and the primary keys must be of the exact same type and length for the foreign key constraints to work and not throw an error. So you'll want the ids on your users and projects table to also be unsignedIntegers.

  2. Another thing you might want to consider is the default naming convention of the pivot tables: project_user, which can spare you a couple of table name specifications.

  3. in order to use a custom pivot model, as far as I recall, you need to give the pivot records an id columns, so that eloquent can treat them as a model

Then all you'll need in your User model would be a method like the following:

public function projects()
{
    return $this->belongsToMany(App\Project::class)->withPivot('id', 'role_id')->using(App\ProjectUser::class);
}

For more details on the custom pivots, refer to the documentation: https://laravel.com/docs/5.8/eloquent-relationships#defining-custom-intermediate-table-models

Cheers and happy coding! ^^

DavidPetrov left a reply on User Relationships

I would personally prefer the single pivot table way since it would be faster to query and easier to access. Laravel provides an easy way to access custom pivot attributes, so you can put your role there, for example as a string access_level or something like that. If you would like to introduce custom role models to furthermore complicate your logic, then you can use a custom pivot model and bind a relationship method to it. If you need some examples, I can provide some, but you can find all you need in the laravle documentation.

14 Jun
1 month ago

DavidPetrov left a reply on Eloquent Query Error

@LEONVR - I suspect that json encoding invitation as a property of inlogdata somehow just converts it into a simple object and not an instance of the model class, which then kills the embedded laravel model functionality. Since I don't see the class either when you dump the invitation, I'm quite sure that's the case. Which refers back to my question above.

DavidPetrov left a reply on Eloquent Query Error

Seems right, weird... Is $invitation an instance of the right class then?

DavidPetrov left a reply on Eloquent Query Error

Seems like your $invitation variable is pointing to a stdClass instead of an instance of App\Invitation, can you show us how you retrieve that certain variable in context?

10 Jun
1 month ago

DavidPetrov left a reply on WhereHas In Advanced LeftJoin

@FTIERSCH - Sorry for the late response, but you answer was actually what I needed! This is how my query looks now and it's working, although it's unimaginably slow...

$query->leftJoin('documents', function($j){ 
                return $j->on('orders.id', '=', 'documents.order_id')
                        ->where('documents.is_paid', true)
                        ->leftJoin('document_categories', 'documents.document_category_id', '=', 'document_categories.id')
                        ->where('document_categories.type', 'revenue');
                })
                ->havingRaw('price_to_customer - sum(documents.price) > ?', [1])
                ->groupby('orders.id');

I suppose the slowing is comnig from the fact that the documents table contains ~10k records, whereas the orders table contains an additional ~6k, thus things are getting complicated when looping keys...

Regarding functionality though it's all fine. Any optimization ideas are welcome! Thanks a lot!

09 Jun
1 month ago

DavidPetrov left a reply on How To Get A Value In Js From Laravel Datatable Cell ?

Classical operation - you can either use an ajax request to fetch your data from the server, or you can use a link to a route, which then reloads the page with the given value, if you want to avoid ajax and make it more consistant as performance.

07 Jun
1 month ago

DavidPetrov left a reply on Method To Sync ManyToMany Relationship From Model With Custom Pivot Columns

Just for an additional disclaimer: I've found a temporary solution for now, which unfortunately includes editing the vendor files... After I've taken a closer look at the relationship's class I've achieved exactly what I need by simply adding a public customPivotAttributes = [] after the protected pivotColumns = []; attribute in the BelongsToMany class and then modifying the withPivot() method in the InteractsWithPivot trait:

    public function withPivot($columns)
    {
        $columns = is_array($columns) ? $columns : func_get_args();

        $this->pivotColumns = array_merge(
            $this->pivotColumns, $columns
        );
        
        $this->customPivotColumns = $columns;

        return $this;
    }

But I really don't like having to edit vendor files since we're planing on migrating to a higher than the current 5.4 version of laravel.

DavidPetrov left a reply on WhereIn Clouse Not After Using Dynamic Variable.

Seems like a basic php misconception. You're using [$arr_contry_exp], which means you're creating a multidimensional array since you're inputing your original array into another bracket pair. Just remove the square brackets and it shall work if the array is correct: $query->whereIn('country_exp', $arr_country_exp);

DavidPetrov started a new conversation Method To Sync ManyToMany Relationship From Model With Custom Pivot Columns

I'm building a massive layer to copy a lot of models with a lot of such relationships so I really need this optimization. A basic example: I've got a model Scheme with the following relationship:

    public function imposts()
    {
        //notice the custom attributes on the pivot
        return $this->belongsToMany('App\Impost')->withTimestamps()->withPivot('count');
    }

I want to copy that scheme. Since it can't be achieved automatically with relationship cloning as well, I'm writing a method to do it in the same class:

    public function copy()
    {
        $copy = $this->replicate(); //replicated the model with it's columns and a new id, quite useful

        //here I want to sync the copy's imposts with the original scheme's imposts BUT with the custom fields listed in the relationship definition. Is it possible? Something like:
        //$copy->imposts()->sync($this->imposts()->toSyncableArray()); //I'd imagine such a method, would be quite useful
        
    //a lot of relationships to clone here... incoming

        $copy->save();
        
        return $copy;
    }

What I want that method to do is simply the following that I'm managing to achieve using this mapping:

$syncableImpostsArray = $scheme->imposts->mapWithKeys(function($imp){
    return [$imp->id => ['count' => $imp->pivot->count]];
})->all();

This produces exactly the array I need for the sync method on a scheme with 5 imposts with respective counts:

[ 
  1 =>  [ "count" => 0 ]
  2 =>  [ "count" => 0 ]
  3 =>  [ "count" => 4 ]
  4 =>  [ "count" => 0 ]
  5 =>  [ "count" => 4 ]
]

As mentioned above, I need this for a lot of models with quite a lot of attributes (refactoring a project with copying functionality). Any ideas as to how to achieve this in a slightly more automatic way?

Thanks in advance for all suggestions!

DavidPetrov left a reply on Call To Undefined Method

In the code provided you're not calling the mentioned method anywhere, so something else is causing the error. You're somehow trying to call a static TotalPrice method which you haven't defined anywhere. Furthermore, you can use aggregate methods and don't have to retrieve the whole collection and iterate it manually. I would go as follows:

public function scopeTotalbillyear($query)
    {
        return $query->whereYear('created_at', date('Y'))->where('status', 'payd');
    }

    public static function getTotalPayd() //since it's a sum of all paid bills, we need a static method which we'll call on the class
    {
        return Payment::Totalbillyear()->sum('amount_payd');
    }

Afterwards you can use your method by simply calling $sum = Payment::getTotalPayd(); //returns the sum of paid amount of all paid bills this year

05 Jun
1 month ago

DavidPetrov left a reply on Two Range Of Number For Data Seeding

What don't you like about this approach? If you need it for a single use once, it's okay, otherwise for integrity's sake it's better to use the attach() method on your models' classes to maintain the relationships. But again, this way should be quick and handy enough for the purpose to attaching the relationships. What's the problem?

30 May
1 month ago

DavidPetrov left a reply on Session Data Lost After Redirect.

Are you sure you're not having a middleware somewhere else that's rewriting the session key and setting a default value? Usually, when you use the session's put method, information should be stored for the lifetime of the session unless something rewrites or resets it. On another occasions, I've also had problems with the default session middleware and positioning other custom middlewares around it in the Kernel.php file. There are a lot of possible scenarious that could cause session termination on given urls when other middlewares are active. I suggest you have a closer look at your middleware net and investigate there.

25 May
1 month ago

DavidPetrov left a reply on Need Help To Think Over A 3 Model Related Query

Firstly, you can use the ->dateBetween() query builder method to just collect the attendances in a given range, like in your case. Secondly, why don't you just set a time_notified column (or something like that) in your member table and save there the exact timestamp you're sending an email to a user, so that you will always know when the last email has been sent. Or am I misunderstanding?

22 May
1 month ago

DavidPetrov left a reply on WhereHas In Advanced LeftJoin

@FTIERSCH - Okay, I got this one, didn't know it could work that way! But the problem still persists, I really am clueless as to how to achieve what I need as described...

DavidPetrov started a new conversation WhereHas In Advanced LeftJoin

So I was having the following query which was working just fine returning all the orders with paid documents having positive debt (difference between order's price and the sum of paid documents' prices):

$query->leftJoin('documents', function($j){ return $j->on('orders.id', '=', 'documents.order_id');)
                ->havingRaw('price_to_customer - sum(documents.price) > ?', [0])
                ->groupby('orders.id'); //hope it's understandable

Now I need to extend the following query adding a check for the document's category's type in the body of the join clause (after on) as an additional constraint. I tried intuitively:

$query->leftJoin('documents', function($j){ return $j->on('orders.id', '=', 'documents.order_id')->whereHas('category', function($q){return $q->where('type', 'revenue');})->where('documents.is_paid', true);})
                ->havingRaw('(case when price_to_customer - abs(sum(documents.price)) < 1 then null else price_to_customer - sum(documents.price) end) > ?', [0])
                ->groupby('orders.id');

but it doesn't work properly and I think it's generating a conflictig query in general. What this produces is the following error:

Column not found: 1054 Unknown column 'has' in 'on clause' (SQL: select `orders`.*, (select count(*) from `montages` where `orders`.`id` = `montages`.`order_id`) as `montages_count` from `orders` left join `documents` on `orders`.`id` = `documents`.`order_id` and `has` = category and `documents`.`is_paid` = 1 where exists (select * from `order_categories` where `orders`.`order_category_id` = `order_categories`.`id` and `program_name` in (order, offer, service, ra_workshop, company_expense, income, expense, income_only)) group by `orders`.`id` having (case when price_to_customer - abs(sum(documents.price)) < 1 then null else price_to_customer - sum(documents.price) end) > 0 order by `number` desc limit 51 offset 0)

As you can notice, it appears around this part: andhas= category and and I find it really odd that the whereHas method is adding has as an additional required column in the query...

Anyway, I hope you get what I'm trying to achieve. Any ideas? Thanks in advance!

19 May
2 months ago

DavidPetrov left a reply on How To Pass A Variable To A Function With Callback?

What is $data? What you have shown here is just a definition of a parameter your anonymous function is expecting, but you don't have it anywhere inside the body of the doIt() function that's actually using it. That's what the error is telling you. If you have $data defined inside doIt(), everything shall work as expected.

18 May
2 months 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 months 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
2 months 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
2 months 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
2 months 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
2 months 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
2 months 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 months 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!