boldstar

boldstar

Member Since 8 Months Ago

Experience Points 4,370
Experience Level 1

630 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.

06 Apr
1 month ago

boldstar left a reply on How To Debug Package Discovery Error

Never mind I just ran "composer update" and was able to resolve the issue.

boldstar left a reply on How To Mail Exceptions

@TOKOIWESLEY - Thank you for the response, I will give this a shot!

boldstar started a new conversation How To Debug Package Discovery Error

I was attempting to install the sentry for laravel package but in doing so has caused an issue that I am unsure on how to solve. According to this github issue click here I needed to update my laravel/passport package which I did but still having the same issue.

Here is the alarm I get in my command line

In ClassDiscovery.php line 210:

  Unexpected exception when instantiating class.


In Psr17FactoryDiscovery.php line 22:

  No PSR-17 response factory found. Install a package from this list: https://packagist.org/providers/psr/http-factory-implementation


In DiscoveryFailedException.php line 41:

  Could not find resource using any discovery strategy. Find more information at http://docs.php-http.org/en/latest/discovery.html#comm
  on-errors
   - Puli Factory is not available
   - No valid candidate found using strategy "Http\Discovery\Strategy\CommonClassesStrategy". We tested the following candidates: .
   - No valid candidate found using strategy "Http\Discovery\Strategy\CommonPsr17ClassesStrategy". We tested the following candidates:
  Nyholm\Psr7\Factory\Psr17Factory, Zend\Diactoros\ResponseFactory, Http\Factory\Diactoros\ResponseFactory, Http\Factory\Guzzle\Respons
  eFactory, Http\Factory\Slim\ResponseFactory.

Any ideas?

boldstar started a new conversation How To Mail Exceptions

so I am trying to understand how exceptions are thrown and also how I can catch the exception and send to an email. I used an example to build out the basic logic for sending an email when an exception occurs but an email is never sent. So I was wondering if someone could help point me in the right direction.

So if I use a try/catch when creating a new record, and and intentionally try to cause an exception I do this.

 try {
            $data = $request->validate([
                'client_id' => 'required|integer',
                'first_name' => 'required|string',
                'middle_name' => 'nullable|string',
                'last_name' => 'nullable|string',
                'dob' => 'nullable|string',
            ]);
    
            $dependent = Dependent::create($data);
            
            return response($dependent, 201);
        } catch(\Exception $e) {
            return response($e->getMessage(), 422);
        }

So say for instance, the first_name is "required" but I submit my data without the first_name this would throw an exception correct?

If it does throw the exception I want it to do the following in the App\Exceptions\Handler file

public function report(Exception $exception)
    {
        if ($this->shouldReport($exception)) {
            $this->sendEmail($exception); // sends an email
        }

        parent::report($exception);
    }

  public function sendEmail(Exception $exception)
    {
        try {
            $e = FlattenException::create($exception);
    
            $handler = new SymfonyExceptionHandler();
    
            $html = $handler->getHtml($e);
    
            Mail::to('[email protected]')->send(new ExceptionOccured($html));
        } catch (Exception $ex) {
            dd($ex);
        }
    }

But for some reason it does not email the exception stack. Any help would be appreciated.

03 Apr
1 month ago

boldstar left a reply on How To Create Timestamp From Date

@LINDSTROM - well when I try to update my created_at date without using Carbon::parse() it throws an error about trailing data. I am not sure what trailing data is or what about it that carbon does not like.

Ive tried sending the date to be saved as 2 different formats without using carbon

1st

Mon Mar 18 2019 00:00:00 GMT-0500 (Central Daylight Time)

2nd

03/18/2019

my controller without carbon(Doesnt Work)

try {
    $action->created_at = $request->date;
    $action->save();
 } catch(\Exception $e) {
     return response(['message' => $e->getMessage()], 422);
 }    

with carbon(Works)

try {
    $action->created_at = \Carbon\Carbon::parse($request->date)->timestamp;
    $action->save();
 } catch(\Exception $e) {
      return response(['message' => $e->getMessage()], 422);
  }

boldstar left a reply on How To Create Timestamp From Date

@lindstrom , the correct method was Carbon::parse(), the problem was I was passing in the wrong data. Thanks for the help!

Here is the code snippet

\Carbon\Carbon::parse($request->date)->timestamp;
02 Apr
1 month ago

boldstar left a reply on How To Create Timestamp From Date

@JLRDW - thanks for the reply, I am trying to create a time stamp from the date I am sending. Basically I want to over write the created_at date in my database with the new date.

database time stamp looks like

2019-03-19 21:01:00

boldstar started a new conversation How To Create Timestamp From Date

Trying to create a time stamp from date. not sure what I am doing wrong. When I send my date it is in the following format

2019-04-02

I would like to change it to a timestamp like so

2019-04-02 15:25:37

When I try

 Carbon::createFromFormat('Y-m-d' H:m:s, $request->date)->timestamp;

I get the following alarm

"Trailing data"

If i try

Carbon::parse($request->date)->timestamp;

I get the following alarm

Creating default object from empty value"

and lastly i tried the php method strtotime($request->date) which also gave me the same alarm.

Any ideas?

13 Mar
2 months 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
2 months 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
2 months 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
2 months 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 months 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
2 months 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
2 months 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
2 months 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
3 months 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
3 months 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
3 months 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
4 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
4 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
4 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
4 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
4 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
4 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
5 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
5 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