trevorpan

trevorpan

Member Since 10 Months Ago

Experience Points 35,730
Experience Level 8

4,270 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 335
Lessons
Completed
Best Reply Awards 0
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.

15 Jul
16 hours ago

trevorpan left a reply on Forge: Script For Adding Column To Production Database Table

Thank you, the next thing I need to go through is the new testing server series of laracasts to test out that stuff.

Going to read up on all those scripts some more. Appreciated!

trevorpan left a reply on Forge: Script For Adding Column To Production Database Table

Ok, it's one of those things - just want to be SURE that nothing screws up. It seems like eventually some really cool things could be done with the forge script, just getting my feet wet. Thank you!

trevorpan started a new conversation Forge: Script For Adding Column To Production Database Table

Was reading this post below and feel I have a good understanding of the process of creating a new migration which then adds a column to an existing table. I know I'll have to test the nullable or default values for previous users, e.g. to ensure there are no errors.

https://laracasts.com/discuss/channels/laravel/what-is-the-typical-process-to-add-a-field-to-a-production-database-without-loosing-existing-data

This doc: https://laravel.com/docs/5.8/migrations#columns states you need to add this dependency composer require doctrine/dbal. I've done that locally.

When I get ready to push this to production does the below script cover this dbal?

It seems like a yes, as it's in the composer.json which would be pushed to master, but it's not something I want to get wrong.

cd /home/forge/bidbird.co
git pull origin master
composer install --no-interaction --prefer-dist --optimize-autoloader
php artisan config:cache -q --no-interaction
php artisan route:cache
npm run production
echo "" | sudo -S service php7.1-fpm reload

if [ -f artisan ]
then
    php artisan migrate --force
fi

Thank you for any tips..

28 Jun
2 weeks ago

trevorpan left a reply on After Updating To Vue 2.6.10 Components Not Rendering

@BOBBYBOUWMANN - ok cool I'll get that straightened out.

Yea, I've seen a number of videos using cdn, and then read a random article somewhere else or visit a package and it has an npm script. So, as a beginner a number of things are catawompus!

Going to look at the stripe.component a little more closely - that may be part of the problem.

trevorpan left a reply on After Updating To Vue 2.6.10 Components Not Rendering

@BOBBYBOUWMANN - Alright! Just got that cleaned up. Every tip is appreciated. Slowly making progress. Thank you.

I researched a bit <scoped slots> as the countdown timer uses them; I thought possibly that was causing an issue.

However the vue.js notes say this has been deprecated but not removed. So I don't think that's contributing to the non-rendered components.

https://vuejs.org/v2/guide/components-slots.html

Wondering if referencing cdn's causes a conflict? Would you delete the duplicates below? Do you use one method over the other? What's your pro-tip?

//master.blade.php
<script src="https://js.stripe.com/v3/"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="{{ asset('js/vendor.js') }}"></script>
<script src="{{ asset('js/app.js') }}"></script>

trevorpan left a reply on After Updating To Vue 2.6.10 Components Not Rendering

@BOBBYBOUWMANN - Hi, thank you. Not sure how the vue-loaders was added in both places; I don't generally manually do this. It is best to allow the npm scripts handle these?

How do you know which dependency is the proper place for a package?

When I'm working locally I run the npm run dev then npm run watch. Can that change the package.json file around?

trevorpan started a new conversation After Updating To Vue 2.6.10 Components Not Rendering

Hi,

I've been trying to figure out all morning why these components are no longer rendering.

Here's a few things I've done composer update npm install

There were a few dependencies that needed updating, and I did that. I can't find any missing dependencies for the portal-vue. I've gone back through the megamenu, and modal videos on laracasts to try and see if something's amiss.

The Vue developer add-in in Chrome does not register any components. The package.json shows:

"devDependencies": {
    ...
    "vue": "^2.6.10",
        "vue-loader": "^15.6.1",
        "vue-loaders": "^2.0.0",
        "vue-template-compiler": "^2.6.10",
        "vueify": "^9.4.1",
    ...
},
    "dependencies": {
    ...
        "portal-vue": "^2.1.5",
        "vue-axios": "^2.1.4",
        "vue-loaders": "^2.0.0"
    }

Here's the app.js file. Any ideas of what's going on?

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

import Vue from 'vue';

import SponsorModal from './plugins/sponsormodal/SponsorModal';

import PortalVue from 'portal-vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
import jquery from 'jquery';

import Countdown from './components/Countdown';
import LocationDropdown from './components/LocationDropdown';
import ReserveBid from './components/ReserveBid';


window.Vue = Vue;
window.Vue = require('vue');
window.$ = jquery;
window.jquery = jquery;

Vue.component('countdown', Countdown);
Vue.component('locationdropdown', LocationDropdown);
Vue.component('reservebid', ReserveBid);
 
Vue.use(VueAxios, axios);
Vue.use(PortalVue);
Vue.use(SponsorModal);

require('./bootstrap');

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */
const compiler = require('vue-template-compiler');
const files = require.context('./', true, /\.vue$/i)
files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

const app = new Vue({
    el: '#app'
});

Usage: Vue.config.devtools = true;
16 Jun
4 weeks ago

trevorpan started a new conversation New Stripe: Return /success Or /cancel From Controller Or Vue Component

Hello ~

Have been working through the Accept Payments video series. On April 16, 2019 Stripe introduced a newer version of checkout.

The store() method below is straight from stripe's upgrade docs.

https://stripe.com/docs/payments/checkout/migration#client-products

Is the success page, and cancel page supposed to be routed from the Vue component, or from the controller? I searched multiple views in Laracasts.com and it seems like having one view for one controller is the way to go.

The below code does return a success page.

class ReservesController extends Controller
{

    public function store()
    {

        $session = \Stripe\Checkout\Session::create([
          'payment_method_types' => ['card'],
          'line_items' => [[
            'name' => 'Bid Reserve Fee',
            'description' => ' Bid Reserve Fee',
            'amount' => 500,
            'currency' => 'usd',
            'quantity' => 1,
          ]],
          'success_url' => 'https://bidbird.co/success',
          'cancel_url' => 'https://bidbird.co/cancel',
        ]);

        
            return view('payments.success', compact('session')); 
       
    }
}
04 Jun
1 month ago

trevorpan started a new conversation Modals And Custom Vue Plugins (video) Model:hover Issue With Multiple Components

Hi,

https://laracasts.com/series/practical-vue-components/episodes/4

This is a sweet video and technique if you haven't watched it yet.

Have managed to get the SponsorModal.vue working fine. I'm using it for sponsor logos on the homepage. The idea is to popup a modal for paying sponsors - they can have a homepage away from home! Because there's multiple logos (10) when you hover over one logo area, say sponsor6 it hovers fine (changes to light blue from a light grey gradient) but after the modal pops up the hovered logo sponsor6 area goes away, and the first logo sponsor1 shows the hover.

I think this is because that's the first instance of the vue component. It's kind of funny really, but if the selected logo can stay selected that'd ideal.

Any ideas?

//blade - just a few divs to test

<div class="homepage">

    <div class="sponsorleft">

        <div class="sponsor1">

             Interested in promoting <a href="#sponsor-modal"><b>Your Logo</b></a>?

            <sponsormodal name="sponsor-modal"></sponsormodal>

        </div>

        <div class="sponsor2">

             Interested in promoting <a href="#sponsor-modal"><b>Your Logo</b></a>?

            <sponsormodal name="sponsor-modal"></sponsormodal>

        </div>

Text here....

    <div class="sponsorright">

        <div class="sponsor6">

             Interested in promoting <a href="#sponsor-modal"><b>Your Logo</b></a>?

            <sponsormodal name="sponsor-modal"></sponsormodal>

        </div>

        <div class="sponsor7">

             Interested in promoting <a href="#sponsor-modal"><b>Your Logo</b></a>?

            <sponsormodal name="sponsor-modal"></sponsormodal>

        </div>
</div>
</div>
//app.css

// Sponsors left

.sponsorleft {
  grid-row: 1 / 8;
  grid-column: 1 / 2;
  display: grid;
  grid-template-rows: repeat(5, 150px);
  grid-row-gap: 10px;
  // background: blue;
}

.sponsor1 {
  grid-row: 1 / 2;
  grid-column: 1 / 2;
  text-align: center;
  padding-top: 35px;
  background: linear-gradient(180deg, #eee 0, #e9e9e9);
  border-radius: 50%;
}

.sponsor1:hover {
  background: lightblue;
}

.sponsor2 {
  grid-row: 2 / 3;
  grid-column: 1 / 2;
  text-align: center;
  padding-top: 35px;
  background: linear-gradient(180deg, #eee 0, #e9e9e9);
  border-radius: 50%;
}

.sponsor2:hover {
  background: lightblue;
}

//Sponsors right

.sponsorright {
  display: grid;
  grid-row: 1 / 8;
  grid-column: 8 / 9;
  display: grid;
  grid-template-rows: repeat(5, 150px);
  grid-row-gap: 10px;
  // background: red;
}

.sponsor6 {
  grid-row: 1 / 2;
  grid-column: 3 / 4;
  text-align: center;
  padding-top: 35px;
  background: linear-gradient(180deg, #eee 0, #e9e9e9);
  border-radius: 50%;
}

.sponsor6:hover {
  background: lightblue;
}

.sponsor7 {
  grid-row: 2 / 3;
  grid-column: 3 / 4;
  text-align: center;
  padding-top: 35px;
  background: linear-gradient(180deg, #eee 0, #e9e9e9);
  border-radius: 50%;
}

.sponsor7:hover {
  background: lightblue;
}
//SponsorModal.vue
<template>
    <div :id="name" class="overlay">

        <a href="#" class="sponsor"></a>

        <div class="modal">

            <slot>
              
                <div class="sponsorheading">
                    <b>Sponsorships Available</b>
                </div>

                <div class="sponsormodal-left-text1">
                    text heading
                </div>

                <div class="sponsormodal-center-text1">
                    
                    text
                </div>

                <div class="sponsormodal-left-text2">
                    text heading
                </div>

                <div class="sponsormodal-center-text2">
                        text
                        
                        <br><br>

                        text

                        <br><br>

                        text
                  
                </div>
            </slot>

            <a href="#" class="close"><span style='font-size:40px;'>&times;</span></a>
        </div>

    </div>

</template>

<script>
    export default {
        props: ['name']
    }
</script>

<style>
    .overlay {
        visibility: hidden;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, .4);
        transition: opacity 3s;
        opacity: 0;
    }

    .overlay:target {
        visibility: visible;
        opacity: 1;
    }

    .modal {
        position: relative;
        width: 1000px;
        height: 750px;
        max-width: 80%;
        background: white;
        border-radius: 4px;
        padding: 10px 20px;
        box-shadow: 0 5px 10px rgba(36, 37, 38, 0.08);
    }

    .modal .close {
        position: absolute;
        top: 20px;
        right: 20px;
        color: grey;
        text-decoration: none;
    }

    .overlay .sponsor {
        position: absolute;
        width: 100%;
        height: 100%;
    }

</style>
31 May
1 month ago

trevorpan left a reply on How To Hook Additional Pagination Symbols Into Paginator

@JLRDW - Hi - thank you, I found this: https://laracasts.com/discuss/channels/guides/paginator-another-episode that helped on the <a href , kept trying different routes that would give 404.

<div class="leftarrow"> 
    <a href="{{ $jobs->previousPageUrl() }}">❰</a>
</div> 

<div class="rightarrow">
<a href="{{ $jobs->nextPageUrl() }}">❱</a>  
</div>

@snapey , thank you for the link. I'd read those before but didn't understand them. I kept thinking $results - what $results, but now understand it's the $jobs the controller is passing..

moving ahead! Thank you

trevorpan started a new conversation How To Hook Additional Pagination Symbols Into Paginator

Hi ~

I've found a number of posts on how to customize the out of the box pagination but want to see if you have created additional symbols for pagination.

The goal is to leave the basic ❰ 1 2 3 ❱the bottom of page results but have the below symbols roughly mid page.

Have you done this?

<div class="leftarrow">❰</div> 
<div class="rightarrow">❱</div>

Thank you `

23 May
1 month ago

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

@TRAY2 - Ok, thank you very much. I tend to have a orderly desire for all the records to be sequential but am going to have to let go!

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

@TRAY2 - Ok, I think I have it.

class CreateStatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('states', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('state');
        });
    }
class CreateCitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('city'); 
            $table->unsignedBigInteger('state_id');
            $table->foreign('state_id')->references('id')->on('states');
            $table->timestamps();
        });
    }
class CreateCityCountyPivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('city_county', function(Blueprint $table)
        {
            $table->primary(['city_id', 'county_id']);
            $table->unsignedBigInteger('city_id')->unsigned()->index();
            $table->foreign('city_id')->references('id')->on('cities');
            $table->unsignedBigInteger('county_id')->unsigned()->index();
            $table->foreign('county_id')->references('id')->on('counties');
        });
    }
class CreateCityZipcodePivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('city_zipcode', function (Blueprint $table) {
            $table->primary(['city_id', 'zipcode_id']);
            $table->unsignedBigInteger('city_id')->unsigned()->index();
            $table->foreign('city_id')->references('id')->on('cities');
            $table->unsignedBigInteger('zipcode_id')->unsigned()->index();
            $table->foreign('zipcode_id')->references('id')->on('zipcodes');
        });
    }
class CreateStateZipcodePivotTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('state_zipcode', function (Blueprint $table) {
            $table->primary(['state_id', 'zipcode_id']);
            $table->unsignedBigInteger('state_id')->unsigned()->index();
            $table->foreign('state_id')->references('id')->on('states');
            $table->unsignedBigInteger('zipcode_id')->unsigned()->index();
            $table->foreign('zipcode_id')->references('id')->on('zipcodes');
        });
    }

Here, I believe the model ZipCode belongsToMany. Does that seem right?

class ZipCode extends Model
{
    protected $fillable = ['zipcode'];
    
    // belongsToMany
    public function state() //$job->user
    {
        return $this->belongsToMany(State::class);
    }


    // hasMany

    public function cities() //$job->user
    {
        return $this->hasMany(City::class);
    }

    public function counties() //$job->user
    {
        return $this->hasMany(County::class);
    }
}
class State extends Model
{
   
    protected $fillable = ['state'];


    // hasMany
    public function cities() //$job->user
    {
        return $this->hasMany(City::class);
    }

    public function zipcodes() //$job->user
    {
        return $this->hasMany(ZipCode::class);
    }

    public function counties() //$job->user
    {
        return $this->hasMany(County::class);
    }
}
class City extends Model
{
    protected $fillable = ['city'];

    // belongsTo
    public function state() //$job->user
    {
        return $this->belongsTo(State::class);
    }


    // hasMany
    public function counties() //$job->user
    {
        return $this->hasMany(County::class);
    }

    public function zipcodes() //$job->user
    {
        return $this->hasMany(ZipCode::class);
    }

}

Putting in the data will be a nightmare, I can now see why @gn0rt0n offered up a package.

At any rate, does having zipcodes out of sorting order matter much? e.g. AZ is in the 85282 range. Should that data be placed in the database sequentially? Thank you `

22 May
1 month ago

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

so after solving the above I find this:

Apache Junction is a city in Maricopa and Pinal counties in the state of Arizona.

Does this suggest having a counties table with a many to many with cities and a belongsTo with state?

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

@TRAY2 - @TRAY2 - if I'm not mistaken that's for testing? Are you suggesting that's a way to populate these via the command line on the production server?

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class State extends Model
{
   
    protected $fillable = ['state'];

    // hasMany

    public function cities() //$job->user
    {
        return $this->hasMany(City::class);
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    protected $fillable = ['city', 'county', 'zipcode'];

    // belongsTo

    public function state() //$job->user
    {
        return $this->belongsTo(State::class);
    }
}
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('city');
            $table->string('county');
            $table->unsignedMediumInteger('zipcode')->length(5);
            $table->string('statecode')->length(2);
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('states', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('state');
            $table->string('statecode')->length(2);
            $table->foreign('statecode')->references('statecode')->on('cities');
            $table->timestamps();
            $table->engine = 'InnoDB';
        });
    }

After trying for quite a while, I found the column types need to be the same. See the string did not allow, as one of the columns needed to increment or something like that (can't remember exactly)

https://coderwall.com/p/o73fbq/creating-foreign-key-in-laravel-migrations

in Laravel 5.8+bigIncrements must align with unsignedBigInteger(). this was a real pain, but: https://stackoverflow.com/questions/55745137/general-error-1215-cannot-add-foreign-key-constraint-laravel-5-mysql/55746533#55746533

Another thing that sucked was the time of the migration, in this case I had to change the cities migration a second prior to states otherwise it wouldn't be found!

$table->engine = 'InnoDB'; some posts I found said you needed to declare this, but the solution below does not require it.

Following is the solution that allowed migrations. Now that this worked, does it appear to you the foreign key is set up properly?

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStatesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('states', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('state');
            $table->unsignedBigInteger('statecode');
            $table->foreign('statecode')->references('id')->on('cities');
            $table->timestamps();
        });
    }
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('city');
            $table->string('county');
            $table->unsignedMediumInteger('zipcode')->length(5);
            $table->timestamps();
        });
    }

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

@TRAY2 - ok, I'll give that a shot and post the results. Since these tables are static, other than a new zipcode every now and then, would each state have a sql file? I guess that would be a mysql source /file command? Have/How do you do that on a production server?

trevorpan left a reply on States, Cities, Zip Codes And Counties Database Tables (best Table Design For Populating Dropdowns)

@GN0RT0N - Hi, ok cool I just checked that one out. Thank you`

Also looked into the post office and UPS api but felt they were a bit much for me to handle now.

My site is quite a ways away from needing other countries; it's not a learning process for the sake of learning, but to get AZ working.

Just wanting to populate like this: https://www.youtube.com/watch?v=c7-HkztGahM

trevorpan started a new conversation States, Cities, Zip Codes And Counties (best Practice For Populating Dropdowns)

Hi there`

Have been working on a filter bar with html selects and came across the idea of dynamically populated dropdowns.

I've sketched out a number of ideas on how to structure the tables. It seems like a states table makes sense, not worried about countries yet, and right now I've got a ArizonaCitiesTable. I thought this would help against duplicate city names like Las Vegas, NM and Las Vegas (well of course Nevada!):

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateArizonaCitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('arizona_cities', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('city');
            $table->string('county');
            $table->unsignedMediumInteger('zipcode')->length(5);
            $table->timestamps();
        });
    }

Does this seem legit, or would you break out zipcodes, county?

These values then populate a jobs table.

And one other deal, with this kind of setup, do you have to create a sql file to upload on the production server to populate the values?

Thank you`

16 May
1 month ago

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - Alright, cool. This should be enough to get this thing figured out. Thank you very much `

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - May have it wrong - it seems if you're looping then a specific table, only for populating lists, would look like this?

class CreateFeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('fees', function (Blueprint $table) {
            $table->increments('id');
        $table->string('name');
            $table->boolean('free');
            $table->boolean('expensed');
            $table->boolean('paid');
        $table->boolean('unknown');
            $table->timestamps();
        });
    }
//CategoriesConroller.php

public function index (Request $request)
{
    $categoryList = Fee::get([
        'name' => $request('name'),
        'free' => $request('free'),
        'expensed' => $request('expensed'),
        'paid' => $request('paid'),
        'unknown' => $request('unknown')
        ]);

    return view('speakers.indes', compact('categorylist');
}

This could be a total botch here - are the child values column names from the table ?

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - @SNAPEY - good morning`

//Session data via Laravel Debugbar
array:7 [
  "bidded" => "0"
  "state" => "arizona"
  "city" => "tucson"
  "biddertype" => "subcontractor"
  "job" => "materials"
  "subjob" => "lumber"
  "filtered" => false
]

I'm a bit confused by this. The dropdowns do not stay set after clicking the submit button, though I've integrated the basic concepts and can still retrieve jobs.

How do you bind the session to the dropdowns?

here's a sample dropdown:

 <select class="selectx" name="job" id="job" required>
            <option class="optionx" value="">(5) Job</option>
            <option class="optionx" id="materials" value="materials">Materials</option>
        </select>

I found some ajax videos which prefixed the selects with id="sel_materials"but that (sel_) did not seem to affect anything.

In your function applyFilter() you are posting the html select to the session right? Not posting to the db? I find this a little confusing as the JobsController uses a get request to retrieve records from the db.

Or is the issue that the above form uses a submit button and your's filters at each dropdown?

14 May
2 months ago

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - @SNAPEY - no, need to be sorry! That's awesome - just what I'm trying to do. Had a FilterJobsController before, but couldn't get the routes right.

It'll take a few days to digest.. starting with this:

https://laracasts.com/lessons/whats-a-trait

13 May
2 months ago

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - The WINNER:

public function index(Request $request, Job $job)
    {
        $request->session()->put([
                'bidded' => request('bidded'),
                'state' => request('state'),
                'city' => request('city'),
                'biddertype' => request('biddertype'),
                'job' => request('job'),
                'subjob' => request('subjob'),
            ]);

        $jobs = Job::bidded($request->bidded)
                ->state($request->state)
                ->city($request->city)
                ->biddertype($request->biddertype)
                ->job($request->job)
                ->subjob($request->subjob)
                ->paginate(3)
                ->appends([
                       'bidded' => request('bidded'),
                       'state' => request('state'),
                       'city' => request('city'),
                       'biddertype' => request('biddertype'),
                       'job' => request('job'),
                       'subjob' => request('subjob')
                ]);

        return view('jobs.index', compact('jobs')); 
}

So, your method of starting with the first item bidded and then state etc found the error. Multiple errors. Egregious things like capital State instead of lowercase state, etc. and after fixing that found that material was materials!

So that works.

But the original post sought to put the selection into a session so the filter button, html selects, would stay populated.

Am I on the right track for that?

I've read that's generally done with ajax, but I'm not familiar. Is there a laravel way?

11 May
2 months ago

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@JLRDW - could you clarify "don't see session in the scope"? In your pdetest() are you saying all the local scopes can be combined there and then you could call $jobs = Job::pdotest()->get;?

on a new finding - I'm wondering if the pagination is causing this. After reading a few posts about getCollection() not available I read the get()request on the controller is an array, so the @blade call fails.

//index.blade.php
    @foreach(array_chunk($jobs->getCollection->all(), 3) as $page)

            @foreach ($jobs as $job) 
                   @include ('jobs.job')
                @endforeach

                <div class="pagenumbers">
                    {{ $jobs->links() }}
                </div>

        @endforeach

man, this stuff fun and crazy frustrating at the same time!

trevorpan left a reply on Put Search Filter Buttons Into Session And Return Results

@SNAPEY - Yea, I love it, too.

This is what the query says (it also shows an auth query, but that's not an issue):

select * from `jobs` where `bidded` = '0' and `state` = 'Arizona' and `city` = 'Phoenix' and `biddertype` = 'GeneralContractor' and `job` = 'Lumber' and `subjob` = 'Material'

The session shows the selected dropdowns each time they are changed.

_token
    HePISm5UdwWOUlAzUZsPzU9d32UoY7aA1vzsDx3s
_previous
    array:1 [ "url" => "http://bidbird.test/jobs?_token=HePISm5UdwWOUlAzUZsPzU9d32UoY7aA1vzsDx3s&bidde...
_flash
    array:2 [ "old" => [] "new" => [] ]
bidded
    array:1 [ 0 => "0" ]
state
    array:1 [ 0 => "Arizona" ]
city
    array:1 [ 0 => "Phoenix" ]
biddertype
    array:1 [ 0 => "GeneralContractor" ]
job
    array:1 [ 0 => "Lumber" ]
subjob
    array:1 [ 0 => "Material" ]
login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d
    1
PHPDEBUGBAR_STACK_DATA
    []

When I dd($jobs, $request); (in [email protected]) I get this below - which seems like it's never talking to the database, as the array is empty - there's two test jobs.

Is that how you would interpret this response?

Collection {#557 ▼
  #items: []
}

// relevant array data

 #session: Store {#489 ▼
    #id: "sjTKpjiW2R1NbxG223hR2cuqaPOII1g9aQcMLSn0"
    #name: "bidbird_session"
    #attributes: array:10 [▼
      "_token" => "HePISm5UdwWOUlAzUZsPzU9d32UoY7aA1vzsDx3s"
      "_previous" => array:1 [▶]
      "_flash" => array:2 [▼
        "old" => []
        "new" => []
      ]
      "bidded" => array:1 [▼
        0 => "0"
      ]
      "state" => array:1 [▼
        0 => "Arizona"
      ]
      "city" => array:1 [▼
        0 => "Phoenix"
      ]
      "biddertype" => array:1 [▼
        0 => "Subcontractor"
      ]
      "job" => array:1 [▼
        0 => "Mechanical"
      ]
      "subjob" => array:1 [▼
        0 => "Material"
      ]
10 May
2 months ago

trevorpan left a reply on Put Filter Buttons Into Session Using ResourceCollection?

@JLRDW - Hi there, been working on this thing the last few days.

select * from `jobs` where `bidded` = '0' and `state` = 'Arizona' and `city` = 'Phoenix' and `biddertype` = 'Subcontractor' and `job` = 'Mechanical' and `subjob` = 'Material'

This query is returned based on the links you shared. It is the proper query but does not retrieve any results.

//JobsController

protected $with = ['bidded', 'state', 'city', 'biddertype', 'job', 'subjob'];

public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }

public function index(Request $request)
    {
   $jobs = Job::bidded($request->bidded)
                    ->state($request->state)
                    ->city($request->city)
                    ->biddertype($request->biddertype)
                    ->job($request->job)
                    ->subjob($request->subjob)
                    ->get();

    return view('jobs.index', compact('jobs'));
}
//Job.php (model)

    public function scopeBidded($query, $bidded)
    {
        if (!is_null($bidded)) {
            return $query->where('bidded', $bidded);
        }

        return $query;
    }

Is the compact(); setup incorrectly? I'm also unclear, the docs show the $query variable but the controller is using $request. Is the query made available via the container, and $request resolves it? .. still trying to wrap my head around all this stuff.

06 May
2 months ago

trevorpan left a reply on Put Filter Buttons Into Session Using ResourceCollection?

@JLRDW - cute pups. It's neat how the 'like' allowed you to type just the first letter for cat.

Ok, I saw that use of 'like' in the stackoverflow post you provided but this: 'return $query->where('bidded', 'like', '%'.$bidded.'%');yielded an errorArray to string conversion. So I tried the above, but I feel it's not pulling the selected, the scope is looking forjob` for instance.

I may have made a mistake in the explanation. The filter bar is a drop down with selects e.g. Job could have steel, lumber, plumbing, etc. So the user is unable to type a choice. (at least at this stage-maybe in the future).

On the authorize() it comes false from the artisan command, but if you have other middleware it said to turn it to true. https://laravel.com/docs/5.7/validation#form-request-validation (a little down the page).

trevorpan left a reply on Put Filter Buttons Into Session Using ResourceCollection?

@SNAPEY - Hi, I don't think that's possible - is it?

I read a post you replied about an actor or speaker website you were working on some time back. It maintained state between pages. That had the basic functionality I'm looking for for my app.

I may be confusing what can be done with the JSON API, but I thought maybe the ResourceCollection could accomplish the filter bar/buttons and give the data in form of JSON like the Job extends JsonResource (hopes) to do.

trevorpan left a reply on Put Filter Buttons Into Session Using ResourceCollection?

@JLRDW - ok, this is how job population was achieved before in the JobsController (prior to today's post):

public function index(Request $request)
    {
        $jobs = Job::oldest()
        ->filter(request(['month', 'year']))
            ->get();

    return view('jobs.index', [
            'jobs' => Job::paginate(3)->onEachSide(3)
            ], compact('jobs'));
}

After reviewing that stack article I've made some modifications. With this form request, is it wise to "re-validate" if the data was validated when user created a job? In this case, we're just trying to populate existing jobs, not create new ones.

Does this prevent malicious attacks?

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class FilterJobs extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'bidded' => 'required|integer'
            'state' => 'required',
            'city' => 'required',
            'biddertype' => 'required',
            'job' => 'required',
            'subjob' => 'required',
            //
        ];
    }
}

Added query scopes. I felt like these queries should be singular, and the controller collects an array - seem right?

// Job.php (model)

    public function scopeBidded($query, $bidded)
    {
        if (!is_null($bidded)) {
            return $query->where('bidded', 'bidded');
        }

        return $query;
    }

    public function scopeState($query, $state)
    {
        if (!is_null($state)) {
            return $query->where('state', 'state');
        }

        return $query;
    }

    public function scopeCity($query, $city)
    {
        if (!is_null($city)) {
           return $query->where('city', 'city');

        return $query;
    }

    public function scopeBidderType($query, $biddertype)
    {
        if (!is_null($biddertype)) {
            return $query->where(['biddertype', request('biddertype')]);
        }

        return $query;
    }

    public function scopeJob($query, $job)
    {
        if (!is_null($job)) {
            return $query->where('job', 'job');
        }

        return $query;
    }

    public function scopeSubJob($query, $subjob)
    {
        if (!is_null($subjob)) {
            return $query->where('subjob', 'subjob');
        }

        return $query;
    }
//JobsController

        public function index(Request $request)
    {

        $jobs = Job::bidded($request->bidded)
                    ->state($request->state)
                    ->city($request->city)
                    ->biddertype($request->biddertype)
                    ->job($request->job)
                    ->subjob($request->subjob);
    
    return view('jobs.index', [
            'jobs' => Job::where([
            ['bidded', request('bidded')],
            ['state', request('state')],
            ['city', request('city')],
            ['biddertype', request('biddertype')],
            ['job', request('job')],
            ['subjob', request('subjob')], 
            ])->paginate(3)
                ->onEachSide(3)
                ->appends([
                    'bidded' => request('bidded'),
                    'state' => request('state'),
                    'city' => request('city'),
                    'biddertype' => request('biddertype'),
                    'job' => request('job'),
                    'subjob' => request('subjob'),
            ])
        ]);

The above does not retrieve a job that exists in the database, but it also does not cause a whoops page either. I feel like this is a double query, not sure how to put the results into an array. Any ideas where it's going wrong?

trevorpan left a reply on When Is A JSON API Necessary In A Laravel App?

Yea, definitely reading a lot. It's crazy all this stuff. I've thumbed through the JSONapi website, and took a brief look.

You really nailed it though, the need of JSON API hinges on using other sites or interacting with them. Somehow I missed that in all the articles.

trevorpan started a new conversation Put Filter Buttons Into Session Using ResourceCollection?

May very well be butchering this process ..

The app has a filter bar with a number of drop down menus which allow users to select a job of their interest. At one point, I had a FilterJobsController but later scrapped it, as you can only get to /jobs by selecting the filter buttons - there is no /jobs link. So, then it seemed having that logic in the JobsController made good sense.

Now, I've determined that in addition to showing the job results on the app's page, I'd like the data to also be available in JSON format for use with other sites.

I've discovered the menus need to be in the session, otherwise it's very annoying to have to re-select the menu of a users choice over and over. ResourceCollections are new to me, and I'm not sure how the user selections are put into the session while retrieving the data.

Do you have any experience with this? Am I on the right track?

class JobsController extends Controller
{
    protected $job;

    public function __construct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }
    

    public function index(Request $request)
    {
        $jobs = function () {
            return JobResource::collection(Job::oldest());
        };
        
    return view('jobs.index', [
            'jobs' => Job::where([
            ['bidded', request('bidded')],
            ['state', request('state')],
            ['city', request('city')],
            ['biddertype', request('biddertype')],
            ['job', request('job')],
            ['subjob', request('subjob')], 
            ])->paginate(3)
                ->onEachSide(3)
                ->appends([
                    'bidded' => request('bidded'),
                    'state' => request('state'),
                    'city' => request('city'),
                    'biddertype' => request('biddertype'),
                    'job' => request('job'),
                    'subjob' => request('subjob'),
            ])
        ]);
    }
<?php

namespace App\Http\Resources;

use App\Job;
use App\Http\Resources\Job as JobResource;
use Illuminate\Http\Resources\Json\ResourceCollection;

class JobCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {

        $request->session()->put([
            'bidded' => 'bidded', 
            'state' => 'state', 
            'city' => 'city', 
            'biddertype' => 'biddertype', 
            'job' => 'job', 
            'subjob' => 'subjob'
        ]);

        return [
            'data' => $this->collection,
            'links' => [
                'self' => route('jobs.index'),
            ],
        ];
    }
}
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Job extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'jobtitle' => $this->jobtitle,
            'body' => $this->body,
            'projectaddress' => $this->projectaddress,
            'city' => $this->city,
            'state' => $this->state,
            'zipcode' => $this->zipcode,
            'biddertype' => $this->biddertype,
            'job' => $this->job,
            'subjob' => $this->subjob,
            'deadline' => $this->deadline
        ];   
    }
}

trevorpan left a reply on When Is A JSON API Necessary In A Laravel App?

First off, cool example!

So, if an app "interacts" with another website, "then" it needs an API? In each case it's different but the JSON format is de facto.

If your website does not interact with a website, e.g. pull in pets, or I imagine, add pets to their selection (in your example) then doing an API is unnecessary?

trevorpan started a new conversation When Is A JSON API Necessary In A Laravel App?

When you type JSON API and Laravel into a search engine there's tons of posts on how to build one—even the virtues of building one.

I watched the Laracasts API Resources video and it seems great, but I'm not fully understanding the difference of retrieving database info as JSON vs what a Controller will do (without ResourceCollections).

https://www.youtube.com/watch?v=7YcW25PHnAA this video shows data rendered as webpages (with styling), but also JSON info in the background if you use the right api web address. e.g. api.twitter.com

I'm having a hard time figuring out if it's necessary in my app. Below is a attempt at using a ResourceCollection, after checking out Laravel Up and Running 2.0 v2 (book).

//Routes\web.php

use App\Job;
use App\Http\Resources\Job as JobResource;

Route::get('jobs/{id}', function ($id){
             return new JobResource(Job::find($id));
        });

The above spits out (without showing the website view):

data    
    id                           1
    jobtitle                     "Test"
    body                     "test"
    projectaddress   "123"
    city                             "phoenix"
    state                    "arizona"
    zipcode                  85004
    biddertype           "subcontractor"
    job                          "materials"
    subjob                   "mechanical"
    deadline             "2019-05-13 16:26:58"

If a poster posted a job, and I wanted it to then be posted to say Twitter, or LinkedIn (for promotion), is it mandatory to use the JSON API resource method?

Can this feature be accomplished with just controllers?

04 May
2 months ago

trevorpan left a reply on Missing /tests/ Folder (upgrading From 5.7 To 5.8)

ok, this was dumb.

I took at look at some Pull Requests changed files tab which had the /tests/ folder for the framework itself. No wonder I couldn't find them - Had made the mistake of trying to manually update the changes, and then realized composer update does that very nicely already!

Is it happy hour yet?

trevorpan started a new conversation Missing Tests/Integration/Events/EventFakeTest.php

https://github.com/laravel/framework/commit/d52298af424f0a5751a3748dc8d8c8330b4c8a77#diff-b1f3fd7464ee0e8493e85002dd33c7d8

also missing: tests/Foundation/Http/KernelTest.php

Trying to upgrade from 5.7 to 5.8. This entire directory is missing in /vendor/laravel/framework/src...

something seems out of whack, any ideas?

24 Apr
2 months ago

trevorpan left a reply on Should /tests Be In .gitignore?

@SHEZ1983 - That's a great thing to keep in mind, too. Thank you. No, now I'm sold — they're not going anywhere.

My knowledge is like a block of swiss cheese — plenty of holes — but a small body of knowledge is there`

trevorpan left a reply on Should /tests Be In .gitignore?

@CRONIX - nice!!

Oh, man so to much to read. I've been reading for 18 months! 256 videos, so far, too.

Thank you very much!

23 Apr
2 months ago

trevorpan left a reply on Should /tests Be In .gitignore?

@CRONIX - Ok, thank you, that's an angle I didn't think of. I was picturing 'megabytes' of tests and unnecessary storage.

On the automated pipeline — is that something you'd create on forge? Is this a non-live, provisioned server?

Also, do you know of a "lifeline" blog post or resource that covers from initial laravel new newwebsite all the way through production and maintenance? I'd love to have access to a resource that says, "and at this step most developers do x..."

trevorpan left a reply on Should /tests Be In .gitignore?

@SNAPEY - At the moment, /tests is not in the .gitignore file.

I've been running through the book Laravel Up and Running 2.0 and TDD on Laracasts. I'm foreseeing a lot of tests in my app.

Is there a reason to commit them to a production server?

It seems like they should be committed to version control, but not uploaded to production server.

trevorpan started a new conversation Should /tests Be In .gitignore?

It seems like this folder should not make it to production. However, having versions of tests also seems like a logical and good thing.

There's no mention of it here: https://laravel.com/docs/5.8/http-tests

Any thoughts or best practice tips?

05 Apr
3 months ago

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@SNAPEY - ok, cool I'll keep that in mind. Still trying to grasp all the globally available things vs imported/namespaced.

Man that was an epic journey on this post!

Really appreciate your help`

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@SNAPEY - ``` $hasbidinterest = auth()->user()->bidInterests()->where('job_id',$job->id)->bidderInterested()->exists();


man, finally got this thing. Your method uses `Auth::user` which returns: 

Class 'App\Http\Controllers\Auth' not found

Why does the basic logic work with `auth()->user(), etc` and not `Auth::user`?

Basic things to fix.
-Routes needed to be `cleaned` up
-`bidinterest` had to be on [email protected], not [email protected]
-by declaring auth()->user()-> I was able to leave the Jobs page without authentication under the @show method but tested the user, if authenticated.

success!

Thank you @snapey and thank you @cronix

trevorpan left a reply on 500 Error, When Registering Account On Live Site

@SNAPEY - ok, that's new to me. I'll give it a go here and let you know. Thank you.

trevorpan left a reply on 500 Error, When Registering Account On Live Site

Hi, thank you.

Have been hunting around here on laracasts, but I must be missing something. The SSH, on SQLPro, only shows tables, not the storage folder.

Where do you go to view log files on a live server? I've hunted around the next three dashboards, but cannot seem to find a /public folder to have a look at everything - like you see in GitHub.

My setup is Envoyer, Forge and Linode.

trevorpan started a new conversation 500 Error, When Registering Account On Live Site

Hi,

finally made it to the point of getting my site live! thank you laracasts.

A real, bonafide "user" even signed up yesterday. However, after signing up a 500 error is thrown. The user told me they can login fine.

I'm able to SSH into the database, provisioned by Forge, and see the user. I tried it myself and the 500 error seems to be consistent.

How can you find the source of this? My local copy does not yield this result.

Here's the RegisterController.php

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/home';
...

web.php

Route::get('/home', '[email protected]')->name('home');

I've double checked the email smtp credentials. at a loss.

04 Apr
3 months ago

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@CRONIX - Here's BidInterest.php

public static function scopeBidderInterested($query)
    {
        return $query->where('bidderinterested', 1);
    }

trying to reference the scope query, and ensure the authenticated user is prohibited from seeing the checkbox if they clicked it.

Other users should see the box so they are enticed to whip out their wallets, and place a bid..

hha

that's right, I forgot on the one =, == is what tests for a condition?

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

man, I'm still tinkering with this thing and have made some progress, but could still use a hand:

class JobsController extends Controller
{
    protected $job;

    public function __construct()
    {

        $this->middleware('auth')->except(['index', 'show']);

    }
....

    public function show(Job $job)
    {

        // $thumbnail = $job->getFirstMedia('document');
        $fullpageimage = $job->getFirstMedia('document');
        // $fullpageimage = Arr::first($fullpageimage);

        $downloads = $job->getMedia('document');
        // $downloads = $job->getMedia('document');
        
        $hasbidinterest = BidInterest::BidderInterested()->where('job_id', '=', $job->id)->get();
        // dd($hasbidinterest);
    

        return view('jobs.show', compact('job', 'downloads', 'fullpageimage', 'thumbnail', 'hasbidinterest')); 
    }

The JobsController has an authentication except on 'show', in this case, and it interferes with displaying the checkbox. How do you test for authenticated user for just $hasbidinterest but not interfere with the overall 'show' method?

The show method is used to display a job for anyone, not just auth()->users

here's new logic in the blade file


        @if ($hasbidinterest = true)

            Thank you for your interest in bidding this job.
            
        @else 
        
            <form action="/jobs/{{ $job->id }}/bidinterest" method="POST">
                @csrf
                <input type="checkbox" name="bidderinterested" value="1" required>

                I will bid this job.<br>
                <input type="submit" value="Submit">
            </form> 

        @endif 

When dd($hasbidinterests); it does show all the bidders, and counts them properly. However, because the blade logic does not yield the result desired a single user can hit the button as many times as they like.

Thank you anyone ~

05 Mar
4 months ago

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@cronix

After a lot of hunting down, I found that the variable was not available because the show method in the JobsController.php did not have the logic.

In this case, the full sized job display page (not thumbnail descriptions) has a number of controllers being referenced.

JobsController:

    public function show(Job $job)
    {

        // $thumbnail = $job->getFirstMedia('document');
        $fullpageimage = $job->getFirstMedia('document');
    

        $downloads = $job->getMedia('document');
    
        $hasbidinterest = BidInterest::BidderInterested(1)->get();

        return view('jobs.show', compact('job', 'downloads', 'fullpageimage', 'thumbnail', 'hasbidinterest'));
    }

After adding the line above and referencing the query scope, it at least does not crash the page.

Do you handle multiple controllers on a page? Is this a case to return back() on the BidInterestsController.php controller, as opposed to a view?

03 Mar
4 months ago

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@CRONIX - ok, got that cleaned up. @if($hasbidinterest) yields a Undefined variable: hasbidinterest.

Stepping back . . . if a bidder has clicked the checkbox it registers as a 1 in the bidderinterested column, if they do not click the checkbox it never registers.

Is it possibile for a query scope in BidderInterest.php, to positively show, or not show the checkbox to someone who has expressed their interest to bid?

<?php

namespace App\Http\Controllers;

use App\Job;
use App\BidInterest;
use Illuminate\Http\Request;

class BidInterestsController extends Controller
{
    //

    protected $bidinterest;

    public function __construct()
    {
        $this->middleware('auth');
    }


        /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Job $job)
    {
        $this->validate(request(), [
            'bidderinterested' => 'required',
        ]);

        // add bidder interest to job
        $bidinterest = auth()->user()->bidInterests()->create([
            'bidderinterested' => request('bidderinterested'),
            'job_id' => $job->id
            ]);
        
        return back();
    }

    public function show(BidInterest $Bidinterest)
    {
        // dd('hi');

        // DB::table('bidinterests')->where('bidderinterested', 1)->exists();
        // $hasbidinterest = Auth::user()->whereRaw('$job->id = jobs.id')->BidderInterested();

        $hasbidinterest = Auth::user()->bidInterests()->where('job_id', '=', $job->id)->BidderInterested();
        
        return view('jobs.jobfull', compact('hasbidinterest'));
    }
}
02 Mar
4 months ago

trevorpan left a reply on Don't Show Checkbox If Auth()->user Has Submitted Checkbox

@snapey @cronix ok, got the routes set (at least no errors right now) thank you there.

//jobs
Route::resource('/jobs', 'JobsController');

//job bid interests
Route::post('/jobs/{job}/bidinterest', '[email protected]');
Route::get('jobs/{job}/bidinterested', '[email protected]');

BidInterest.php (model)

    public static function scopeBidderInterested($query)
    {
        return $query->where('bidderinterested', 1)->exists();
    }

Job.php (model)

    public function bidderinterests()
    {
        return $this->hasMany(BidInterest::class);
    }

User.php (model)

    public function bidinterests()
    {
        return $this->hasMany(BidInterest::class);
    }

The above models now have names that don't conflict (there were 2 bidinterests()).

    public function show(BidInterest $Bidinterest)
    {

        $job->load('bidInterests');

        $hasbidinterest = Auth::user()->bidInterests()->where('job_id', '=', $job->id)->BidderInterested();

        return back(compact('job', 'hasbidinterest'));

    }

After clicking a checkbox, the counter ups the number of interested bidders, but the checkbox does not return the if statement.

        @if ($job->user->hasbidinterest)

            Thank you for your interest in bidding this job.
            
        @else 
            <form action="/jobs/{{ $job->id }}/bidinterest" method="POST">
                @csrf
                <input type="checkbox" name="bidderinterested" value="1" required>

                I will bid this job.<br>
                <input type="submit" value="Submit">
            </form> 
        @endif 

Any ideas?