boldstar

boldstar

Member Since 6 Months Ago

Experience Points 4,170
Experience Level 1

830 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 5
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.

13 Mar
1 week ago

boldstar left a reply on How To Use Mail::setBody() On Build()

@bobbybouwmann , So I ended up going with a hacky option for now, but would be nice for some feedback. I wanted to be able to use templates from database that could render data variables as well. The common way to create a view for a email template is with the view('your_view')->with([ 'data' => $data ]) however because my template would be coming from the database and not from the resources/views directory I had to figure out how I could dynamically render the view from the database and for now I have come to this simple solution. Have not tested in production though

file_put_contents('../resources/views/email.blade.php', $template->html_template)

$template coming from the database.

file_put_contents() will overwrite the current file everytime.

public function build()
{
        $template = EmailTemplate::where('title', 'Status Update')->first();
        file_put_contents('../resources/views/email.blade.php', $template->html_template);

        if($sender->has_spouse == true) {
            $spouse_email = $sender->spouse_email;
            return $this->replyTo($email, $name)
                        ->cc($spouse_email)
                        ->bcc($email, $name)
                        ->subject($template->subject . $account->business_name)
                        ->setBody($template->html_template, 'text/html')
        };
}

boldstar left a reply on How To Use Mail::setBody() On Build()

@bobbybouwmann , yes that method does work, unfortunately I want to access variables that are also stored in the database template, for example {{ $variable }}

I think I am going to attempt to use this package from spatie (https://github.com/spatie/laravel-database-mail-templates)[https://github.com/spatie/laravel-database-mail-templates]

12 Mar
1 week ago

boldstar started a new conversation How To Use Mail::setBody() On Build()

I would like to pass in a custom email template from database and I have seen where you can use setBody() however when I try to do that I get the following alarm

Call to undefined method App\Mail\StartConversation::setBody()

So to send an email I do the following. In my controller try { Mail::to($client->email)->send(new StatusUpdate(['engagement' => $engagement, 'client' => $client]));

        return response()->json(['message' => 'The Contact Has Been Notified']);
    } catch(\Exception $e) {
        $e->getMessage();
    }
And then in my StatusUpdate mailable class

public function build() { $template = EmailTemplate::where('title', 'Status Update')->first();

    if($sender->has_spouse == true) {
        $spouse_email = $sender->spouse_email;
        return $this->replyTo($email, $name)
                    ->cc($spouse_email)
                    ->bcc($email, $name)
                    ->subject($template->subject . $account->business_name)
                    ->setBody($template->html_template, 'text/html')
    };

}


Should I instead pass another parameter in on my controller method `Mail::to`?
11 Mar
1 week ago

boldstar left a reply on How To Loop Through Database Connections

@CRONIX - Thanks for suggestions, I’ll check it out! The only issue I have with it being able to grab the users connection is it requires the “fqdn” which does not work with my current application structure. My front end is on a separate server so in order to determine which fqdn the user belongs to I have to query the tenant databases...

boldstar left a reply on How To Loop Through Database Connections

I ended up using the methods available in the package hyn/multi-tenant to solve my issue. Here is the code.

Note that I placed this code in a custom middleware, and also it is not recommended to use this method for expensive operations, however in this use case I am simply setting the connection based on if the user exists so I feel like it will serve its purpose atleast for now.

 $environment = app(\Hyn\Tenancy\Environment::class);
        $websites = Website::all();
        foreach($websites as $website) {
            $hostname = Hostname::where('website_id', $website->id)->first();
            $environment->tenant($website);
            $user = DB::table('users')->where('email', $request->username)->first();
            if($user) {
                $environment->hostname($hostname);
                Config::set('database.default', 'tenant');
                return $next($request);
            }
        }

        return response('No Such User Exists, Please Try Again', 401);

passing in the $website to the $environement->tenant($website) will set the tenant connection. If a user is found it will continue to my auth controller with return $next($request). If a user does not exist it will return an error.

10 Mar
1 week ago

boldstar started a new conversation How To Loop Through Database Connections

So I am not sure if anybody has worked with multi tenant style applications but I am trying to loop through each of my tenant databases to find a user. I want to change the connection dynamcally using a for loop but when I attempt to do such a thing I get an alarm saying the database connection is not configured.

Here is my code

$websites = Website::all();
        foreach($websites as $website) {
            $connection = DB::connection($website->uuid);
            $user = DB::table('users')->where('email', $request->username)->first();
            if($user) {
                return response()->json($user);
            } else {
                return response('No User');
            }
        }

I've also tried using Config::set instead of DB::connection but no luck. Perhaps there is another way that I can query multiple databases?

08 Mar
2 weeks ago

boldstar left a reply on Package-lock.json Causing Conflicts When Deploying On Laravel Forge

Nevermind I just ssh into server and fixed the merge conflicts. Lol

boldstar started a new conversation Package-lock.json Causing Conflicts When Deploying On Laravel Forge

I am getting the following alarm when try to deploy my recent changes.

* branch            master     -> FETCH_HEAD
   91a3da8..c01f5d1  master     -> origin/master
error: Your local changes to the following files would be overwritten by merge:
    package-lock.json
Please commit your changes or stash them before you merge.
Aborting
Updating 716952a..c01f5d1

This is my current build script

git pull origin master
npm install
composer install --no-interaction --prefer-dist --optimize-autoloader
echo "" | sudo -S service php7.3-fpm reload

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

I have tried multiple ways of getting around this issue but nothing has worked. Any help would be greatly appreciated!

28 Feb
3 weeks ago

boldstar left a reply on How To Only Return Collections Where Array Is Not Empty

@CRONIX - Thats what I needed. I attach the has method after the with and it worked

 return Task::where('user_id', auth()->user()->id)->with(['engagements', 'engagements.client'])->has('engagements')->get();

Thanks!!

boldstar started a new conversation How To Only Return Collections Where Array Is Not Empty

I am attempting to return records with a nested array however I only want the records where the array is not empty. My data structure looks like this

{
    task1: {
        name: "some value",
        random: "another value",
        engagements: [
            { id: 1, text: "some text"},
            { id: 1, text: "some text"},            
        ]
        },
    task2: {
        name: "some value",
        random: "another value",
        engagements: [
            // array is empty           
        ]
    }
}

So when I attempt to retrieve the Task model with engagements like so

$tasks = Task::where('user_id', auth()->user()->id)->with(['engagements', 'engagements.client'])->get();

I would like to then loop through each record and check if the engagements array is empty. If it is empty I want to discard that record. I only want to return records where the enagements array is not empty. Some thing like the following however it is not working properly

$tasks = Task::where('user_id', auth()->user()->id)->with(['engagements', 'engagements.client'])->get();

        foreach($tasks as $task) {
            if($task['engagements']->isNotEmpty()) {
                return $task;
            }
        }

        return response($tasks);
27 Feb
3 weeks ago

boldstar left a reply on How To "Implements" Vendor File

So instead of extending the interface I switch to extending the model. My final code looks like this now

<?php

namespace App\Models\System;

use Illuminate\Database\Eloquent\Model;
use Hyn\Tenancy\Models\Hostname as Contract;
use Laravel\Cashier\Billable;

class Hostname extends Contract
{
    use Billable;

}

boldstar left a reply on How To Properly Implement A Vendor Interface

So instead of extending the interface I switch to extending the model. My final code looks like this now

<?php

namespace App\Models\System;

use Illuminate\Database\Eloquent\Model;
use Hyn\Tenancy\Models\Hostname as Contract;
use Laravel\Cashier\Billable;

class Hostname extends Contract
{
    use Billable;

}

boldstar left a reply on How To Properly Implement A Vendor Interface

@arukomp , thanks for the response! However I run into a couple problems.

1st: When I add the method public function website(): BelongsTo I get the following alarm

Non abstract method must contain body

So I change the method to public function website(): BelongsTo {;} which as you expect then throws an alarm saying

Return value of App\Models\System\Hostname::website() must be an instance of Illuminate\Database\Eloquent\Relations\BelongsTo

Which makes sense because I am not telling it to return anything. Typically when I write a belongsTo method it would look like this

public function website() {
   return $this->belongsTo('Hyn\Tenancy\Contracts\Website');
}

But when I try to do it that way I get this alarm

Declaration of App\Models\System\Hostname::website() must be compatible with Hyn\Tenancy\Contracts\Hostname::website():

2nd: The argument being passed to public function __construct(Hostname $hostname) is not receiving any arguments however I only get this alarm occasionally.. Here is the alarm

Too few arguments to function App\Models\System\Hostname::__construct(), 0 passed in

The file structure looks like this when I get the Too few arguments alarm

namespace App\Models\System;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hyn\Tenancy\Contracts\Hostname as Contract;
use Laravel\Cashier\Billable;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Hostname extends Authenticatable implements Contract
{
    use Billable;

    protected $fillable = [
        'id', 'stripe_id'
    ];

    
    private $hostname;

    public function __construct(Hostname $hostname) {
        $this->hostname = $hostname;
    }

    public function website(): BelongsTo {;}

}

boldstar started a new conversation How To Properly Implement A Vendor Interface

So I am trying to implement a vendor file. I have been looking for something that would give me an idea of what is happening, but perhaps from lack of experience I am unable to make sense.

So this is the vendor file I am looking to implement Hostname.php

namespace Hyn\Tenancy\Contracts;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @property int $id
 * @property string $fqdn
 * @property string $redirect_to
 * @property bool $force_https
 * @property Carbon $under_maintenance_since
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Carbon $deleted_at
 * @property int $website_id
 * @property Website $website
 */
interface Hostname
{
    public function website(): BelongsTo;
}

Now according to there Instructions I can extend there model to a custom model however I am running into an issue with the public function website() method because I beliece I need to concretely instantiate the vendor file but I am unsure how should go about doing this.

  1. Do I need to register a service provider?
  2. What should I do in my custom model file?

This is the current structor of my custom model file


namespace App\Models\System;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hyn\Tenancy\Contracts\Hostname as Contract;
use Laravel\Cashier\Billable;

class Hostname extends Authenticatable implements Contract
{
    use Billable;

    protected $fillable = [
        'id', 'stripe_id'
    ];

    public function __construct(Hostname $hostname) {
        $this->hostname = $hostname;
    }

}

This is the alarm that I am currently getting

Class App\Models\System\Hostname contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Hyn\Tenancy\Contracts\Hostname::website)
26 Feb
3 weeks ago

boldstar started a new conversation How To "Implements" Vendor File

So I am trying to apply a Billable trait to a model. However when I call this model in my controller and attempt to perform a method on it. I get the following alarm.

"Declaration of App\Models\System\Hostname::website() must be compatible with Hyn\Tenancy\Contracts\Hostname::website(): Illuminate\Database\Eloquent\Relations\BelongsTo"

Any ideas?

This is the model file Hostname.php

<?php

namespace App\Models\System;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Hyn\Tenancy\Contracts\Hostname as Contract;
use Laravel\Cashier\Billable;


class Hostname extends Authenticatable implements Contract
{
    use Billable;

    protected $fillable = [
        'id', 'stripe_id'
    ];


    public function website() {
        return $this->belongsTo('Hyn\Tenancy\Contracts\Website');
    }

}

this is the file that it implements

namespace Hyn\Tenancy\Contracts;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * @property int $id
 * @property string $fqdn
 * @property string $redirect_to
 * @property bool $force_https
 * @property Carbon $under_maintenance_since
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Carbon $deleted_at
 * @property int $website_id
 * @property Website $website
 */
interface Hostname
{
    public function website(): BelongsTo;

}

This is the controller where I am attempting to grab the model

public function subscribe(Request $request)
    {
        // $request->validate($request->all());

        $host = Hostname::first();

        $host->newSubscription('main', 'monthly')->create($request->secretToken);

        return response('Success');
    }
14 Feb
1 month ago

boldstar left a reply on How To Save Image As Blob

Update: I have changed the method to this and it seems closer to the acutally base64 image but when I go to decode it, I still can't get the image to render

$account = Account::first();
            $path = $request->file('file')->getRealPath();
            $logo = file_get_contents($path);
            $base64 = base64_encode($logo);
            $account->logo = $base64;
            $account->save();
            return response('success');

boldstar started a new conversation How To Save Image As Blob

So I am trying to use a blob column to store my image. However when I look in the database the data saved does not seem to look right. For example when I look at images that have been encoded to base64 they look quite long. When I check my database I only see this in the blob column.

0x433A5C55736572735C746A2E775C417070446174615C4C6F63616C5C54656D705C706870384332312E746D70

This is the method I am using to save the logo to the database

 public function uploadLogo(Request $request) {

        if (empty($request->file('file')->getRealPath())) {
            return back()->with('success','No file selected');
        }
        else {
            $account = Account::first();
            $logo = $request->file('file')->getRealPath();
            $account->logo = $logo;
            $account->save();
            return response('success');
        }
    }

But when I try to display it in vue It doesn't render anything, which makes me think that I am not saving it to the database correctly. Here is how I am trying to display it in Vue

 <img v-if="accountDetails.logo" v-bind:src="logo" />

computed

logo() {
        return `data:image/jpg;base64, ${btoa(this.accountDetails.logo)}`
      }

Any ideas?

04 Feb
1 month ago

boldstar left a reply on How To Change From Address On Mail Dynamically

Thanks all for the responses. Yes I was trying to use gmail to send emails and it is true that they override whatever value you have set with default values. It can be changed in gmail but you will have to register each individual email you want to use as a sender and this is not dynamic so not worth trying. However thank you for the help.

@snapey , thanks for the advice on the auth()->user() so I can just call ('id', id) instead?

and @aurawindsurfing , I did use the mailable class. I pass in the data like so however the user was queried on the StartConversation class and not passed in as data attribute.

Perhaps there is a better way to do this but I call a sendMail() function in my controller like this

public function sendMail(Request $request)
    {
        $data = $request->validate([
            'id' => 'required|integer'
        ]);

        $question = Question::where('id', $request->id)->first();
        $engagement = Engagement::where('id', $question->engagement_id)->first();
        $client = CLient::where('id', $engagement->client_id)->first();

        Mail::to($client->email)->send(new StartConversation(['question' => $question, 'engagement' => $engagement, 'client' => $client]));

        $question->email_sent = true;
        $question->save();

        return response()->json([ 'question' => $question, 'message' => 'Email Was Sent']);
    }

which calls the StartConversation mailable class

 /**
     * The demo object instance.
     *
     * @var Client
     */
    public $client;
 
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($client)
    {
        $this->client = $client;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {   
        $account = Account::first();
        $sender = User::where('id', auth()->user()->id)->first();
        $email = $sender->email;
        $name = $sender->name;

        return $this->from($email, $name)
                    ->replyTo($email, $name)
                    ->bcc($email, $name)
                    ->subject('Pending Questions From '. $account->business_name)
                    ->view('email')
                    ->with([
                        'phoneNumber' => $account->phone_number,
                        'faxNumber' => $account->fax_number,
                        'accountName' => $account->business_name,
                        'accountEmail' => $account->email,
                        'userEmail' => $email
                    ]);
    }
}
31 Jan
1 month ago

boldstar started a new conversation How To Change From Address On Mail Dynamically

So I am sending mail from my application and I want to change the from email address and name dynamically. I see that you can use a global setting in the config file but that will not do what I am looking for.

So here is where I am adding the from address dynamically but when the email is sent it does not use the $email property in the from($email, $name). However thereplyTo` works fine. What could I be doing wrong?

As you see below I want the from address to be from the user making the send email request...

$sender = User::where('id', auth()->user()->id)->first();
        $email = $sender->email;
        $name = $sender->name;

        return $this->from($email, $name)
                    ->replyTo($email, $name)
                    ->subject('Pending Questions From '. $name)
                    ->view('email');

boldstar left a reply on How To Handle HTML Sent To Email Template Dynamically

@GRENADECX - so sorry, I wasn't removing a set of the { } which is why it was wrapping like an object lmao you were correct!

boldstar left a reply on How To Handle HTML Sent To Email Template Dynamically

@GRENADECX - thanks for reply! I actually tried that and when I receive the email it looks like this

{
    this is a question
}

it wraps the question like its an object. Am i missing something?

boldstar started a new conversation How To Handle HTML Sent To Email Template Dynamically

So I am sending emails and the text for body of the email template is coming in as html. To paint a better picture I will try to layout what is happening.

I make a request to send an email

public function send($question)
    {
        $engagement = Engagement::where('id', $question->engagement_id)->first();
        $client = CLient::where('id', $engagement->client_id)->first();

        $testUser = ['email' => '[email protected]'];

        Mail::to($testUser['email'])->send(new StartConversation(['question' => $question, 'engagement' => $engagement, 'client' => $client]));

        return response('Email Was Sent');
    }

I then access these properties in my email template. the $question array contains the actual question that is wrapped in html like so

question: [
    {
        question: '<p>this is a question</p>'
    }
]

So when I display this question property in my email.blade.php template it looks like this

<p>this is a question</p>

But I would like for it to look like this

this is a question

How can I turn the question into a string? or remove the html tags?

04 Jan
2 months ago

boldstar left a reply on Best Way To Track And Store Database Model Events

@DALMA - thank you for the response and @cobs thank you for the response! It looks like I am just going to try spatie/laravel-activitylog but I appreciate the advice!

boldstar started a new conversation Best Way To Track And Store Database Model Events

This is a general question, just looking for best available options or ideas on tracking and storing the data changes on certain models or all models for that matter.

Lets say I have eloquent model called Engagement and I would like to have a database table that stores the events that take place on this model. The columns on the data table would be something like timestamps, user, event, engagement_id, so e.g( A user, updated, the engagement_id, at timestamps), OR ( A user, deleted, the engagement_id, at timestamps)

My question is are the packages available I could install to track and store this kind of thing OR would it be better to just code it myself with no packages?

My next question is, if I wanted to implement a way to run reports on this data are there any packages I should consider for doing that or would it be better to just code it myself?

Thanks in advance!

02 Jan
2 months ago

boldstar left a reply on How To Change Date Format Using Carbon

@CRONIX - sorry for the late response!

so I am still having issues. I changed my method to just pull one record with the parse method and it returns an error. Now prior to trying to parse the dob I made sure that I was at least returning the record return $dob; and it just obviously returns the database format of yyyy-mm-dd So here is the method currently with trying to parse to format d/m/y

$dob = Client::select('dob')->where('id', 9);
       
$formatedDOB = \Carbon\Carbon::parse($dob)->format('d/m/y');
         
return $formatedDOB;

boldstar left a reply on How To Change Date Format Using Carbon

@ITSRICKY - thank you for the reply! yeah so I gave that a shot as well and it returns the original format of dd-mm-yy hh:mm:ss

which is also what I got be trying to return the value as well in the foreach Ill keep playing around with it!

boldstar left a reply on How To Change Date Format Using Carbon

@S4MUEL - Thanks for the reply! I am not exactly sure what you mean but I assumed you meant something like this?

foreach($clients as $client) {
 \Carbon\Carbon::createFromFormat('d/m/y', $client->dob);
};

boldstar started a new conversation How To Change Date Format Using Carbon

so I am looking for a way that I can transform the date format when exporting. I am using the maatwebsite/excel package. when importing the dates are changed to the following format dd-mm-yyyy hh:mm:ss which is fine for storing but when exporting I am trying to change the format to d/m/y however what I have tried doesn't seem to do anything. Im pretty sure I am missing something.

Here is the ClientsExport.php file

<?php

namespace App\Exports;

use App\Models\Tenant\Client;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ClientsExport implements FromQuery, WithHeadings
{
    /**
    * @return \Illuminate\Support\Query
    */
    public function query()
    {
        $clients = Client::select(
            'active',
            'category',
            'referral_type', 
            'first_name', 
            'middle_initial', 
            'last_name', 
            'occupation', 
            'dob', 
            'email', 
            'cell_phone', 
            'work_phone',
            'has_spouse',
            'spouse_first_name', 
            'spouse_middle_initial', 
            'spouse_last_name', 
            'spouse_occupation', 
            'spouse_dob', 
            'spouse_email', 
            'spouse_cell_phone', 
            'spouse_work_phone', 
            'street_address',
            'city',
            'state',
            'postal_code',
            'created_at',
            'updated_at'

        );

        foreach($clients as $client) {
            return \Carbon\Carbon::createFromFormat('d/m/y', $client->dob);
        };

        return $clients;
    }

    public function headings(): array
    {
        return [
            'active',
            'category',
            'referral_type', 
            'first_name', 
            'middle_initial', 
            'last_name', 
            'occupation', 
            'dob', 
            'email', 
            'cell_phone', 
            'work_phone',
            'has_spouse',
            'spouse_first_name', 
            'spouse_middle_initial', 
            'spouse_last_name', 
            'spouse_occupation', 
            'spouse_dob', 
            'spouse_email', 
            'spouse_cell_phone', 
            'spouse_work_phone', 
            'street_address',
            'city',
            'state',
            'postal_code',
            'created_at',
            'updated_at'
        ];
    }
}

notice the

foreach($clients as $client) {
            return \Carbon\Carbon::createFromFormat('d/m/y', $client->dob);
        };
24 Dec
2 months ago

boldstar left a reply on Laravel Cors Issue On Production Server(NGINX)

the issue was with laravel forge config file. because I am making requests to subdomains on the server and not just the main domain, I had to tell the server to accept requests to subdomains. in the nginx config file I added *.myurl.com and it resolved the alarm 301 permanently moved. So even though in the console it said it was a cors issue it was with the server and not the cors package.

boldstar left a reply on Laravel Cors Issue On Production Server(NGINX)

@BOBBYBOUWMANN - thanks for help! My issue actually ended up being with nginx config file on laravel forge. I was getting a 301 permanently moved alarm because the server was only set up to listen for requests to my main domain myurl.com. once I added *.myurl.com for wildcard subdomains it resolved my issue.

boldstar left a reply on 301 Moved Permanently

@XEWL - @xewl , thanks for the help. this post is kind of screwed up because what I originally posted I solved right after and was attempting to acutally delete the post which I guess I can't. so I had to add *.myurl.com to the nginx config file on laravel forge. Which actually ended up not really being a cors package issue and just a configuration isssue on the server. I am ussing spatie/laravel-cors. Once I added the wild card subdomain it fixed the 301 redirect.

23 Dec
2 months ago

boldstar started a new conversation 301 Moved Permanently

So I am trying to solve a cors redirect issue. It has something to do with origin is not the same as the redirect so it returns an alarm. I have read that you can modify the nginx.conf file to handle this issue but still no luck. here is the command I am running

 curl -s -D - -H "Origin: https://aewcpa.traxit.io" -X OPTIONS https://aewcpa.traxit.pro/api/account -o /dev/null

and this is the response I get

HTTP/1.1 301 Moved Permanently
Server: nginx/1.15.6
Date: Mon, 24 Dec 2018 01:04:45 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
Location: https://traxit.pro/api/account

I have changed the nginx.conf file on laravel forge to look like this

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/traxit.pro/before/*;

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name traxit.pro;
    return 301 https://aewcpa.traxit.pro$request_uri;
    root /home/forge/traxit.pro/public;

    # FORGE SSL (DO NOT REMOVE!)
    ssl_certificate /etc/nginx/ssl/traxit.pro/463036/server.crt;
    ssl_certificate_key /etc/nginx/ssl/traxit.pro/463036/server.key;

    ssl_protocols TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_dhparam /etc/nginx/dhparams.pem;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.html index.htm index.php;

    charset utf-8;

    # FORGE CONFIG (DO NOT REMOVE!)
    include forge-conf/traxit.pro/server/*;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
        
        if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
         }
         if ($request_method = 'POST') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
         }
         if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
         }
    }

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

    access_log off;
    error_log  /var/log/nginx/traxit.pro-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

# FORGE CONFIG (DO NOT REMOVE!)
include forge-conf/traxit.pro/after/*;

The reason I am trying to solve this issue is because any request I attempt to make from my frontend application throws this alarm

Access to XMLHttpRequest at 'https://aewcpa.traxit.pro/api/account' from origin 'https://aewcpa.traxit.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I have tried the spatie/laravel-cors package and the barryvdh cors package with nothing changed. I referenced this laracasts discussion for help about solving the 301 issue however like I said still no luck

I am throwing darts until something sticks because this issue is rather out of my league. If anybody has a solution for this I would greatful forever Lol

boldstar left a reply on Laravel Cors Issue On Production Server(NGINX)

@ZEROHOUR - yes I have. I have tried just about every solution I can find on the internet with no success yet. Thank for the help though!

21 Dec
3 months ago

boldstar started a new conversation Laravel Cors Issue On Production Server(NGINX)

I am running into an issue on my production server that did not come about when running things locally. I have a separate front end making requests to my laravel backend. I installed the the spatie/laravel-cors package to handle cors and like I said locally it works fine. Once I loaded it to my digital ocean droplet using forge I started getting this alarm

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I am not sure how I can trouble shoot this issue and I have tried every option I can find available. Desperate for a solution.

here is the cors.php configu file

<?php

return [

    /*
     * A cors profile determines which origins, methods, headers are allowed for
     * a given requests. The `DefaultProfile` reads its configuration from this
     * config file.
     *
     * You can easily create your own cors profile.
     * More info: https://github.com/spatie/laravel-cors/#creating-your-own-cors-profile
     */
    'cors_profile' => Spatie\Cors\CorsProfile\DefaultProfile::class,

    /*
     * This configuration is used by `DefaultProfile`.
     */
    'default_profile' => [

        'allow_credentials' => false,

        'allow_origins' => [
            'https://*.myurl.com',
        ],

        'allow_methods' => [
            'POST',
            'OPTIONS',
            'GET',
            'PUT',
            'PATCH',
            'DELETE',
        ],

        'allow_headers' => [
            'Content-Type',
            'X-Auth-Token',
            'Origin',
            'Authorization',
        ],

        'expose_headers' => [
            'Cache-Control',
            'Content-Language',
            'Content-Type',
            'Expires',
            'Last-Modified',
            'Pragma',
        ],

        'forbidden_response' => [
            'message' => 'Forbidden (cors).',
            'status' => 403,
        ],

        /*
         * Preflight request will respond with value for the max age header.
         */
        'max_age' => 60 * 60 * 24,
    ],
];

I tried allow origins like this as well

  'allow_origins' => [
            '*',
        ],

but still no luck.

any help would be greatly appreciated!!

boldstar started a new conversation Laravel Cors Issue On Production Server(NGINX)

So I have project using the spatie/cors package, and on my local machine it works fine, but on my production server any request I make by api returns a 301 alarm, and this message

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

The application is actually hosted by Digital Ocean, and I am wondering if anybody has had any issues with this set up on nginx server, and what I should do about it?

boldstar left a reply on Your Local Changes To The Following Files Would Be Overwritten By Merge

@NAKOV - thank you for the help! moving npm run production to my local enviroment did solve my issue.

20 Dec
3 months ago

boldstar started a new conversation Your Local Changes To The Following Files Would Be Overwritten By Merge

I am a little confused on how I should manage this alarm. I a made some changes that i then pushed to my git directory. But when I attempt to deploy my site I get the following alarm

Fri Dec 21 04:22:08 UTC 2018
From github.com:my working directory
 * branch            master     -> FETCH_HEAD
error: Your local changes to the following files would be overwritten by merge:
    public/css/app.css
    public/js/main.js
Please commit your changes or stash them before you merge.
Aborting
Updating c2c9380..96ccc95

this is the deploy script

git pull origin master
npm install
npm run production
composer install --no-interaction --prefer-dist --optimize-autoloader
echo "" | sudo -S service php7.3-fpm reload

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

What do I need to do so it forces the merge? Why does it throw this alarm?

boldstar left a reply on Patch Request Not Receiving Data

@prasadchinwal5 , actually after taking a break I realized that prior to submitting the request to update, I was not properly accessing the data from my vue compenent

e.g

before submitting request i was attempting to access data like this

this.data.whatever

needed to be

this.data[0].whatever

However I appreciate the help!

19 Dec
3 months ago

boldstar started a new conversation Patch Request Not Receiving Data

So I am trying to update a record with a past request. I have read that if you are facing this issue that you should spoof the request with _method attached in the headers however I am still facing an issue, perhaps I am doing something wrong still?

Here is my axios request

updateCompanyAccount(context, account) {

        axios.defaults.headers.post = {
            '_method': 'PATCH',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        console.log(axios.defaults.headers)
        axios.post('/companyAccount/' +account.uuid, {
            business_name: account.business_name,
            email: account.email,
            phone_number: account.phone_number,
            fax_number: account.fax_number,
            address: account.address,
            city: account.city,
            state: account.state,
            postal_code: account.postal_code
        })
        .then(response => {
            console.log(response.data)
            context.commit('successAlert', response.data.message)
        })
        .catch(error => {
            console.log(error.response.data)
        })
    },

Here is the web.php route

Route::patch('/companyAccount/{uuid}', 'System\[email protected]')->name('companyAccount');

Here is the controller

public function updateCompanyAccount(Request $request, $uuid)
    {
        return response($request);

        $account = DB::table($uuid . '.accounts')->firstOrFail();

        $data = $request->validate([
            'business_name' => 'required|string',
            'email' => 'required|string',
            'phone_number' => 'required|string',
            'fax_number' => 'required|string',
            'address' => 'required|string',
            'city' => 'required|string',
            'state' => 'required|string',
            'postal_code' => 'required|string',
            'subscription' => 'required|string'
        ]);

        $account->update($data);

        return response('Update Was Succesful', 200);
    }
18 Dec
3 months ago

boldstar left a reply on Deleting Records With Many To Many Relationship

Alright so because I am only assigning 1 task to an engagement at a time i just called the tasks associated with the engagement and then delete it after the engagement.

I may want to just describe this relation differently but for not this works

/**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Engagement $engagement)
    {
        $task = $engagement->tasks()->first();

        $engagement->delete();

        $task->delete();

        return response('Engagement Is Deleted', 200);
    }

boldstar left a reply on Deleting Records With Many To Many Relationship

@LOSTDREAMER_NL - With the listener I am facing the alarm

"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`b8f19d329b3d4fadbf13b862453ea8a9`.`engagement_task`, CONSTRAINT `engagement_task_task_id_foreign` FOREIGN KEY (`task_id`) REFERENCES `tasks` (`id`)) (SQL: delete `tasks` from `tasks` inner join `engagement_task` on `tasks`.`id` = `engagement_task`.`task_id` where `engagement_task`.`engagement_id` = 4)"

Which is weird because when I first set up this relationship, I could delete records for engagement and task with no issue. The Task model has a user_id field on it and I am not sure if maybe that is what is causing my issue. My models look like this

Engagement.php

boldstar left a reply on Deleting Records With Many To Many Relationship

@lostdreamer_nl , thanks for the help!

so I thought I had configured it to cascade onDelete in the migration file?

   $table->integer('engagement_id')->unsigned();
            $table->foreign('engagement_id')->references('id')->on('engagements')->onDelete('cascade');

Should I put this on the task column as well?

i will give your other option a shot and see what happens

boldstar left a reply on How To Dynamically Call Passport Login End Point(oauth/token)

@SADNUB - thank you for the response! sorry for the late reply Lol

so I actually figured it out for using my original setup prior to seeing your response. In the tenancy documentation there is a way for forcing the connection, which forwhatever reason does not happen for all instances if with EnforceTenancy middleware..

I placed this method

$env = app(Environment::class);

        if ($fqdn = optional($env->hostname())->fqdn) {
            config(['database.default' => 'tenant']);
        }

In the boot() method of the AppServiceProvider file and it worked like a charm

My route setup to login looks like this

Route::group(['middleware' => 'tenancy.enforce'], function () {
    Route::post('/login', 'Tenant\[email protected]');
});

I am still doing some testing right now but so far it seems to be working as expected. Thank you for the help though!!

boldstar started a new conversation Deleting Records With Many To Many Relationship

So I have models with the following relationship

  1. Engagements belongsToMany Tasks
  2. Tasks belongsToMany Engagements

I have pivot table setup to create a relationship between these 2 models

{
        Schema::create('engagement_task', function (Blueprint $table) {
            $table->integer('task_id')->unsigned();
            $table->foreign('task_id')->references('id')->on('tasks');
            $table->integer('engagement_id')->unsigned();
            $table->foreign('engagement_id')->references('id')->on('engagements')->onDelete('cascade');
        });
    }

Now when I call to delete my Engagement record I want to also delete the Task related to it however using the following method it only removes the Engagment record from the engagements table and the Relationship record on the pivot table

public function destroy(Engagement $engagement)
    {
        $engagement->delete();

        return response('Engagement Is Deleted', 200);
    }

How can I also delete the matching Task on my tasks table?

16 Dec
3 months ago

boldstar left a reply on Submitting Post Request From Vue Throwing MethodNotAllowedException

So actually had nothing to do with vue, I had to prefix the routes with web

Route::prefix('web')->group(function () {
    Route::post('/login', '[email protected]');
});

Thank you for the help though!

15 Dec
3 months ago

boldstar left a reply on Submitting Post Request From Vue Throwing MethodNotAllowedException

*UPDATE

I have added csrf-token headers to my axios post however still no luck. My store.js file currently looks like this

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)
axios.defaults.baseURL = 'http://multitenant-diy.test/web'
const token = document.head.querySelector('meta[name="csrf-token"]');
axios.defaults.headers.common['header1'] = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN': token.content
}

export default new Vuex.Store({
  actions: {
    login(context, credentials) {
        axios.post('/login', {
            username: credentials.username,
            password: credentials.password
        })
        .then(response => {
            console.log(response.data);
            context.commit('loggedIn', response.data)
        })
        .catch(error => {
            console.log(error.response.data)
        })
    }
  }
})

boldstar left a reply on Submitting Post Request From Vue Throwing MethodNotAllowedException

@MATTSPLAT - well I gave that a shot but no change. However I don't think that the order matters in the web.php file?

boldstar started a new conversation Submitting Post Request From Vue Throwing MethodNotAllowedException

So I changed my set up to use vue for my views and I am attempting to make a login post request which is returning an alarm

exception: "Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException",

Here is my workflow

Vue login component

<template>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card card-default">
                    <div class="card-header">
                        Login
                    </div>

                    <div class="card-body">
                    <form @submit.prevent="login">
                        <input type="text" v-model="username" class="form-control mb-3" placeholder="Email">
                        <input type="password" v-model="password" class="form-control mb-3" placeholder="Password">
                        <div>
                            <button type="submit" class="btn btn-primary btn-block">Login</button>
                        </div>
                    </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'login',
        data() {
            return {
                username: '',
                password: ''
            }
        },
        methods: {
            login() {
                this.$store.dispatch('login', {                    
                    username: this.username,
                    password: this.password
                })
            }
        }
    }
</script>

Here is the store action that I am calling

actions: {
    login(context, credentials) {
        axios.post('/login', {
            username: credentials.username,
            password: credentials.password
        })
        .then(response => {
            context.commit('loggedIn', response.data)
        })
        .catch(error => {
            console.log(error.response.data)
        })
    }
  }

which I want to then send to my web.php routes however I think this is where I am running into my issue

Route::domain('multitenant-diy.test')->group(function () { 
    Route::get('/{any}', '[email protected]')->where('any', '.*');
    Route::post('/login', 'Auth\[email protected]');
});

which is supposed to then call the standard login controller that comes with the auth scaffolding...

Can you make a post request from vuex to the web.php file?

14 Dec
3 months ago

boldstar left a reply on Auth()->user() Returns Null Using Passport As Authentication

Well after changing the api.php file from

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();

   
    Route::post('/logout', '[email protected]');
});

To this

Route::group(['middleware' => 'auth:api'], function () {
    Route::post('/logout', '[email protected]');
    Route::get('/todos', '[email protected]');
});

I was able to load the current user. I am not sure why it was unable to use return $request->user(); but for now this is my workaround.

boldstar started a new conversation Auth()->user() Returns Null Using Passport As Authentication

So I am using passport to create access tokens. Now previously I was struggling to create access tokens on a per tenant basis which has now been solved. The next step was to destroy token when logging out but when I do dd(auth()->user()) the result returned is null I have changed the auth.api file to use

'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],

I access my logout right like so

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();

   
    Route::post('/logout', '[email protected]');
});

and then use this method in controller

    public function logout()
    {   
        dd(auth()->user());

        auth()->user()->tokens->each(function ($token, $key) {
            $token->delete();
        });

        return response()->json('Logged out successfully', 200);
    }

and help would be greatly appreciated!