trevorpan

trevorpan

Member Since 8 Months Ago

Experience Points 30,510
Experience Level 7

4,490 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 287
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.

16 May
3 days 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
5 days 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
6 days 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
1 week 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
1 week 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
1 week 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 weeks 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
3 weeks 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
3 weeks 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
1 month 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
1 month 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
2 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
2 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
2 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?

26 Feb
2 months ago

trevorpan left a reply on Email Best Practice: Messages & Controllers & Tables

@SNAPEY - Hi,

Ok, I was not aware of that. I thought validated fields had to be stored in a database table.

Always something. Thank you again. You are super helpful!

trevorpan left a reply on Email Best Practice: Messages & Controllers & Tables

@SNAPEY - May not need a table. My goal was to find out how people handle this.

e.g. a prospective customer emails to get more info from the typical 'contact' button on the navbar.

Is that stored in the database and sent to an email account? From the forum posts on Laracasts, I see that people create forms which need to be validated—I assumed that means having a particular table for contacts. There were a few posts on ContactController.

Could you elaborate a little on storing/validating in a session? (this is a form contact you are thinking of?)

25 Feb
2 months ago

trevorpan started a new conversation Email Best Practice: Messages & Controllers

When creating a site that has authenticated users (with account) and potential new users (no account) do you typically create a PublicMessagesController for public messages e.g. on the navbar, and an internal (authenticated) SupportsController?

<?php

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

class PublicMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('publicmessages', function (Blueprint $table) {
            $table->increments('id');
            $table->string('firstname');
            $table->string('lastname');
            $table->string('email')->unique();
            $table->text('message');
            $table->timestamps();
        });
    }

Just whipped this up. And am thinking about the future of the site. Should a controller like this include a user_id and force people to signup? Seems kind of pushy. What if they're just dipping their toes? But it'd be nice to associate all messages with a user.

Does this happen in the email response? Like, hey "messager" we love you emailed us, after we answer your question—create an account!

However, if they never sign up a message in the publicmessages table—it's like a misfit.

If you have any experience here, I'd love to see how other sites handle this. It's not particularly unique, but I think valuable.

22 Feb
2 months ago

trevorpan left a reply on Laravel Forge Pushing To Master Gives An Error

@CRONIX - Hi, after you run 'npm run production' and pushed to github I ran composer install, to resume developing on my local machine.

Is this how it's done?

I felt like it was inefficient run the commands in the laravel deploy docs, and then 'npm run production', have all those packages deleted and the reinstall them. Just want be sure that is the correct way.

Thank you`

19 Feb
3 months ago

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

@SNAPEY - would you say in this case BidInterestsController is not needed?

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

@CRONIX - this was helpful.

now if you want to render the variables from '[email protected]' (this OP) on a specific jobs/{job} page can you redeclare the same view? I think this is a major reason this has been troublesome.

e.g. JobsController.php:

public function show(Job $job)
    {
        //code

        return view('jobs.show', compact('job'));
    }

e.g. BidInterestsController.php:

public function show(Job $job)
    {
        //code

        return view('jobs.show', compact('hasbidinterests'));
    }

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

@CRONIX - Thank you again, as always!

how would you specify the bid route if the bid is submitted on the job page?

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

@CRONIX - That's another area that's still a little muddy.

Here's are the current routes:

Route::get('/jobs', '[email protected]')->name('jobs.index');
Route::get('/jobs/create', '[email protected]');
Route::post('/jobs', '[email protected]');
Route::get('/jobs/{job}/edit', '[email protected]');
Route::get('/jobs/{job}', '[email protected]')->name('showjobedits');
Route::patch('/jobs/{job}', '[email protected]');


Route::post('jobs/media', '[email protected]')
  ->name('jobs.storeMedia');


Route::post('/jobs/{job}/questions', '[email protected]');


Route::post('/jobs/{job}/bids', '[email protected]');
Route::get('/jobs/{job}/edit', '[email protected]');
Route::patch('/jobs/{job}', '[email protected]');


Route::post('/jobs/{job}/bidinterests', '[email protected]');
Route::get('jobs/{job}', '[email protected]');

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

@CRONIX - ok, i'm not going insane! thank you.

There are two controllers. JobsController and BidInterestController. Could they possibly conflict?

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

@SNAPEY - Yea, I had thought about the double negatives, too. I'll keep this in mind for future.

This error is given in the blade: Undefined variable: hasbidinterest (View: /Users/trevorpan/code/bidbird/resources/views

This is the exact method:

    public function show(BidInterest $Bidinterest)
    {
        $job->load('bidInterests');


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

 
        return view('jobs.show', compact('hasbidinterest'));
    }

It's puzzling.

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

@SNAPEY - https://laracasts.com/discuss/channels/eloquent/what-is-the-proper-way-to-check-a-boolean-from-a-db

so many trickses in programming.

$hasbidinterest = Auth::user()->bidInterests()->where('job_id',$job->id)->where(1,'=',1)->get(['bidderinterested']);

I tried the above but the code

       @if (!$job->hasbidinterest)
            <form action="/jobs/{{ $job->id }}/bidinterests" method="POST">
                @csrf
                <input type="checkbox" name="bidderinterested" value="1" required> I will bid this job.<br>
                <input type="submit" value="Submit">
            </form> 
        @else 
            Thank you for your interest in bidding this job.
        @endif 

Does it need to test for boolean? The table only stores 1 if they click the checkbox.

Also, tried to modify the above and use the exists() method:

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

thank you, feels like on the verge of solving the issue.

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

@SNAPEY - Wow. I pulled this from the Laravel docs.

You refactored it to one line:

old:

        $bidinterests = App\BidInterest::withCount('bidderinterested')->get();
        
        foreach ($bidinterests as $bidinterest) {
                 echo $bidinterest->bidderinterested_count;
             }

new: $job->load('bidInterests'); the same call in blade works as you mentioned: {{ $job->bidInterests->count() }}

Does this technique work because the table is minimal? Where a table with more than one column would need the above 'old' code?

18 Feb
3 months ago

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

@SNAPEY - omg. idk.

Perhaps the confusing part is there are two operations. I may be trying to do too much in the show method.

http://trevorpan.com/stuff/bidders2.jpg (top box of screenshot)

1st part: There are `___` many bidders for this job. (here is where the $bidinterests goes. It works)
2nd part:  `[ ]` box if you would like to bid this job. (here is where $hasbidinterest goes. It does not work)

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

@CRONIX - thank you much` I understand the array a good bit better and why it works for the count of bidders.

one confusing thing here in relation to the single variable $hasbidinterest:

$bidinterests = App\BidInterest::withCount('bidderinterested')->get();
        
        foreach ($bidinterests as $bidinterest) {
                echo $bidinterest->bidderinterested_count;
            }

(this code renders in the page) with {{ $job->bidinterests->count() }}. Is it available in the blade because it was echoed? So this case a compact('bidinterests') is unnecessary?

@snapey 's line:

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

is what the goal is => Is this user authenticated, have they hit the select box "interested in bidding this job". The @if statement checks this.

My goal is something like

@if(!$hasbidinterest)    
    show the check box
@else 
    thank you for your interest in bidding
@endif 

the above does not work. is this because several variables are being created in the show method? e.g. bidinterests and $hasbidinterestare they conflicting?

I have changed the code to:

public function show(BidInterest $Bidinterest)
    {

        $bidinterests = App\BidInterest::withCount('bidderinterested')->get();
        
        foreach ($bidinterests as $bidinterest) {
                echo $bidinterest->bidderinterested_count;
            }


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

        // echo = $hasbidinterest;

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

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

@SNAPEY - Sweet.

This is where I'm confused in MVC. I added to this line: return view('jobs.show', compact('job', 'bidderinterested)); Read up on compact here: http://php.net/manual/en/function.compact.php Not clear on how that array works, or if 'bidderinterested' even registers with compact in this scenario.

Now the good thing is{{ $job->bidinterests }} spits out the json records in the page.

[{"id":40,"user_id":1,"job_id":22,"bidderinterested":1,"created_at":"2019-02-18 21:10:53","updated_at":"2019-02-18 21:10:53"}]

{{ $job->bidinterests->hasbidinterest }} goes nowhere either. Why is the variable we created not visible?

Property [hasbidinterest] does not exist on this collection instance.

'{{ $job->hasbidinterest }}' nada and {{ $hasbidinterest }} is useless..

Then I thought perhaps echo = $hasbidinterest; would make it available in the public function show method. man.

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

@SNAPEY - Ha! puzzled ? I'm puzzled, too.

the bidderinterested is a feature which allows a bidder to state their intent to bid. This is so other bidders see how competitive the job is - the logic is if you know 8 bidders are going for a modest job you can pass. My goal is transparency.

There is a separate bids table which handles the actual dollar amounts. (the screenshots above show interested, and submit bid - it's real bare bones right now, just trying to get it function)

back to the line you have above is what I was "trying" to do. thank you`

In User model, I had already placed

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

If the relationship is hasMany is it good to use plural? And if hasOne to use singular? This is just a convention question.

I put the line like so:

    public function show(BidInterest $Bidinterest)
    {
    // this shows all the interested bidders in the screenshot above
        $bidinterests = App\BidInterest::withCount('bidderinterested')->get();
        
        foreach ($bidinterests as $bidinterest) {
                echo $bidinterest->bidderinterested_count;
            }
    //end

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

I've added the $hasbidinterest to the blade file as {{ $hasbidinterest }} (changed slightly to reflect the logic of the app) but it spits out Undefined variable: .

Why does that happen?

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

@SNAPEY - good morning, and thank you.

I was unclear why the $userbidinterests was not available. In fact, it was puzzling. In the same view $question->body can be accessed—although this was after a `@foreach ($job->questio was established. (still a bit unclear on how this comes together)

With regards to the boolean, I tried the Laravel docs: return DB::table('orders')->where('finalized', 1)->exists(); however, the @if statement read it as if any finalized exists. So, the auth()->userwas not acting as the conditional.

So the above attempts were made using the collection method.

Here's

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class BidInterest extends Model
{
    //
    protected $guarded = [];
    
    public $table = "bidinterests";

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

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

    public function job()
    {
        return $this->belongTo(Job::class);
    }
}
<?php

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

class CreateBidinterestsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('bidinterests', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_id');
            $table->unsignedInteger('job_id');
            $table->boolean('bidderinterested')->default(false);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('bidinterests');
    }
}
17 Feb
3 months ago

trevorpan started a new conversation Don't Show Form If Auth()->user Has Submitted Form

Hi, this form shows how many interested bidders there are for a given job. After a user_id has submitted interest to bid, the blade takes away the possibility of resubmitting the form.

http://trevorpan.com/stuff/bidders.jpg

Having a real tough go on getting the auth()->user to be the conditional. There are two forms, but I think the first one should resolve the

    //class BidInterestsController extends Controller @ show


    // $userbidinterests = DB::table('bidinterests')
        //     ->where('user_id', '==', auth()->user->id)->get();
        
        $userbidinterests = DB::table('bidinterests')
                                ->whereExists(function ($query) {
                                    $query->select(DB::raw(1))
                                          ->from('bidderinterested')
                                          ->whereRaw('bidderinterested.user_id = users.id');
                                })
                                ->get();

The blade logic

    <div class="bidinterest">
        <h3>Number of bidders:</h3>     

        There are <b> {{ $job->bidinterests->count() }} </b> bidders for this job. 
        <hr> 


        @if (!$job->userbidinterests)
            <form action="/jobs/{{ $job->id }}/bidinterests" method="POST">
                @csrf
                <input type="checkbox" name="bidderinterested" value="1" required> I will bid this job.<br>
                <input type="submit" value="Submit">
            </form> 
        @else 
            Thank you for your interest in bidding this job.
        @endif

    </div>

    <div class="placebid">
    
        
        @if (count($job->bids) === 0)

        <h3>Place bid here:</h3>
            <form method="POST" action="/jobs/{{ $job->id }}/bids"> 
                @csrf
                <div class="bidinput">
                    <textarea name="bid" placeholder="e.g. ,645.22" cols="14" rows="1" class="form-control" required></textarea>
                </div>

                <div class="bidsubmit">
                    <button type="submit" class="btn-bid">Place my bid!</button>
                </div>
            </form>

        @else

        <h3>Edit your bid here:</h3>
            <form method="POST" action="/jobs/{{ $job->id }}">  
                @method('PATCH')
                @csrf
                <div class="bidinput">
                    <textarea name="bid" cols="14" rows="1" class="form-control" value="{{ $job->bids }}" required></textarea> 
                </div>

                

                <div class="bidsubmit">
                    <button type="submit" class="btn-bid">Edit my bid!</button>
                </div>
            </form>

        @endif

        @include ('layouts.errors')
    </div>