deansatch

Experience

16,350

12 Best Reply Awards

  • Member Since 10 Months Ago
  • 74 Lessons Completed
  • 2 Favorites

22nd January, 2018

deansatch left a reply on How To Include If Condition In Select Option Make The Id Matches • 42 minutes ago

@Shawdow if parent_id is a number why are you checking if it == "some" in your js??

Also why do you have a value attribute in your div tag? You have it in a foreach loop too so you are going to have a lot of value attributes inside one div tag.

You've also added an id inside a loop on your option tag

If I understand correctly, you are wanting to do this (not tested but gives an idea):


<select required class="selectpicker" name ="parent_id" id="parent_id">
    <option value="" ></option>
    @foreach ( $subcat  as  $subcats)
       <option  value="{{ $subcats->parent_id }}" > {{ $subcats->name }} </option>
    @endforeach
 </select>

@foreach($attr as $attrs)  
<div class="some"  id="some_{{ $subcats->parent_id }}"  style="display:none;">
    {{ $attrs->attribute_1 }}
</div>
@endforeach


$('#parent_id').on('change',function(){
    $(".some").hide();
    var some = $(this).find('option:selected').val();
    $("#some_" + some).show();
});

deansatch left a reply on How To Include If Condition In Select Option Make The Id Matches • 3 hours ago

Your javascript looks wrong no matter what it is you are trying to do:


if($(this).val() === "some"){

I expect that should be something more like:


if($('#parent_id option:selected').val() == 3){ // whatever parent_id you are after

Also, your html has id="some" in a loop. You can't use an id more than once

deansatch left a reply on Should We Use Laravel Collective Or Regular Forms? • 4 hours ago

I'd say its which ever you prefer. I use it and there is nothing wrong with mixing & matching...switching back to regular html if you get stuck for a particular form. For form model binding I find it is well worth it - especially when it comes to remembering selected options in dropdowns

21st January, 2018

deansatch left a reply on How To List The Users With Roles Id • 14 hours ago

Does your users table have a role_id column? If not that won't work. What is your relationship setup and table structure?

deansatch left a reply on GroupBy Works On Local Testing Server But Not On Production? • 17 hours ago

Looks like it the production server might be using full group by and your dev one isn't. This could be if you have strict set to true in your config/database.php on production version and false on local. Setting it to false will make it work but probably better to alter the offending query so that it includes 'title'

18th January, 2018

deansatch started a new conversation Ignore Facebook Scrape • 4 days ago

I have a simple status update using save() when a person visits a unique link. This only happens once as I set it to fire if status == 0 then after they visit it ==1. However, when I send the link via facebook to each person facebook has to scrape the page to get the og: data and it counts as the first visitor. Is there a way I can have this little snippet only fire if it is a real person/browser visiting instead?

9th January, 2018

deansatch left a reply on Outgoing Mail • 1 week ago

@bashy what confuses me about this is if the mail is to come from something like [email protected] and they already have their own email addresses set up, how can something like mailgun do this without authenticating? Or does it have to be sent from a @mailgun.com address?

deansatch left a reply on Outgoing Mail • 1 week ago

@bashy recommendations? Again baring in mind some may be large corporations and some are one man bands that just need a simple form on their site for the occasional user so won't be impressed with a £20/month mail service

deansatch started a new conversation Outgoing Mail • 1 week ago

For years when building websites with or without laravel I have been using smtp for sending mail. Generally I would add a mail settings page in the cms where the user can set their email, password, port etc...

This has worked fine so far apart from occasions when they change their email password and forget to reflect that within their site which can cause serious nightmares for the ones that rely on the emails for their business to function.

What are people’s best solutions for sending email from sites, baring in mind that some sites may be one man bands on a tight budget and some might need their site to send 100s of emails a day, or even 100s per minute

I don’t mean queues...just the outgoing server setup and avoiding failed jobs due to password changes or email downtime (a fall back second address could be another subject)

4th January, 2018

deansatch left a reply on Supervisor And Schedule:run • 2 weeks ago

@lostdreamer_nl Thanks for that - I can definitely sort the cron job out instead.

But would a queue worker be a more suitable option for what I am doing? It basically has to listen for certain events and/or membership accounts and when they hit a certain date/time, 'do something' e.g. send email(s). This can be at any minute of the day but might only happen 5 times a day, but could be 300. A cron would work but wondering if there is something more efficient that doesn't run queries every minute hoping for a result.

deansatch started a new conversation Supervisor And Schedule:run • 2 weeks ago

I have a few tasks that need to be constantly checked e.g. has account expired, is invoice due etc... and each task does something like 'find accounts that have past expiry date, loop through and send email to each user'

I have set these up in console/Kernel.php as:


$schedule->call('App\[email protected]')->everyMinute();
$schedule->call('App\[email protected]')->everyMinute();

If I run the command artisan schedule:run in terminal it works as expected. If I wait for another account to expire, type it again it runs.

Likewise if I set the command in supervisor I see it run and work as expected but then it exits and never runs again. I get an "Exited too quickly" error...sometimes it says FATAL, sometimes BACKOFF.

Supervisor conf file command:

``

command=php /var/www/mysite/artisan schedule:run


a) should I be using a different method? I see there are queues :work, :listen etc... but not really sure what the differences are between all these.

b) if I'm using correct method, how do I get it to run my schedules every minute?

13th December, 2017

deansatch left a reply on Very Very Slow Query...how To Speed Up • 1 month ago

@kobear Thanks...I couldn't get toSql() to work but I added an index for classes_id and superfast now

deansatch left a reply on Very Very Slow Query...how To Speed Up • 1 month ago

mysql

deansatch started a new conversation Very Very Slow Query...how To Speed Up • 1 month ago

I have this:


        $subQuery = function($q)use($start, $end){
                       $q->whereHas('classdates', function($q)use( $start, $end){
                            $q->whereBetween('datetime',[ $start, $end]);
                        );
                    };

        $subQuery2 = function($q)use($start, $end){
                        $q->whereHas('classes.classdates', function($q)use( $start, $end){
                            $q->whereBetween('datetime',[ $start, $end]);
                        });
                    };
        
        $studios = \App\Studio::
        select('name')->
        withCount([classes' => $subQuery])
        ->withCount(['bookings' => $subQuery2])
        ->get();

It takes about 20 seconds to run just for a one month date range and I need it to run for full years or even more.

Is there a way I could speed this up?

10th December, 2017

deansatch left a reply on Count 3rd Level Relationship Items • 1 month ago

Do i need to add any more information to get some help on this?

7th December, 2017

deansatch left a reply on Count 3rd Level Relationship Items • 1 month ago

Anyone?

deansatch started a new conversation Count 3rd Level Relationship Items • 1 month ago

I want to get a total number of classes & total number of class bookings per studio (between certain dates). This query works to output [studio(with no. of classes)]->[classes]->[bookings]

So if I dd() I can expand bookings and see the array which i want to count.

$studios = \App\Studio::
        withCount([
            'classes'=> 
               function($q)use($start, $end){
                       $q->whereHas('classdates',function($q)use( $start, $end){
                               $q->whereBetween('datetime',[ $start, $end]);
                               });
             }])
                           
            ->with(['classes.classdates' =>
                function($q)use($start, $end){
                        $q->whereHas('classes.classdates',function($q)use( $start, $end){
                                $q->whereBetween('datetime',[ $start, $end]);
                            })
                            ->whereHas('classes.bookings');

                        }
                ,'classes.bookings'
                ])
                ->get();

I thought adding this (2nd bottom line) would work but it gives an error: Call to undefined method Illuminate\Database\Query\Builder::classes.bookings()

$studios = \App\Studio::
        withCount([
            'classes'=> 
               function($q)use($start, $end){
                       $q->whereHas('classdates',function($q)use( $start, $end){
                               $q->whereBetween('datetime',[ $start, $end]);
                               });
             }])
                           
            ->with(['classes.classdates' =>
                function($q)use($start, $end){
                        $q->whereHas('classes.classdates',function($q)use( $start, $end){
                                $q->whereBetween('datetime',[ $start, $end]);
                            })
                            ->whereHas('classes.bookings');

                        }
                ,'classes.bookings'
                ])
->withCount('classes.bookings')
                ->get();

I've tried a few ways of adding withCount() but it only seems to work on my first part...counting the classes

3rd December, 2017

deansatch started a new conversation ToArray() With Primary Key String • 1 month ago

Not sure if this is a bug or supposed to happen but if I get an eloquent collection and use toArray(), if I have set the primary key to an alternative string column it makes the value a zero no matter what.


    protected $primaryKey = 'slug';



$test = $user->posts()->get();
dd($test); //will show my slug value as it should do e.g. "a-post"

$test = $user->posts()->get()->toArray();
dd($test); //will show slug value as 0

28th November, 2017

deansatch left a reply on Envoyer Adds New Stuff And Breaks • 1 month ago

@abbujan did you find anything? This is still causing me major headaches

23rd November, 2017

deansatch left a reply on Envoyer Adds New Stuff And Breaks • 1 month ago

anyone???

17th November, 2017

deansatch left a reply on Envoyer Adds New Stuff And Breaks • 2 months ago

Ok...so this seems to be a bit more of a composer thing and relating to a couple of packages that have been updated.

I inherited this project ready-made so it was already set up on envoyer, github etc... push/pull/deploy had all been going fairly problem free until yesterday. It seems that the second last step of envoyer is to clear OpCache where it fails. I have a second copy of the site on another server for staging and this deployed fine. I looked in vendor/appstract and saw laravel-opcache and lush-http directories. The ones on the staging server seemed to be a different version with less files inside.

I looked on github and see laravel-opcache has been updated recently so at some point it must have applied this update on my live deployment. It's annoying as the version number in composer was set as ^1.2 so you wouldn't expect anything to break.

What I can't quite understand is what exactly is going on with envoyer re:composer. I can't roll back a deployment as I still get the same errors...the vendor directory seems to be set in stone (so how did it change?!?). I've even tried replacing the appstract directory with my staging copy but deployment fails.

Does deploying with envoyer run composer install? or update? or none? Any ideas how I can repair this and fix the versions so it doesn't happen again?

16th November, 2017

deansatch started a new conversation Envoyer Adds New Stuff And Breaks • 2 months ago

On my recent deployment it failed at Clear OpCache with a message:

PHP Fatal error: Trait 'Illuminate\Foundation\Events\Dispatchable' not found in ...vendor/appstract/lush-http/src/Events/RequestEvent.php on line 11

However, this Events folder and all files inside didn't exist in the previous deployment...vendor folder isn't in the git repo anyway. But on deployment the new release contains this new folder and causes a failure on the second last step.

Anyone got a clue a) what is going on and b) what this dispatchable thing is for?

8th November, 2017

deansatch left a reply on Paypal Sandbox Ssl Handshake On Localhost • 2 months ago

If I change the core paypalhttpconfig to CURLOPT_SSLVERSION => 'TLSv1', instead of '6' it works. Not sure if I should change it back to 6 for production or not though?

deansatch left a reply on Paypal Sandbox Ssl Handshake On Localhost • 2 months ago

Nope...I still get exactly the same thing - this must be something to do with ssl on valet?!?

30th October, 2017

deansatch left a reply on No Application Encryption Key Has Been Specified - But The Key Has Been Specified • 2 months ago

If you’ve regenerated the key, did you restart the server?

deansatch left a reply on Multi Auth In One Table • 2 months ago

Looks like your problem is your misunderstanding of routes. You have 3 routes at “/“ & “/home”. Only one of those will be used. If you imagine it reads your routes file and when it matches your url with the route “/“ it goes to that controller and method and runs it. So the other 2 are ignored regardless of the log in state.

Apologies but I’m replying to this on my phone so can’t go more in depth but you should probably look at using one route for “/“ with one controller and one method. Then put your logic in that method for now to determine which view to return.

And for posting on here look at markdown: https://guides.github.com/features/mastering-markdown/

deansatch left a reply on Blog.dev In Browser Doesn't Navigate To Project • 2 months ago

Quit mamp completely otherwise that will take precedence

deansatch left a reply on ~../code: No Such File Or Directory(?) • 2 months ago

He keeps his projects in that directory. You may keep yours somewhere else. E.g. Documents/mysites/ just change that ath to match where you plan to store all your local laravel projects

deansatch left a reply on Admin Adds Users And They Set Their Own Password • 2 months ago

Just thinking about this...would it be better to NOT create a new user on the admin side but instead to populate a new table of 'invited users' containing email, date, bcrypt the email address to generate an invite link, then show the normal registration page only if the url contains an encrypted email address that matches the invites table. That way I could perhaps put a 48 hour time limit on the invites.

If nobody suggests a better method I might just go ahead with this one...I'll wait a little while first and see what people say

deansatch started a new conversation Admin Adds Users And They Set Their Own Password • 2 months ago

What would be the best way of doing this? Say you have a CMS and you want an admin to be able to add more users but you just want to add a name and email, then the new user will get a link to activate and set their password.

I have created a page where the user is created and the password is randomly generated. It finishes by sending out a password reset link via email. I am just wondering if this is the best way to do it as I thought the password reset link might expire after an hour and the new user might not check their emails for a day or so? Also, I would prefer to also have a custom 'set your password' page rather than send them to the default reset password page (but still keep that for when they forget their login)

deansatch left a reply on Middleware In Controller Or On Route • 2 months ago

Anyone want to elaborate on why I shouldn't use middleware for my auth checking? Jeffrey seems to teach that way in his videos i.e. adding auth middleware in the constructor and/or on the route. My original question still also remains unanswered as this applies not just to roles but to basic logged in/not logged in users.

deansatch left a reply on Middleware In Controller Or On Route • 2 months ago

@RamjithAp thanks...I'll have a look at that. Is what I have done so far a bad idea that should be scrapped and rebuilt or should I just think about using gates moving forward in future builds?

deansatch started a new conversation Middleware In Controller Or On Route • 2 months ago

Just wondering if there are any drawbacks to putting middleware directly on a route or route group as opposed to putting it in the constructor on a controller. The reason I ask is because a lot of apps I build have different user types e.g. members, admins, public users etc...

I generally have a single controller for a model so for example if I only wanted an admin to be able to delete a post I would need to add isAdmin middleware. If I stick that in the controller constructor my show(), index() methods etc.. would not be available to members or public. So what I have been doing on a recent project is grouping my routes and adding the middleware to the group so /admin/* has isAdmin middleware. Is this secure?

18th October, 2017

deansatch started a new conversation 504 Gateway Timeout On Wherehas() And Has() • 3 months ago

Basically, if I do a query using whereHas('relationship', $function) or has('relationship') on a table of 9000 rows I get the timeout. (locally on valet, local mysql). Any ideas what might cause this?

13th October, 2017

deansatch left a reply on @if Auth::user()->type • 3 months ago

@if(\Auth::user()->type == 'Admin' || \Auth::user()->type == 'Mod')
    <li><a href="/conf"><span>Configuração</span></a></li>
@endif

10th October, 2017

deansatch left a reply on Use Method Inside Eloquent Query? • 3 months ago

That's ok...although it doesn't help with this particular problem I hadn't actually considered using events instead of schedules and it does seem more appropriate. I just hope I can move onto that stage...I really don't want to move forward with my original method

deansatch left a reply on Use Method Inside Eloquent Query? • 3 months ago

The entries table has each persons scores and the highest one wins (each entrant/user can have multiple entries with varying scores for the same competition). So currentWinner($competition) basically sorts the entries and returns the highest scoring user.

This looks rough, but it makes sense when you know the full ins and outs of the system:

protected static function currentWinner($competition)
    {
        $currentHighScorer = Entry::with('user')->where('competition_id', $competition->id)
        ->orderBy('score', 'desc')
        ->orderBy('id', 'asc')
        ->take(2)->get();
        //->pluck('user.name');
        
        if(count($currentHighScorer)>1){
            if($currentHighScorer[0]->amount > $currentHighScorer[1]->amount){
                return $currentHighScorer[0]->user;
            }else{
                return  $currentHighScorer[0]->user;
            }
        }elseif(count($currentHighScorer)==1){
                return  $currentHighScorer[0]->user;
        }else{
            return false;
        }
    }

deansatch left a reply on Use Method Inside Eloquent Query? • 3 months ago

@Screenbeetle Thanks but that doesn't really include the winner which is the main issue

deansatch started a new conversation Use Method Inside Eloquent Query? • 3 months ago

I have a class Entry. Within the class I have a static method currentWinner($competition).

In the same class I want to notify the winner (I plan to use task scheduling) by email once the competition ends. I can do this:

$competitions = Competition::where('ends_at', '<', Carbon::now())->get();
foreach($competitions as $ended)
{
    $winner = Entry::currentWinner($ended);
    // send mail to this winner
}

However, this seems absolutely awful! I was hoping I could at least do something like:

$competitions = Competition::with('currentWinner')->where('ends_at', '<', Carbon::now())->get();

foreach($competitions as $ended)
{
    // send mail to this winner
}

Any suggestions?

deansatch left a reply on How Would You Dynamically Insert An Element Where It Is Needed When You Know The Base Requirements Of When It Is Needed? • 3 months ago

@section('content')
  <div class="row">
    <div class="col-xs-12">
      @foreach($display_info['users']->chunk(6) as $_user_info)
    <div class="row">
      @foreach($_user_info as $entry => $user_info)
          <div class="col-xs-2">
            <div class="panel panel-default text-center user-profile-2">
              <div class="user-profile-inner">
                <h4 class="user-header">{{$user_info['name']}}</h4>
                @if(App\Models\User::find($user_info['id'])
                  ->avatar !== null)
                    {{Html::image(App\Models\User::find($user_info['id'])
                        ->avatar
                        ->file_path, "Profile Avatar",
                      array(
                        'class' => 'img-rounded profile-avatar',
                        'alt' => $user_info['name'] . "Avatar"
                      ))}}
                @else
                  {{Html::image("storage/avatars/avatar_question-mark.jpg", "Profile Avatar",
                    array(
                      'class' => 'img-rounded profile-avatar',
                      'alt' => $user_info['name'] . " GenericAvatar"
                    ))}}
                @endif
              </div>
            </div>
          </div>
      @endforeach

    </div>
      @endforeach
    </div>
  </div>
@endsection

deansatch left a reply on Strtotime • 3 months ago

That is a date...you'll have to be more specific. Convert to what format exactly?

btw - look at http://carbon.nesbot.com/docs/

deansatch left a reply on Session ID Is Different In Constructor And Action • 3 months ago

I don't think you are supposed to mess with your sessions inside a constructor in general so to fix the problem, just don't do it.

That said, I expect the reason it is different is because laravel will run the constructor before it runs middleware and I think session start is in middleware.

deansatch left a reply on "Valet Open" Problem? • 3 months ago

php artisan serve, not just artisan serve

Try: sudo /usr/sbin/apachectl stop Make sure apache is stopped on mamp then: valet restart

6th October, 2017

deansatch left a reply on "Valet Open" Problem? • 3 months ago

Try stopping your local apache (sudo apachectl stop)

5th October, 2017

deansatch left a reply on Exclude Private Items • 3 months ago

anyone?

4th October, 2017

deansatch started a new conversation Exclude Private Items • 3 months ago

I have a column 'fao' (for attention of) which is set as null by default so all products are viewable by everyone. I want it so if fao contains a specific user id, only that user will be able to see it, edit it etc... This is simple enough to do if I just remember to exclude non-null fao products every time I do an eloquent query on Product... but a bit risky. I'd rather they were all excluded by default and I have to explicitly include them in any views/controllers where required.

Whats the best way to approach this? Was thinking a bit like how a soft deleted item works

deansatch left a reply on Save Old Data After Refresh Page With Ajax • 3 months ago

It looks like he is trying to submit the form as normal but is using ajax during filling out the form to pull in a title to display elsewhere on the page which is fine...however, it looks like you already have the titles in your dropdown so why not just scrap the whole ajax call and do:

$(document).on('change', '.js-delivery', function(e){
                delivery.show();
        $('.delivery-type').html($(this).text());    
        });

Then, if you want your form to remember the selection on error, try using the form builder and it will take care of that for you. You can always run the delivery.show() etc... on doc ready too...if errors are set. Something along these lines:

@if($errors->any())
function populateDelivery(select){
    delivery.show(); //you'll have to set var delivery to whatever it is
    $('.delivery-type').html(select.text()); 
}    
    
$( document ).ready(function() {
    populateDelivery($('.js-delivery').find(":selected"));  
});
$(document).on('change', '.js-delivery', function(e){
    populateDelivery($(this).find(":selected"));  
});  
@endif 

2nd October, 2017

deansatch left a reply on Passing Var In View Composer? • 3 months ago

Actually, this isn't solved. That doesn't work either.

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.