Shedman

Member Since 6 Months Ago

Experience Points
6,640
Total
Experience

3,360 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
54
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

  • Community Pillar

    Earned once your experience points ranks in the top 10 of all Laracasts users.

Level 2
6,640 XP
Mar
05
1 month ago
Activity icon

Awarded Best Reply on File Path Error

I failed to create a symbolic link by using

php artisan storage:link

Then accessing it this way.

asset('storage/file.txt');
Activity icon

Replied to File Path Error

I failed to create a symbolic link by using

php artisan storage:link

Then accessing it this way.

asset('storage/file.txt');
Mar
04
1 month ago
Activity icon

Started a new Conversation File Path Error

I am trying to attach a pdf to an email. I am passing the details with the path to the file.

$details = [
					'message' => 'Here is a new signed pdf',
					'attachment' => $storage_path.'/app/public/'.$document_id.'.pdf'
				];

Then I am attaching it to the build function

public function build()
    {

        return $this->subject($this->details['title'])->view('contracts.mail')->attachFromStorage($this->details['attachment']);
    }

I get an error that the path is wrong.

[previous exception] [object] (League\Flysystem\FileNotFoundException(code: 0): File not found at path: home/forge/domain.com/storage/app/public/39861cca-5676-4c51-8478-bdb4de9a31bf.pdf at /home/forge/domain.com/vendor/league/flysystem/src/Filesystem.php:389)

If I SSH into the site I can see this document in views.

cd domain.com/storage/framework/views/
Feb
18
1 month ago
Activity icon

Replied to Collecting Payments

Following the Cashier documentation, I have tried to change it to my customer model.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Contracts;
use Laravel\Cashier\Billable;


class Customers extends Model
{
    use HasFactory;
    use Billable;

    protected $guarded = [];

    public function user() {

        return  $this->belongsTo('App\Models\User'); // where customer belongs to user with id
    }

    public function contracts() {

        // get the contracts for this user
        return $this->hasMany(Contracts::class); // example SELECT * contracts where customer_id = this customer
    }
    
}

Then I found that I had to download the migrations for Cashier in the vendor according to this; https://laravel.com/docs/8.x/billing#installation

php artisan vendor:publish --tag="cashier-migrations"

I changed vendor/laravel/cashier/database/migration to customer table.

<?php

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

class CreateCustomerColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('customers', function (Blueprint $table) {
            $table->string('stripe_id')->nullable()->index();
            $table->string('card_brand')->nullable();
            $table->string('card_last_four', 4)->nullable();
            $table->timestamp('trial_ends_at')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('customers', function (Blueprint $table) {
            $table->dropColumn([
                'stripe_id',
                'card_brand',
                'card_last_four',
                'trial_ends_at',
            ]);
        });
    }
}

Also, I updated the vendor/laravel/cashier/config/casher.php

vendor/laravel/cashier/

I also added this to the .env file.

CASHIER_MODEL=App\Models\Customer

I ran migration:fresh and it still has the Cashier items in the user table, not the customer table. Stuck!

Feb
17
1 month ago
Activity icon

Replied to Collecting Payments

I am really new to Laravel, can you point me to where I can learn about adding a trait to a model?

Feb
16
1 month ago
Activity icon

Replied to Collecting Payments

It is a site for shed dealers to create rental contracts. Users create customers and their contracts then they need to take payments for the contracts. Single payment for the initial payment and then if the customer wants it taken out every month a recurring payment needs to be setup.

I had this all working with Authorize.net but then they switched it to Stripe and I am trying to figure out the best route. I started to change it to the customer as being a user type to use Cashier, but then I have to prevent these users from accessing the site. That opened up a whole new complexity. They really aren't meant to be users.

Feb
15
1 month ago
Activity icon

Replied to Collecting Payments

Thanks, but the one-time payment won't work because each transaction will be a different price. Laravel has Cashier, but it seems to rely on a user being set up for each transaction. Is there a way to use Cashier with out having it tied to a user?

Activity icon

Started a new Conversation Collecting Payments

I created a site that has customers. The users create customers and then contracts that belong to the customers. I need to for the users to collect payment (both recurring and single) for the contracts. I am supposed to use stripe. Looking at the stripe documentation it appears that the customers have to be users in order to do that payment. Is there a way to collect payments without a contract without having the customers as users? Hope this makes sense.

Feb
01
2 months ago
Activity icon

Awarded Best Reply on Site Shows Blank Page

It is working now. I not sure why.

Activity icon

Replied to Site Shows Blank Page

It is working now. I not sure why.

Activity icon

Replied to Site Shows Blank Page

Not sure how to check that, but why would what I did change that?

Activity icon

Started a new Conversation Site Shows Blank Page

I just tried to create a development version of my site. It was up and then I copied and pasted the database info from my default version that I was developing on so that I could use that database. I logged in and all was fine. I did notice the name of the App_name was "laravel" so I changed it to my site's name and also change the App_URL to the domain name because it was set to my localhost domain name. Then the page turned blank. I change the App_debug to true but it is still blank.

Jan
26
2 months ago
Activity icon

Started a new Conversation Cannot Get Require_if To Work

I have a radio set and one says new and the other used. When used is selected I want a description box to be required. I have tried just about everything I know.

<div class="field">
                        
     <div class="control radio-control">

      <label class="input-container">New Condition:
               <input type="radio" name="product_condition" id="condition-new" value="new" {{ old('product_condition')=="new"  ? 'checked='.'"'.'checked'.'"' : '' }} required />
     </label>
     </div>

     <div class="control radio-control">

      <label class="input-container">Use Condition:
            <input type="radio" name="product_condition" id="condition-used" value="used" {{ old('product_condition')=="used" ? 'checked='.'"'.'checked'.'"' : '' }} />
                             
            </label>

    </div>
     @error('product_condition')
          <p class="help is-danger">{{ $errors->first('product_condition') }}</p>
     @enderror

   <div class="control" style="margin-top: 18px;">
    <label for="product_condition_description">If used enter description of product:
               <textarea @error('product_condition_description') class="is-danger" @enderror name="product_condition_description" id="product_condition_description" rows="1">{{ old('product_condition_description') }}</textarea>
     </label>
     @error('product_condition_description')
           <p class="help is-danger">{{ $errors->first('product_condition_description') }}</p>
      @enderror
  </div>
</div>

Here is the validation

'product_condition'  => 'required | string',
'product_condition_description' => 'required_if:product_condtion,==,used | string',
Jan
04
3 months ago
Activity icon

Awarded Best Reply on XML URI Namespace Not Absolute

The answer is I had to create the XML like this.

$element = new SimpleXMLElement('<createTransactionRequest/>');

$element->addAttribute('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd');
Activity icon

Replied to XML URI Namespace Not Absolute

The answer is I had to create the XML like this.

$element = new SimpleXMLElement('<createTransactionRequest/>');

$element->addAttribute('xmlns', 'AnetApi/xml/v1/schema/AnetApiSchema.xsd');
Dec
31
3 months ago
Activity icon

Started a new Conversation XML URI Namespace Not Absolute

I am trying to implement Authorize.net payment. I was given a script that sends an XML file through CURL. I was getting an error that the namespace is not absolute when creating the doc. I found that I could fix the error by adding HTTP:// to the namespace. However, when I receive the XML doc back it has the namespace without the HTTP:// and so I get an error. I find that most answers to the XML namespace are just a warning, but in Laravel, it is a 500 error. The error is caught at the simplexml_load_string method.

How I address the first error.

<?xml version="1.0" encoding="UTF-8"?>
        <createTransactionRequest xmlns="http://AnetApi/xml/v1/schema/AnetApiSchema.xsd">

The same error is thrown when I receive the XML.

$content = curl_exec($ch);
                if (FALSE === $content)
                    throw new Exception(curl_error($ch), curl_errno($ch));
                curl_close($ch);
                
                $xmlResult=\simplexml_load_string($content);
Dec
29
3 months ago
Activity icon

Replied to Trying To Create A Webhook

I feel stupid. Thanks

Activity icon

Replied to Trying To Create A Webhook

I sent a request from Postman to a script on one of my sites. I captured the SERVER info and found the [REMOTE_ADDR]. I entered that into my exceptions. It still gives me a page expired.

protected $except = [
        //
        '73.174.232.2',
    ];
Activity icon

Replied to Trying To Create A Webhook

Forge will not let me add SSL to the default site. I did find that if I just add the * to the exception I can get through.

protected $except = [
        //
        '*'
    ];

I am not sure why my URL is not working.

Activity icon

Started a new Conversation Trying To Create A Webhook

I want to use a web service that has a webhook. I am getting a 419 error. I have added my URL to the VerifyCsrfToken.php exceptions. I create a form on one of my sites that sends it to the URL and I get the error.

I have tried using the Postman website. My site is on Forge as the default no SSL. Postman says "Mixed Content Error: The request has been blocked because it requested an insecure HTTP resource." So I can't use that.

I cannot figure out what to do.

Dec
28
3 months ago
Activity icon

Replied to Blade Component Not Getting Var On Forge

It appears that it is a case-sensitive issue. On my Mac using lower case component names is okay, but on Forge it needs to be upper case.

Activity icon

Started a new Conversation Blade Component Not Getting Var On Forge

I have a site working on my local install. I loaded it to forge through github. The site works except for components. It is as if it is not even looking for the component.php.

<label for="product_material">Material:</label> 
                        
<div class="control">

    <select name="product_material" required>
        @foreach($materials AS $material)
            <option value="{{$material->material}}" {{ old('product_material') == $material->material || $slot == $material->material ? 'selected='.'"'.'selected'.'"' : ''   }}>{{$material->material}}</option>
        @endforeach
    </select>

</div>

Here is the component.php

<?php

namespace App\View\Components;

use Illuminate\View\Component;
use DB;

class material extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|string
     */
    public function render()
    {
        $material = DB::table('materials')->get();
       
        return view('components.material',['materials' => $material]);
    }
}

I get an error saying that "Undefined variable: materials."

What is strange is, if I add a dump to the file I get nothing.

 public function render()
    {
        $material = DB::table('materials')->get();
       DD($material);
        return view('components.material',['materials' => $material]);
    }

I would expect it to dump the materials retrieved from the DB. Yet it ignores this. That makes me think it is not even using the PHP component. I used tinker to execute the query and I get the results.

I have three similar components and all behave the same way.

Dec
22
3 months ago
Activity icon

Started a new Conversation Table Plus And Forge

I am trying to get Table Plus connected to my Forge DB. What I cannot figure out are the private keys. I used the string provided in the welcome email. Now Table Plus is asking me to import private keys stored on my computer. Where do I get these keys? All the documentation says is I need keys. All I have received is a public key. What also confuses me is I have GIT, AWS, and Forge. I get confused as to what key belongs to what service. any help would be appreciated.

Dec
21
3 months ago
Activity icon

Started a new Conversation Working With A Site On Forge And AWS

I am lost as this is my first time doing something like this. I set up a server and got my git repository on my Forge site. The site is loaded. However, now I am lost, and after searching, I not even sure I am asking the right questions. How do I use artisan to migrate my tables to the database?

Activity icon

Started a new Conversation Having Problems With Validation Exclude_unless

I have a validation rule that is baffling me.

'product_condition'  => 'required | string',
'product_condition_description' => 'exclude_unless:product_condtion,used | string',

I can echo out the value using old('product_condition'); So I know it is used. Plus the used radio is checked.

It passes not matter what.

<input type="radio" name="product_condition" id="condition-new" value="new" {{ old('product_condition')=="new" || $contract->product_condition == 'new' ? 'checked='.'"'.'checked'.'"' : '' }} required />
 
<input type="radio" name="product_condition" id="condition-used" value="used" {{ old('product_condition')=="used"  || $contract->product_condition == 'used' ? 'checked='.'"'.'checked'.'"' : '' }} />
                        
@error('product_condition')
          <p class="help is-danger">{{ $errors->first('product_condition') }}</p>
@enderror

<textarea @error('product_condition_description') class="is-danger" @enderror name="product_condition_description" id="product_condition_description" rows="1">{{ old('product_condition_description') ? old('product_condition_description') : trim($contract->product_condition_description)}}</textarea>
                           
 @error('product_condition_description')
          <p class="help is-danger">{{ $errors->first('product_condition_description') }}</p>
 @enderror
                   
Dec
02
4 months ago
Activity icon

Started a new Conversation Update Customer Verifying Email

Forcing A Unique Rule To Ignore A Given ID:

I have searched for this and it seems the answer is here; https://laravel.com/docs/8.x/validation#available-validation-rules . But pardon me for being dense but where doest his code go? I put it in my controller and I get an error: Class 'App\Http\Controllers\Validator' not found

use Illuminate\Validation\Rule;

Validator::make($data, [
    'email' => [
        'required',
        Rule::unique('users')->ignore($user->id),
    ],
]);

I also assume that I would need to change 'users' to 'customers' and 'user->id' to 'customer->id'.

Nov
19
4 months ago
Activity icon

Replied to Having Trouble With Ajax Post

When I use $request->json(); I get a 500 error. When I add $request->json('shipping_address'); I get nothing.

Nov
18
4 months ago
Activity icon

Started a new Conversation Having Trouble With Ajax Post

I want to send form data to a controller with ajax. In the controller, I get everything including the headers. I cannot figure out how to deal with it. Shouldn't the Request just pass the variables?

function calc() { // this will capture the form data and return it to a function
        
        var contractForm = $("#contract-form").serialize();
      
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            }
        });
      
        $.post('calculate',contractForm,function(data) {
            console.log(data);
        })

    }

The controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CalcluatorController extends Controller
{
    public function calculate(Request $request) {

       echo $request;
    }
}

Response

POST /contracts/calculate HTTP/1.1
Accept:           */*
Accept-Encoding:  gzip, deflate, br
Accept-Language:  en-US,en;q=0.9
Connection:       keep-alive
Content-Length:   692
Content-Type:     application/x-www-form-urlencoded; charset=UTF-8
Cookie:           XSRF-TOKEN=eyJpdiI6IllVS0w1L2dGR3NQSkdodndUVTB0cGc9PSIsInZhbHVlIjoiRzZzbzZ6OHJZWUFXOTZhdUxERUJGL0I2ZnFlckZkK1NoNXhzdVRIRHE2Z1hSQnNkaURCRkNMOGQ1MXZBSmJGaEltcG1rSnRmWWErSXdYTEJ0OG9TUWZONUNSOVo4NjdnS29sUTM4NnVHVXlILzNyMEt4NDZmNURTSnB0ZnNjcmIiLCJtYWMiOiJmMjkzM2UwYzEwZDY5MzI4ZGY4MGUxNmUzMjU1NmNhMTk5YTkxMTYyODYzYzYzOGVkZTUyMGJjM2FlMmExMzliIn0%3D; bighorn_rental_session=eyJpdiI6IjVZVXhFa25RMTE4emRaT0xpNFVTb3c9PSIsInZhbHVlIjoiLzcwMmRJR1BwRlZBSVd5TTFyMCtkeWsveXNEVFZRRTlqVGZhWWFSUlRkMHRweERPMmpjQ3I0blRZMHRDNkxIdHVZNEV6UVZsaVFVWDUzYUZoYnRIT0tTZ0FMdFlXLzJ0b0pMWWg2T25TcEpuOUtyMHVWMlNFS1NYVkpKbDBzbVgiLCJtYWMiOiJmZDUzOTRiMjlmNzAyOWFkOWZlZDg3ODFlY2FjZmM5OTA4NjczNTkyNDAwMDIwNGMxNDE5YmI1MzgwMThiMGQzIn0%3D
Host:             com.bighornrental:8890
Origin:           https://com.bighornrental:8890
Referer:          https://com.bighornrental:8890/contracts/create
Sec-Fetch-Dest:   empty
Sec-Fetch-Mode:   cors
Sec-Fetch-Site:   same-origin
User-Agent:       Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36
X-Csrf-Token:     lpwGB1sU9QX7uDybnv4M1gLKyy7Cws46dAeZoMNQ
X-Requested-With: XMLHttpRequest
Cookie: XSRF-TOKEN=lpwGB1sU9QX7uDybnv4M1gLKyy7Cws46dAeZoMNQ; bighorn_rental_session=diiATxUX6KdiwLJo6UnzvQ9qN1kskCtvzbvW5RHr

_token=lpwGB1sU9QX7uDybnv4M1gLKyy7Cws46dAeZoMNQ&sales_person=&email=montana%40rocketmail.com&phone=4067502781&secondary_phone=&shipping_address=1205+4th+Ave+S&shipping_city=Great+Falls&shipping_state=MT&shipping_county=MT&shipping_country=USA&reference_name=&reference_phone=&product_size=&product_style=&product_side_colo
Nov
09
5 months ago
Activity icon

Started a new Conversation Laracast On Tenants Gives Me Errors.

I was trying to set up a globalscope to add a where call for companies. I think I did everything just the way I was shown but I get an error that I cannot get past.

I created a scope folder in the app folder with a file names CompanyScope.php

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('short_code', '=', 'MSC');
    }
}

I created a listener named SetCompanyShortCodeInSession

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SetCompanyShortCodeInSession
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        DD(event);
    }
}

Last I added this method to my user method

protected static function booted()
    {
        static::addGlobalScope(new CompanyScope);
    }

The page gives me this error. Class 'App\Models\CompanyScope' not found and the dev bar says this. Class 'App\Models\CompanyScope' not found /Users/mark/Websites/LaravelDashboard2/app/Models/User.php#46

Activity icon

Commented on Tenant Global Scope

I am using Laravel 8 and having problems. I used company instead of tenants. I created a scopes directory with a CompanyScope.php file

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('short_code', '=', 'MSC');
    }
}

I created a listener SetCompanyShortCodeInSession.php

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class SetCompanyShortCodeInSession
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        DD(event);
    }
}

In my user file I added the method

protected static function booted()
    {
        static::addGlobalScope(new CompanyScope);
    }

The dev bar gives this error

Class 'App\Models\CompanyScope' not found
/Users/mark/Websites/LaravelDashboard2/app/Models/User.php#46

The instruction never had me create a CompanyScopes model. I do have a Company model.

Oct
30
5 months ago
Activity icon

Replied to Join Tables Without Mixing Variables

I am really sorry but this is all so new and hard to grasp. I have read and tried but I cannot get it to work.

Here is my model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function  user() {

        return  $this->belongsTo(User::class);
    }

    public function contracts() {

        return $this->hasMany(Contracts::class);
    }
    
}

Here is the method in the Controller:

public function contracts(Customers $customer) {

        return view('contracts.index', ['contracts' =>  $customer->contracts]);
    }

The Route:

Route::get('/customers/{customer}/contracts', [CustomersController::class, 'contracts']);

This gets me all my contracts for a certain customer. Along with these contracts, I need the customer's info. They are connected by foreign keys Contracts/customer_id is associated with Customers/id.

Activity icon

Started a new Conversation Join Tables Without Mixing Variables

I have been following the Laravel from scratch and Jeffery creates a post table with an id. I have created a customer table with an id and a contracts table with an id, but the user table also has an id. So when I request a customer with hasMany contracts I need to include the customer with the query. I use this;

return $this->hasMany(Contracts::class)->leftJoin('customers','customers.id','=','customers_id');

After joining, I DD the results the id is now the customer id and there is no contract id. Normally I would alias the ids so they would not get mixed up. So my question is should I not use the generic id for each table? Or is there a nice way to Join tables in Eloquent without the id's being consolidated?

Activity icon

Replied to HasMany Is Not Getting Results

This is my first use of Laravel and it is a little challenging. I am not that young anymore and it is a little hard to grasp these concepts. Thanks very much.

Oct
29
5 months ago
Activity icon

Started a new Conversation HasMany Is Not Getting Results

I am trying to get a hasMany(Contracts::class) in a customer model. I have an endpoint of; contracts/19

My route looks like this:

Route::get('/contracts/{custoner}', [ContractsController::class, 'show']);

My Customer Model is this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function  user() {

        return  $this->belongsTo(User::class);
    }

    public function contracts() {

        return $this->hasMany(Contracts::class);
    }
    
}

My ContactsController looks like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contracts;
use App\Models\Customers;

class ContractsController extends Controller
{
    //
    public $customers;
    public $user;

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

        $this->customers = new Customers;

    }

    public function index() {

        // All contracts

        $contracts = Contracts::all();

        return view('contracts.index', ['contracts'=> $contracts]);
    }
    
    public function show() {
        
        return view('contracts.show', ['allContracts' => $this->customers->contracts()]);
    }
}

I return zero contracts. I set up my foreign key like this;

$table->foreign('customers_id')->references('id')->on('customers')->onDelete('SET NULL');

I have two contract records that the foreign key customers_id = 19 and a customer with that id.

Oct
22
5 months ago
Activity icon

Started a new Conversation Running A Factory

I was following the Learning Laravel and ran into a problem. It is in factories.

My Factory


namespace Database\Factories;

use App\Customer;
use Illuminate\Database\Eloquent\Factories\Factory;

class CustomerFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Customers::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'first_name' => $faker->firstName,
            'last_name' => $faker->lastName,
            'phone' => $faker->phoneNumber,
            'secondary_phone' => $faker->phoneNumber,
            'email' => $faker->unique()->safeEmail,
            'country' => 'USA',
            'address' => $faker->streetAddress,
            'city' => $faker->city,
            'state' => $faker->state,
            'postal_code' => $faker->postcode,
            'county' => $faker->realText($maxNbChars = 20, $indexSize = 2)
        ];
    }
}

Model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customers extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function testDatabase() {

        $customer = CustomerFactory::factory()->make();
    }
}

In tinker I run this and get an error

>>> factory(App\Customers::class)->create();
PHP Fatal error:  Call to undefined function factory() in Psy Shell code on line 1

How can I run my factory? Thanks for any help.

Oct
20
5 months ago
Activity icon

Started a new Conversation Need Help With CRUD & Ajax

I am a little confused. I see tutorials on Ajax in Laravel and they always start with a new install and I need to include CRUD. It appears it creates a CRUD directory. Is that correct? If so is there a way to install CRUD to an already existing Laravel installation?

Activity icon

Awarded Best Reply on Component Wont Pass Variable

I recreate the component and it worked.

Activity icon

Replied to Component Wont Pass Variable

I recreate the component and it worked.

Oct
19
5 months ago
Activity icon

Replied to Component Wont Pass Variable

This is strange. If I add the var to the x tag then it will display the contents, but it will not pass it. In other words if do this...

<x-delivery_list deliveryList="shed" />

And this

public function __construct($deliveryList = 'Error')
    {

        return $this->$deliveryList = "jack";
    }

What shows in the view is "shed"

Here is the deivery_list.php


namespace App\View\Components;

use Illuminate\View\Component;
use DB;

class delivery_list extends Component
{
    /**
     * Create a new component instance.
     *
     * @return void
     */
   // public $my_new_list;
    public $deliveryList;
    public function __construct($deliveryList = 'Error')
    {

        return $this->$deliveryList = "jack";
    }

    private function get_scheduled_building(){

        $theList;

        $rows = DB::table('orders')->where('status','=',17)->simplePaginate(9);

        foreach($rows AS $row) {
           $theList .= '<li>'.$row->id.'</li>';
        }
        return $theList;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\View\View|string
     */
    public function render()
    {
        return view('components.delivery_list');
    }
}

The component blade, delivery_list.blade.php

<div>
{{ $deliveryList }}
</div>

Use

<x-delivery_list deliveryList="mark" />
Oct
16
5 months ago
Activity icon

Started a new Conversation Component Wont Pass Variable

I was following a tutorial on who to use components. I got it working as a test, but when I went to implement it won't work.

Component Blade: delivery_list.blade.php

  {{$my_new_list}}

Component PHP: delivery_list.php

namespace App\View\Components;

use Illuminate\View\Component;

class delivery_list extends Component
{
   
    public $my_new_list;
    public function __construct()
    {
        $this->my_new_list = 'My code';
    }

}

The Error

Undefined variable: my_new_list (View: /Users/mark/Websites/LaravelDashboard2/resources/views/components/delivery_list.blade.php)