amcardwell

amcardwell

Member Since 3 Years Ago

Atlanta, GA

Experience Points 10,630
Experience Level 3

4,370 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 89
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 Mar
2 years ago

amcardwell left a reply on Laravel 5.4: Bind AuthServiceProvider To Route Group?

@Screenbeetle Nice. That seemed to work! I just moved my logic into a new middleware. I was worried though that my defined Gate methods wouldnt apply but they did. Thanks again!

amcardwell left a reply on Laravel 5.4: Bind AuthServiceProvider To Route Group?

Does no one have an answer to this?

03 Mar
2 years ago

amcardwell started a new conversation Laravel 5.4: Bind AuthServiceProvider To Route Group?

My routes are split up into 2 groups: the web(default) group and the admin(custom) group. The admin group uses the auth middleware. Everything else uses the web middleware.

I'm having an issue where my AuthServiceProvider is querying my Permissions model in both groups... but I only want to query my Permissions model when a user requests access to a route within my admin group. Here is my AuthServiceProvider:

    <?php

    namespace App\Providers;

    use App\Models\Permission;
    use Illuminate\Support\Facades\Gate;
    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

    class AuthServiceProvider extends ServiceProvider
    {
     /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy'
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::before( function($user){
            if($user->isAdmin()){
                return true;
            }
        });

        foreach ($this->getPermissions() as $permission) {
            Gate::define($permission->name, function ($user) use ($permission) {
                return $user->hasRole($permission->roles);
            });
        }
    }

    protected function getPermissions()
    {
        return Permission::with('roles')->get();
    }

So in every request within my web middleware, my app is querying permissions for a user when it doesnt need to. There is no need for any permissions to get queried within my web middleware. So how do I tell my AuthServiceProvider to check permissions for only routes within my Auth group (or middleware)?

13 Feb
2 years ago

amcardwell left a reply on Polymorphic Relationship

@mirzap Okay great. So I set those up, but how would I set up the relationship on my Form model? I'm assuming from the above example that I should use the Submissions pivot table. So

I need to query the submissions FROM the Form model...


$form = Form::find(1);

$form->submissions;

11 Feb
2 years ago

amcardwell left a reply on Polymorphic Relationship

@swalker2 Thanks for the response... but I still dont understand. I tried that and I got an empty collection. Let me be more clear:

All I want is to be able to query form submissions based on the form I'm querying from. Like this:

// This selects the form called "ContactForm"
$form = Form::find(1);

// Then, I want to get all the submissions on the related "ContactFormData" model...
$data = $form->submissions->get();

or, another example:

// This selects the form called "Registration Form"
$form = Form::find(2);

// This time I need to get all of the submissions on the related "RegistrationData" model...
$data = $form->submissions->get();

It seems so simple. Thats what is so frustrating :P. I feel like my code is totally screwed. Could someone give me an example of how I should set up my relationships? I really would appreciate the help!!

10 Feb
2 years ago

amcardwell left a reply on Relationship Structure For A Form Builder?

For anyone curious as to how I managed this... see this post on Laracasts.

amcardwell left a reply on Fastest Way To Collect Data From Multiple Related Models?

UPDATE:

I learned that the way I wanted my database structured is based on the EAV (Entity-Attribute-Value) data model, which has documented performance issues when not set up correctly. I chose not to go that route since I wasnt ready to implement some complex structure to my schema. Instead I just created static tables, each holding all the combined records of tables "B" and "C". This is fine, but I will have to create a new related table/model for every new instance of table "A".

An EAV structure is not impossible, I learned, but there arent many packages made for laravel to handle a schema like this. If anyone else has a different opinion, feel free to add one.

amcardwell started a new conversation Polymorphic Relationship

I know... another question on polymorphic relationships. I've looked at every other topic on this but I just cant wrap my head around it. Pleeeease guys, I need some help!

I have many different forms on my website (with different attributes) that get filled out and the data gets posted to its own model based on the form. So I have a Form model that lists all of the forms with a name attribute, and another model based on that form that lists each "submission". So, for example, if I had the models ContactFormData and RegistrationFormData, my models would look like this:

// Form.php
- id
- name

// ContactFormsData.php
- id
- first_name
- last_name
- phone

// RegistrationFormData
- id
- name
- date_registered
- likes_candy

Im almost positive that this is a one-to-many polymorphic relation, but I cant for the life of me figure out how to setup my relationships in order to query the data based on the form. Another post I read suggested creating a pivot table to join a Form to its related Model, but no matter what I did, the result returned null whenever I made a query to that relation.

I added a Submissions table with the attributes form_id, submittable_id, and submittable_type. I set up the relationships as follows:

// Form.php
{
    $this->hasMany('App\Submission');
}

// Submission.php
public function form()
{
    $this->belongsTo('App\Form');
}

public function submittable()
{
    $this->morphTo();
}

// ContactFormsData.php
public function submissions()
{
    $this->morphMany('App\Submission', 'submittable');
}

// RegistrationsData.php
{
    $this->morphMany('App\Submission', 'submittable');
}

Once set up, every variation of this query returned null:

$form = Form::find(1);
$form->submissions

Please help!

03 Feb
2 years ago

amcardwell left a reply on Fastest Way To Collect Data From Multiple Related Models?

Okay. I think its the same. But even when I eager load the data... the request times out.

// my actual query $submission_data = Business::find($id)->with('submissions.data')->get();

amcardwell left a reply on Fastest Way To Collect Data From Multiple Related Models?

Thanks Snapey. Forgive my ignorance, but would you please show me how to loop through eager-loaded data to get the same result as in my example?

amcardwell started a new conversation Fastest Way To Collect Data From Multiple Related Models?

Suppose I have a model structure like this:

TableA has many TableB TableB has many TableC

I am trying to collect data for a DataTable. What I'm needing is to collect data from tables B and C starting at table A.

Here is the loop that works, but its rediculously slow when there are 1000+ records in table B:

$collect = [];
$a = TableA::find($id);

$i = 0;
foreach($a->tableB as $b_records){
    $collect[$i]['custom_key_one'] = $b_records->some_field_one;
    foreach($b_records->tableC as $c_records){
        $collect[$i][$c_records->name] = $c_records->value;
    }
    $collect[$i]['custom_key_two'] = $b_records->some_field_two;
    $i++;
}

This loop will return something like this:

Array:
    1 => [
            custom_key_one  => some_field_one
            name1           => value1
            name2           => value2
            name3           => value3
            custom_key_two  => some_field_two
        ],
    2 => [
            custom_key_one  => some_field_one
            name1           => value1
            ...
        ]

So if TableA has 1000 records of TableB, TableB would query TableC possibly 100k+ times. So its a no-go. Can someone provide a solution that maximizes performance and reduces the amount of queries?
19 Jan
2 years ago

amcardwell started a new conversation Relationship Structure For A Form Builder?

Here is my scenario:

I am creating a form builder for the admin portal of my website. A user can create a form using a jquery form builder plugin, which (once submitted) is then saved to my "Forms" table as html. There is a one-to-many relationship between a Form and a Business, respectively. A business "belongsTo" one form, while a form "hasMany" businesses.

My models:

Form
    - id
    - name
    - html
Business
    - id
    - form_id
    - name

I am trying to figure out how to store the submissions for each respected business. Since each business can have a different form (with different attributes), I cant just create a static submissions table. Also, because I could have 600+ businesses with different forms, I dont want to create a table for each business, obviously.

In a perfect world, I want to be able to query all the form submissions of any respective business. In a more perfect world, I would like the result of the query to return a collection as though I am querying a regular model. How do I achieve this?

15 Jan
2 years ago

amcardwell left a reply on Dynamic Form Generator Tips?

hmm... okay that makes things a bit clearer. the only thing is... I hate the fact that I would have to generate a new table for every new form... Also, do you also generate an associated model for each new table? How else do you make the columns fillable and set relations?

14 Jan
2 years ago

amcardwell started a new conversation Dynamic Form Generator Tips?

Hey guys. Can anyone give me some advice on the best way to use laravel to generate dynamic forms? Currently I am using a many-to-many relationship... but I KNOW there has to be a better, faster, and cleaner way... Here is my current model structure:

Form.php
- id
- name (string)

FormAttribute.php
- id
- form_id
- field_id
- attr_name (string)
- attr_type (int)       // Boolean, String, Integer, etc.
- attr_required (bool)

FormField.php
- id
- attribute_id
- value (text)

I dont have that many forms yet (< 5), but for flexibility's sake I know this needs to be improved. I would also like to avoid using JSON. I tried the suggestion of using MongoDB, but I could not figure out how to use it. I'm currently using MySQL on Laravel 5.2. Any tips/pointers?

16 Dec
2 years ago

amcardwell left a reply on Asynchronous Loading Of Form In Bootstrap Modal From External Script

I figured it out... I dont quite understand it yet, but I stumbled upon this https://github.com/krux/postscribe, which seems to make my code work. I created an empty div in my modal with an id of #formCode, then placed this line of code in my footer:

<script>
      $( function(){
          postscribe('#formCode', '<script src={!! $contact_form !!}><\/script>');
      });
</script>

$contact_form only contains the value of my "src" attribute.

Again, dont know how it works, just does. Maybe someone could elaborate

amcardwell started a new conversation Asynchronous Loading Of Form In Bootstrap Modal From External Script

Hey everyone. I have an issue loading a form in a bootstrap modal. I am using a service called Formstack to embed a form into my website. The embed code provided to me uses an external script to load the proper CSS, HTML, and JS into my page. The problem is that I am getting 10K+ warnings in my browser console once the page is loaded. All the warnings are the same. Each warning reads:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

Here is a link to that javascript file: [https://trustdale.formstack.com/forms/js.php/business_contact]

Looking at the external javascript, EVERY line begins with document.write. I dont know if it matters, but I am loading the form in a bootstrap modal. Also note that the form loads totally fine... unless I'm missing something. How would I load my form without all the errors?

21 Nov
2 years ago

amcardwell started a new conversation Dynamic Model Binding Based On Request Uri Inside Controller

I have an ImageController that is set up to create, update, and/or delete images in my database based on the request uri. I currently have 2 different models that accept image CRUD requests and store them.

What I want to know is... how do I, using one controller method ([email protected]), dynamically update a model based on the request uri? I want to do this WITHOUT writing multiple nested if statements like this:

public function upload(Request $request)
    {
    // get the file from POST request
        $file = $request->file;

        // set the file name
        $filename = uniqid() . "_" . $file->getClientOriginalName();

    if $request->is('admin/business'){
        // move the file to the correct location
            if(!file_exists('img/businesses')){
                    mkdir('img/businesses', 0777, true);
            }
            $file->move('img/businesses', $filename);
        Business::create

    // blah, blah, blah
    }

    if($request->is('admin/products'){
    // blah blah blah
    }

So how would I approach this?

13 Oct
2 years ago

amcardwell left a reply on Redirect For Specific Url Segment?

Thanks!! Both answers worked, but for me personally, I would rather do it on an application level since 1: I get nervous using server config files and 2: I can nest the redirects in a separate file to keep the clutter away. Anyway, question answered! Thanks :)

amcardwell started a new conversation Redirect For Specific Url Segment?

Hey all. I have a simple question... How do I create a 301 redirect that would change the FIRST segment of this url (/partners/):

    http://mysite.com/__partner__/atlanta/mypage

to the first segment of this url (/business/)?:

    http://mysite.com/__business__/atlanta/mypage

I know how to create a redirect for a specific full url, but I dont want to create one for every single page that is a descendant of the /partner/ segment. It would be great if this works (using the " * " wildcard)... but of course it doesnt:

Route::get('/partner/*', function() {
    return Redirect::to('/business/*');
});

So, how? Thanks!

11 Oct
2 years ago

amcardwell left a reply on Best 3rd Party Notification Service?

rollbar is okay, but I was wondering if there was something out there that integrates better with laravel... for example, like how blackfire integrates with laravel forge.

amcardwell started a new conversation Best 3rd Party Notification Service?

Hey everyone. I am using Rollbar, a paid stack-monitoring service, to inform me about errors in my production environment. I am at the point where I can switch from Rollbar if I want, and I was wondering what everyone else is using for their stack notifiers? It of course needs to be compatible with Laravel 5, and can integrate with Github. Any suggestions?

09 Oct
2 years ago

amcardwell started a new conversation Insert "dummy" Record Into Foreach Loop

Hey everyone. I have an array that lists every subcategory within a main category. There is a condition that each subcategory must have a business within the subcategory, and that business must be active. Now, in my blade, I iterate through my array and list each subcategory name with an anchor tag to link each subcategory to its respective page.

That being said - I want some of my categories to have a "dummy" subcategory that isnt a real subcategory, but links to another main category. For example, I have a main category called "Home Services" and another main category called "Cleaning Services". I want a "dummy" subcategory within "Home Services" called "Cleaning Services" that links to the main category "Cleaning Services". I have this set up already and its working, but the code is messy and I know there is a better way to do this. Im going to want to do this for more than one main category.

CategoryController.php

public function index($category_id)
    {
        $data['category']          = Category::with('children')->where('slug',$category_id)->first();

    if($data['category']->id == 25){
            $data['subcategories'] = $data['subcategories']->where(function($query){
                $query->whereHas('businesses', function($query) {
                    $query->where('status', 1);
                })
                ->orWhere('id', 485);
            })
            ->orderBy('name')
            ->get()
            ->toArray();
        } else {
            $data['subcategories'] = $data['subcategories']
                ->whereHas('businesses', function($query) {
                    $query->where('status', 1);
                })
                ->orderBy('name')
                ->get()
                ->toArray();
         }

category.blade.php

@foreach($subcategories as $subcategory)
                          <li>
                // Intercept "Cleaning Services" and redirect to main category
                                @if($subcategory['name'] == "Cleaning Services")
                                  <a href="{{URL::route('services::category_id', ['category_id' => 'cleaning-services']) }}"> {{ $subcategory['name'] }}</a>
                                @else
                                  <a href="{{URL::route('services::subcategory_id', ['category_id' => $category['slug'], 'subcategory_id' => $subcategory['slug']]) }}"> {{$subcategory['name']}}</a>
                                @endif
                          </li>
                        @endforeach

To make this work, I have to actually ADD a subcategory called "Cleaning Services" within my "Home Services" model. I'm sure there is a way to just manually insert a $subcategory['name'] into my array (and resort the array by $subcategory['name'] ), all within my foreach loop in my blade. I'm just lost. Can anyone give any suggestions?

06 Oct
2 years ago

amcardwell left a reply on Removing /index.php Completely

I just want to also thank @TiBian for his response. This has been an issue for me for a while and this fixed it!

For all the ubuntu newbies out there like myself, make sure you add this to your nginx config file for your site. My file was at /etc/nginx/sites-available/mysite.com

If you are using Forge, this is as easy as editing your Nginx Configuration file by opening up your "site", clicking the "Edit Files" button at the bottom, and clicking "Edit Nginx Configuration". I added the code from @TiBian towards the bottom of the file. Here is my complete configuration file:

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/default/before/*;

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name default;
    root /home/forge/default/public;

    # FORGE SSL (DO NOT REMOVE!)
    # ssl_certificate;
    # ssl_certificate_key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers '';
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DOT NOT REMOVE!)
    include forge-conf/default/server/*;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/default-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
    
    # Remove index.php$
    if ($request_uri ~* "^(.*/)index\.php$") {
        return 301 $1;
    }
    
    location \ {
        try_files $uri $uri/ /index.php?$query_string;
    
        # Remove from everywhere index.php
        if ($request_uri ~* "^(.*/)index\.php(/?)(.*)") {
            return 301 $1$3;
        }
    }
    
    
    # Remove trailing slash.
    if (!-d $request_filename) {
        rewrite ^/(.+)/$ /$1 permanent;
    }
    
    # Clean Double Slashes
    if ($request_uri ~* "\/\/") {
      rewrite ^/(.*) /$1 permanent;
    }

    location ~ /\.ht {
        deny all;
    }
}

# FORGE CONFIG (DOT NOT REMOVE!)
include forge-conf/default/after/*;

For me, the only change I had to make was to change the forward slash to a backslash to the right of "location":

 location \ {
        try_files $uri $uri/ /index.php?$query_string;

Anyway, I hope this helps.

24 Aug
2 years ago

amcardwell left a reply on Save Form Data Array To DB Using Eloquent

Worked like a charm! Thanks!

// dd($request->top_description)
"top_description" => array:5 [▼
    1 => "<p>123</p>"
    5 => "<p>456</p>"
    6 => "<p>789</p>"
    7 => "<p>abc</p>"
    8 => "<p>def</p>"
  ]

// My foreach loop
foreach($request->top_description as $id => $value){
            $lm = LandingMarket::findOrFail($id);
            $lm->top_description = $value;
            $lm->save();
        }

amcardwell left a reply on Save Form Data Array To DB Using Eloquent

Great! So the above answer worked to set the key of each value. To help, here is the layout of my models:

Landing
    - id // unique(primary)

LandingMarket
    - id  // unique(primary)
    - landing_id
    - market_id
    - top_description

So I've set the key to the primary ID of my LandingMarket table, like this: LandingMarket->id = LandingMarket->top_description

Now that I have the correct array of inputs with their associated keys, how do I save them to the database? Again, I need to UPDATE the records.

dd($request->all());

array:6 [▼
  "_method" => "PUT"
  "_token" => "zpXFZZ10JFfsVOz84KIwJePb5jw4ZIi2YVGhJi6q"
  "top_description" => array:5 [▼
    1 => "<p>123</p>"
    5 => "<p>456</p>"
    6 => "<p>789</p>"
    7 => "<p>abc</p>"
    8 => "<p>def</p>"
  ]

amcardwell left a reply on Save Form Data Array To DB Using Eloquent

Thanks. So, Ive set the textarea name to an array, and in my controller, I've dumped $request->top_description, which correctly lists my array. Now how do I save each value to my LandingMarket model? I can forsee a problem where it wouldnt work because I havent set a unique key to my values... though I dont know how I would do that. Here is my dd:

array:5 [▼
  0 => "<p>asd</p>"
  1 => "<p>123</p>"
  2 => "<p>asd</p>"
  3 => "<p>asd</p>"
  4 => "<p>asd</p>"
]

Where do I go from here?

amcardwell started a new conversation Save Form Data Array To DB Using Eloquent

Hey all,

I am having some issues submitting form data to my DB using eloquent. In my blade, I have a foreach loop that display's my form data for user input:

@foreach($markets as $market)
              <div id="fragment-{{$i++}}">
                <?=Form::textarea('top_description', $market->top_description, ['rows' => '15', 'class' => 'mce', 'name' => 'top_description[]']);?>
              </div>
@endforeach

Once the form gets submitted, each input in this loop is stored in an array ('top_description[]'). Now, what I need to do is iterate through each $request->top_description[] and store the values in the columns I specify. Here is my controller update method:

public function update($id, Request $request)
{
    $landing                        = Landing::findOrFail($id);                 // Getting the id of the Landing model
        $landing_markets[]                = LandingMarket::where('landing_id', $landing->id)->get();    // I need to update a record on THESE rows
        foreach($request->top_description as $top_description){     // Iterating through input values for $top_description
            $landing_markets[] = $top_description;      // trying to store each input value to its associated 
        }
        foreach($landing_markets as $landing_market){
            $landing_market->save();
        }
.....blah blah blah....

So, I need to save each $request->top_description value to its respective row in my LandingMarket model. How do I do this?

14 Aug
2 years ago

amcardwell left a reply on Link To Named Route With Optional Parameter Set FALSE

That's what I needed to know. Thanks

amcardwell started a new conversation Link To Named Route With Optional Parameter Set FALSE

Hey everyone. I need to directly link to a named route with an optional parameter automatically set to NULL. This is what my url looks like when I try to do this: http://mysite.com/services//category_id. It needs to look like http://mysite.com/services/category_id. Here is my route:

// routes.php
Route::group(['prefix' => 'services', 'as' => 'services::'], function () {
    Route::get('{market?}/{category_id}', [
        'as' => 'category_id',
        'uses' => '[email protected]'
    ]);

I'm trying to link to the route above WITHOUT {market?}. Here is what I've tried:

<a href="{{ route('services::category_id', ['category_id' => $category['slug']])}}">

<a href="{{ route('services::category_id', ['category_id' => $category['slug'], 'market' => false])}}">

<a href="{{ route('services::category_id', ['category_id' => $category['slug'], 'market' => null])}}">

Again, I need it to link to this: http://mysite.com/services/category_id

Can anyone help me out?

12 Aug
2 years ago

amcardwell left a reply on Help Me Shorten A Query Please!

@lindstrom I am querying businesses based on user input either from the zipcode field ($request->zip) or from the city field ($request->city). If both fields are sent with data... I only use the $request->zip data.

@jimmck I am using a MaxMind geoip database that ships with every zipcode in every country. I'm not too familiar with it, but I'm worried about removing records outside the US, since the database is scheduled to update through Maxmind servers every month.

amcardwell started a new conversation Help Me Shorten A Query Please!

Could I please get some suggestions on how to shorten this query in order to get results faster? Its taking forever to perform. Mainly because my Zipcode table is so large (nearly 200K records).

public function search(Request $request, $category_id, $subcategory_id)
    {
        $data['category_id']       = $category_id;
        $data['subcategory_id']    = $subcategory_id;
        $data['maincategory']      = Category::where('slug', $category_id)->first();
        $data['subcategory']       = Category::where('slug', $subcategory_id)->first();

        $data['zip'] = $request->zip;
        $data['city'] = $request->city;


        $search = Business::distinct('businesses.id')
            ->join('business_zipcodes', 'business_zipcodes.business_id', '=', 'businesses.id')
            ->whereHas('categories', function ($query) use ($data) {
                $query->where('categories.id', $data['subcategory']->id);
            });
            if("" != $data['zip'] && isset($data['zip'])) {
                $search->whereIn('business_zipcodes.zipcode', [$data['zip'],'99999']);
            }elseif("" != $data['city'] && isset($data['city'])){
                $search->where('business_zipcodes.city', 'like', $data['city']);
            }else{
                return redirect()->back()-with('error', 'Please enter your location');
            }
            $search ->where('business_zipcodes.order', '>', 0)
                    ->where('businesses.status', '1')
                    ->groupBy('businesses.id')
                    ->orderBy('order', 'asc');

        $data['businesses'] = $search->get();
10 Aug
2 years ago

amcardwell started a new conversation From View To->controller Back To->view With Dynamic Url

Hey everyone. I have a search form field within a view at a dynamic url. How do I get the search form to perform a GET query from my controller BACK to my view, while keeping the same url? Here are my routes:

// Landing Pages
Route::group(['prefix' => 'services', 'as' => 'services::'], function () {
    Route::get('{category_id}', [
        'as' => 'category_id',
        'uses' => '[email protected]'
    ]);
    Route::get('{category_id}/{subcategory_id}', [
        'as' => 'subcategory_id',
        'uses' => '[email protected]'
    ]);
    Route::get('{category_id}/{subcategory_id}/{search}', [
        'as' => 'search',
        'uses' => '[email protected]'
    ]);
    Route::post('{category_id}/{subcategory_id}', [
        'as' => 'result',
        'uses' => '[email protected]'
    ]);
});

Here is my view:

<div class="result-search">
  <div class="row">
    {!! Form::open(array('method' => 'get', 'route' => 'services::search', 'class' => 'form-inline')) !!}
            <span class="span-in"> Change your location: </span>
            <label class="sr-only" for="address">Your Location </label>
            <input type="text" name="address" class="form-control" placeholder="City or Zipcode" value="{{ str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($city)))) }}, {{ $zip }}" onclick="this.focus();this.select()">
            <div aria-label="Search" role="group" class="btn-group btn-search pull-right" style>
              <button class="btn btn-default" id="text" type="submit">Search</button>
              <button class="btn btn-default btn-right" type="submit"><i class="icn-magni"></i></button>
            </div>
    {!! Form::close() !!}
  </div>
</div>

Here is what I would like my site to do. If I am at this url: "http://mysite.com/services/plumbing/install" and I perform a search (lets say, with 'Atlanta'), I want the results to come up with an updated url of this: "http://mysite.com/services/plumbing/install/search?address=Atlanta". Can anyone help?

08 Aug
2 years ago

amcardwell started a new conversation Show Categories->that Have Children->where Children Has Products

Hey everyone. I'm having issues checking existence of a distant relationship. Here is my relationship structure:

My frontend structure: Category->SubCategory->Business

My backend relationships:

My Models:

Categories
-- id
-- name
-- slug
-- [parent_id]      // Main categories have a parent_id of 0, SubCategories have a parent_id of respective parent id

Businesses
-- id
-- name
-- [market_id]

My relationships:

/// Many-to-many
Category->belongsToMany->businesses
Business->belongsToMany->categories

Basically, what I want to do is show a list of categories where 'parent_id' = 0 ONLY IF:

  1. Category has children
  2. Those children have businesses
  3. Those businesses have a 'market_id' of $market->id (which is already defined).

I have a getChildrenAttribute() method in my Categories model, but I'm not sure how to use it...:

    public function getChildrenAttribute()
    {
        $children = Category::where('parent_id', $this->id)->orderBy('name')->get();
        return $children;
    }

Can anyone help me out?

05 Aug
2 years ago

amcardwell left a reply on JQuery: Not All Show/hide Toggles Are Working?

Okay.. i changed that... but it still doesnt work. Here is a jsfiddle.

https://jsfiddle.net/qdcvv97s/1/

Notice that all of the "show more" buttons work except for the one on "business services" AND "financial services".

04 Aug
2 years ago

amcardwell started a new conversation JQuery: Not All Show/hide Toggles Are Working?

Can someone please tell me why not all of my lists are toggling using javascript? Some of them are toggling... but some of them arent. I am using Laravel Eloquent to generate lists of categories with nested subcategories. Here is my code:

@extends('page.main_template')
@section('content')
   
   <div class="container heading">
            <h1>All Categories</h1>
   </div>
    
    <hr style="border-top: 1px solid #96351A; width: 100%;">

    <div class="container category-view-all">
        <?php $counter = 1; ?>
            <div class="row">
                @foreach($mainCategories as $category)
                    <div class="col-xs-12 col-md-4">
                        <div class="panel panel-default">
                            <div class="panel-heading">
                                <h2>{{ strtoupper($category->name) }}</h2>
                            </div>
                            <div class="panel-body">
                                <ul id="allcats">
                                    @foreach($category->children as $subcategory)
                                        <li><a href="{{URL::to('category/'.$category['slug'].'/'.$subcategory['slug'])}}">{{ $subcategory->name }}</a></li>
                                    @endforeach
                                </ul>
                            </div>
                        </div>
                    </div>
                    <?php 
                        $counter++;
                        if($counter % 3 == 1){
                            echo '<div class="clearfix"></div>
                                    </div>
                                    <div class="row">';
                        };
                    ?>
                @endforeach
        </div>
   </div>
@stop

@section('js')
    @parent
        <script>
            $('ul#allcats').each(function(){
              var max = 6
                if ($(this).find("li").length > max) {
                    $(this)
                      .find('li:gt('+max+')')
                      .hide()
                      .end()
                      .append('<li class="accordian"><span class="show-button" id="show_more"><i class="glyphicon glyphicon-plus"></i> Show More</span></li>');
                            $('.accordian').click( function(){
                            $(this).siblings(':gt('+max+')').toggle();
                            if ( $('#show_less').length) {
                                $(this).html('<span class="show-button" id="show_less"><i class="glyphicon glyphicon-minus"></i> Show Less</span>');
                            } else {
                                $(this).html('<span class="show-button" id="show_more"><i class="glyphicon glyphicon-plus"></i> Show More</span>');
                            };
                            });
                }
            });
        </script>
@stop
02 Aug
2 years ago

amcardwell left a reply on MethodNotAllowedHttpException When Using JQuery

Great! That worked perfectly. For everyone else, here is my new form:

<div class="modal fade in" id="zipmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog">
            <?php echo Form::open(array('url' => 'setzip', 'class' => 'modal-content')); ?>
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Input Your Zip</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input id="changezip" type="text" class="form-control" name="zipcode" >
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
                <input type="hidden" id="next_url" name="next_url" class="form-control" value="" >
            </form>
        </div>
    </div>

and my setzip() modal in my PageController:

public function setZip(Request $request)
    {
        if (!empty($request->zipcode) and is_numeric($request->zipcode)) {
            Zip::setZip($request->zipcode);
        }
        if(isset($request->next_url)) {
            return redirect($request->next_url);
        }
            return redirect('');
    }

amcardwell left a reply on MethodNotAllowedHttpException When Using JQuery

So, it looks like its trying to POST to the url bound to the submit button:

Headers:
Request URL:http://mysite.dev:8000/services/atlanta/air-conditioning-and-heating
Request Method:POST
Status Code:405 Method Not Allowed
Remote Address:127.0.0.1:8000

How do I get the form to POST to the correct URL (setzip), while also taking me to the requested url linked to the submit button via jQuery? Again, here is my form...

<div class="modal fade in" id="zipmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog">
            <?php echo Form::open(array('url' => 'setzip', 'class' => 'modal-content', 'id' => 'zipcode-form')); ?>
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Input Your Zip</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input id="changezip" type="text" class="form-control" name="zipcode" >
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </form>
        </div>
    </div>

and my route:

Route::post('setzip', '[email protected]');

and the setzip() method in my PageController:

public function setZip(Request $request)
{
        if (!empty($request->zipcode) and is_numeric($request->zipcode)) {
            Zip::setZip($request->zipcode);
        }

        return redirect('');
}

Finally, here is my setZip() method in my Zip class:

public static function setZip($zipcode){
    Session::put('zip', $zipcode);
    return $zipcode;
}

amcardwell started a new conversation MethodNotAllowedHttpException When Using JQuery

Hey all. I have a question regarding the use of jQuery in my form. I am receiving this error:

MethodNotAllowedHttpException in RouteCollection.php line 218:
in RouteCollection.php line 218
at RouteCollection->methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php line 205
at RouteCollection->getRouteForMethods(object(Request), array('GET', 'HEAD')) in RouteCollection.php line 158
at RouteCollection->match(object(Request)) in Router.php line 750
at Router->findRoute(object(Request)) in Router.php line 659
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Debugbar.php line 49
at Debugbar->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Debugbar), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in RedirectToWWW.php line 29
at RedirectToWWW->handle(object(Request), object(Closure))
at call_user_func_array(array(object(RedirectToWWW), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in Redirect301.php line 39
at Redirect301->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Redirect301), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 54

I have pinpointed the root of the issue, which has to do with my jQuery script. To be honest, I really dont know much about jQuery... so forgive me if I dont make sense in some way.

I have a foreach loop that is generating some links for me. Once a link is clicked, a bootstrap modal pops up that asks the user to enter their zipcode. Once the user does that and then clicks submit, the input is posted to the session, the link that the user clicked on originally is followed. To make this work, I had to use jQuery to pass the original link url into the modal:

<script>
        jQuery(document).ready(function(){
        jQuery('a[data-toggle="modal"]').each(function(){
        var item = jQuery(this);

        item.on('click', function(e){
            e.preventDefault();
            var url = jQuery(this).data('url');

            jQuery('#zipcode-form').attr('action', url);
        });
    });
});
      </script>

Here is my foreach loop in my blade:

<?php foreach ($categories_1 as $category): ?>
                <li><a data-toggle="modal" data-target="#zipmodal" href="#" data-url="{{ URL::to('services/atlanta/'.$category['slug'])}}"><span><img alt="" src="img/icons/{{$category['icon']}}" class="img-responsive"></span> {{$category['name']}}</a></li>
              <?php endforeach;?>

Here is my modal:

<div class="modal fade in" id="zipmodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog">
            <?php echo Form::open(array('url' => 'setzip', 'class' => 'modal-content', 'id' => 'zipcode-form')); ?>
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Input Your Zip</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <input id="changezip" type="text" class="form-control" name="zipcode" >
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-success">Submit</button>
                </div>
            </form>
        </div>
    </div>

If I were to remove the id "zipcode-form" from the modal input (and effectively disconnect my jQuery handler), the request would get sent without any error... but I am not directed to the correct url. Can someone let me know what I need to do to get this working?

26 Jul
2 years ago

amcardwell left a reply on Link To URL -> Lightbox Request Input -> Redirect To Original Url

Does anyone have any suggestions? I can provide more info if needed....

25 Jul
2 years ago

amcardwell left a reply on Link To URL -> Lightbox Request Input -> Redirect To Original Url

Sorry. When I click the link, the featherlight box opens... I type in a new zipcode and hit submit, and it redirects me back to the home page I was previously on when I clicked the link. The new zipcode gets set, but like I said it doesnt take me to the url I want it to.

amcardwell started a new conversation Link To URL -> Lightbox Request Input -> Redirect To Original Url

Hey all. I have a very simple question for once :). I have a page with a list of links that need to go to a specific url. Once the user clicks on a link, and before the page changes and the link loads, I have a lightbox that comes up with a form input requesting the user's location. Once the user enters their location, I need the form submit button to direct them to the url that was originally requested when clicking the link. Here is my setup:

home.blade.php

<?php foreach ($categories_1 as $category): ?>
                <li><a href="{{ URL::to('atlanta/'.$category['slug'])}}" data-featherlight="#ziplightbox" onclick="document.getElementById('changezip').focus()"><span><img alt="" src="img/icons/{{$category['icon']}}" class="img-responsive"></span> {{$category['name']}}</a></li>
              <?php endforeach;?>

zip.blade.php:

<div id="ziplightbox">
    <?php echo Form::open(array('url' => 'setzip')); ?>
      <label>Please enter your zip code.</label>
      <div class="clearfix"></div>
      <input id="changezip" type="text" class="form-control" name="zipcode" placeholder="{{$zip}}" style="max-width:50%; float:left;" autofocus>
      <div aria-label="Basic example" role="group" class="btn-group"  style="max-width:45%; float:right;">
        <a href="{{URL::to('atlanta/'.$category['slug'])}}"><button class="btn btn-default" type="submit">find pros</button>    //  <-  ??????
        <button class="btn btn-default btn-right" type="button"><i class="fa fa-search"></i></button></a>
      </div>
  </form>
</div>

Once the submit button is clicked, the zipcode POST's to this method.

PageController.php:

public function setZip(Request $request)
    {
        if (!empty($request->zipcode) and is_numeric($request->zipcode)) {
            Zip::setZip($request->zipcode);
        }

        return redirect('');
    }

As you can see, the link is dynamic. In this case, I need to redirect to this url after submitting the form: {{ URL::to('atlanta/'.$category['slug'])}}

How do I do that? Thanks for the help!

12 Jul
2 years ago

amcardwell left a reply on Change Route Based On Location

Ah I forgot to mention that.

Routes.php

// Zipcode
Route::post('setzip', '[email protected]');

PageController.php

/**
     * Set the current zipcode.
     *
     * @param  Request $request
     * @return \Illuminate\Http\Response
     */
    public function setZip(Request $request)
    {
        if (!empty($request->zipcode) and is_numeric($request->zipcode)) {
            Zip::setZip($request->zipcode);
        }

        return redirect()->back();
    }

So how do I set the prefix to the current market? Do I do this in my routes file or do I route it somewhere else? Preferably, I would like to abandon my PageController for handling my market routes since I'm way beyond creating static pages. Forgive me, I'm no expert at this...

amcardwell left a reply on Change Route Based On Location

I'm assuming a fix would require a dynamic route prefix...? but I'm kindof lost on how to go about that while keeping my PageController "intact".

amcardwell left a reply on Change Route Based On Location

No, for SEO purposes, we need to display the current market in the url.

amcardwell started a new conversation Change Route Based On Location

Hey everyone. I need some suggestions on how to update a url segment based on the current state the site visitor is in.

For example, if a site visitor is in the 30092 zip code (an Atlanta zipcode), the url is 'http://mysite.com/atlanta', and the content of the site displays information related to the Atlanta market. If the site visitor changes their zipcode to 37221 (a Nashville zipcode), the site redirects them to 'http://mysite.com/nashville', and displays information relevant to the Nashville market.

Here is how it works currently: I have a PageController that handles the redirects based on the visitors current state. The zipcode->state relationship is handled by a geoip database table -- I have set up a custom class to get the current zipcode and return it to my app: Zip::getZip(). Here are my routes and controller methods, in order from the initial zipcode request, to the returned view (I know its not clean):

Routes.php Route::get('/', '[email protected]');

PageController.php

public function index()
    {
        $end_date = Carbon::now()->tomorrow();

        $current_zip = Zip::getZip();       // Request current zipcode
        $zip_state = Zipcode::where('zip',  $current_zip)->value('state');          // Return state based on current zipcode

// We only have 5 markets that display information. If zipcode is outside one of the 5 markets below, default to the 'atlanta' market.
        if ($zip_state == 'GA') {
            return redirect()->route('atlanta');        // 
        } else if ($zip_state == 'TX') {
            return redirect()->route('dallasftworth');
        } else if ($zip_state == 'TN') {
            return redirect()->route('nashville');
        } else if ($zip_state == 'AL') {
            return redirect()->route('birmingham');
        } else if ($zip_state == 'FL') {
            return redirect()->route('tampa');
        } else {
            return redirect()->route('atlanta');
        }
    }

Routes.php

// Market pages
Route::get('atlanta', ['as' => 'atlanta', 'uses' => '[email protected]']);
Route::get('dallasftworth', ['as' => 'dallasftworth', 'uses' => '[email protected]']);
Route::get('birmingham', ['as' => 'birmingham', 'uses' => '[email protected]']);
Route::get('nashville', ['as' => 'nashville', 'uses' => '[email protected]']);
Route::get('tampa', ['as' => 'tampa', 'uses' => '[email protected]']);

PageController.php (only showing the 'Atlanta' method... they are all basically the same for each market)

/**
     * Display the Atlanta page.
     *
     * @return \Illuminate\Http\Response
     */
    public function atlanta()
    {
        $backgrounds = [
            'default' => 'img/home-bg/atlanta-skyline.jpg',
            'GA'      => 'img/home-bg/atlanta-skyline-over-water.jpg',
        ];
        $end_date = Carbon::now()->tomorrow();

        $current_zip = Zip::getZip();
        $zip_state   = Zipcode::where('zip', $current_zip)->value('state');

        $deal = Deal::with('business')
            ->orderBy('date_active', 'desc')
            ->where('date_active', '<', $end_date);

        $deal = $deal->where('state', 'GA');
        $deal = $deal->first();

        $data = [
            'home_zip_img' => array_key_exists($zip_state, $backgrounds) ? $backgrounds[$zip_state] : $backgrounds['default'],
            'categories'   => Category::orderBy('name')->where('parent_id', 0)->get()->toArray(),
            'ac_cats'      => Category::orderBy('name')->where('parent_id', 1)->get()->toArray(),
            'deal'         => $deal,
        ];

        return view('page.atlanta', $data);

    }

Here is my question... I am wanting to create a new controller for a different section of the site, but I want to keep the option to change the zipcode and: 1) update the url segment to show the current market and 2) update the page to show content relevant to that market. I want to do this without having to recreate the 'route->redirect()->route->method->view' scenario (disaster) like the above. Can someone help me as I think my brain capacity has reached its limit :(.

amcardwell left a reply on AuthController Does Not Exist

Ahh clearing the cache fixed it. Thanks!

amcardwell left a reply on AuthController Does Not Exist

Route::controllers([
    'auth'     => 'Admin\Auth\AuthController',
    'password' => 'Admin\Auth\PasswordController',
]);
Route::get('auth/logout', 'Admin\Auth\[email protected]');

Still not working. Your right, that was a problem but the issue is that my app is not looking in the right namespace for AuthController (see my above post)