boldstar

boldstar

Member Since 5 Months Ago

Experience Points 3,780
Experience Level 1

1,220 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.

14 Feb
5 days 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
2 weeks 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
2 weeks 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
1 month 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
2 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
2 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
2 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
2 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
2 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!

boldstar started a new conversation How To Dynamically Call Passport Login End Point(oauth/token)

Alright so I am working with a multi-tenant setup and I am looking for a way that when I attempt to request access tokens I can send the request to the correct login end point.

For instance in a single tenant set up when I make a request for a access_token it would look something like this

$http = new \GuzzleHttp\Client;

        try {
            $response = $http->post('http://mydomain.test/oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => env('CLIENT_ID'),
                    'client_secret' => env('CLIENT_SECRET'),
                    'username' => $request->username,
                    'password' => $request->password,
                    ]
                    ]);

                    return response()->getBody();
                }

Now what I am trying to do is make the login end point $http->post(my url) to change depending on the tenant user making the request.

So currently when I make a post request to the login controller I have the route wrapped in a middle ware like this

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

and then in my controller I can call the client secret and the fqdn based on the tenant requesting the information

So when I ask for the fqdn of the request being made and the client_secret from the database of the tenant I will get the correct data

$passport = DB::table('oauth_clients')->where('id', 2)->first(); 

$hostname  = app(\Hyn\Tenancy\Environment::class)->hostname();

now if I insert these variables into the login method I will get an 500 internal server error

public function login(Request $request)
    {
        $passport = DB::table('oauth_clients')->where('id', 2)->first(); 

        $hostname  = app(\Hyn\Tenancy\Environment::class)->hostname();

        $http = new \GuzzleHttp\Client;

        try {
            $response = $http->post('http://' . $hostname->fqdn . '/oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => 2,
                    'client_secret' => $passport->secret,
                    'username' => $request->username,
                    'password' => $request->password,
                    ]
                    ]);

                    return response()->getBody();
                } catch (\GuzzleHttp\Exception\BadResponseException $e) {
                    if ($e->getCode() === 400) {
                        return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
                    } else if ($e->getCode() === 401) {
                        return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
            }
            return response()->json('Something went wrong on the server.', $e->getCode());
        }

    }

Notice the $http->post(my url) changes depending on the tenant user making the request.

Is there something with passport I should be doing so that I can dynamically make the request for the oauth access token??

I have been stuck on this issue for a couple days and any help would be greatly appreciated!!!

11 Dec
2 months ago

boldstar started a new conversation How To Use Passport With Multi-Tenant

I am not sure if anybody on here is familiar with the package hyn/multi-tenant but I am looking for a way that I can have users login to there database based on the tenant they belong too.

So currently what happens when I register a new tenant it creates a database for them. Inside that database contains there passport credentials. the login I was using prior to implementing multi tenancy was this

 public function login(Request $request)
    {
        $http = new \GuzzleHttp\Client;
        try {
            $response = $http->post(config('services.passport.login_endpoint'), [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => config('services.passport.client_id'),
                    'client_secret' => config('services.passport.client_secret'),
                    'username' => $request->username,
                    'password' => $request->password,
                ]
            ]);
            return $response->getBody();
        } catch (\GuzzleHttp\Exception\BadResponseException $e) {
            if ($e->getCode() === 400) {
                return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
            } else if ($e->getCode() === 401) {
                return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
            }
            return response()->json('Something went wrong on the server.', $e->getCode());
        }
    }

However my issue is that laravel needs to know for which tenant the user is trying to access so verifys the correct client_id, client_secret and credentials. Currently with services.passport.end_point , services.passport.client_id and services.passport.client_secret it would automatically assume that there is only one database which is not the case with multi-tenant. Now I pulled some of the following code from a example that and I will walk through the workflow so that you might be able to understand what it is that I am trying to achieve

lets start with route I have in api.php

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

Now the idea here is to make laravel aware of multi-tenancy. so the middleware has been placed in the kernal.php file under routeMiddleware like so

'tenancy.enforce' => \App\Http\Middleware\EnforceTenancy::class,

which calls the EnforceTenancy class that looks like this

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;

class EnforceTenancy
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        Config::set('database.default', 'tenant');
        
        return $next($request);
    }
}

and the [email protected] would be the next step

class TenantAuthController extends Controller
{
    public function login(Request $request)
    {
        $http = new \GuzzleHttp\Client;

        try {
            $response = $http->post('http://aewcpa.tenancyapp.test/oauth/token', [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => '2',
                    'client_secret' => 'tkYkeRWW09VCQkMzxiSSeYAECJLRbCHMhziUMtZl',
                    'username' => $request->username,
                    'password' => $request->password,
                    ]
                    ]);

                    return $response->getBody();
                } catch (\GuzzleHttp\Exception\BadResponseException $e) {
                    if ($e->getCode() === 400) {
                        return response()->json('Invalid Request. Please enter a username or a password.', $e->getCode());
                    } else if ($e->getCode() === 401) {
                        return response()->json('Your credentials are incorrect. Please try again', $e->getCode());
            }
            return response()->json('Something went wrong on the server.', $e->getCode());
        }
    }
}

And its at this point I run into trouble. I get a response that Something went wrong on server. Now as you can see I have hard coded the values from the tenants database so that I can atleast see if it finds anything but also notice the i have fqdn as part of my endpoint url and so I am not sure if this is an issue with guzzle

'http://aewcpa.tenancyapp.test/oauth/token'

aewcpa = fqdn

Obviously this is a lot to digest but any help would be greatly appreciated!!!

boldstar left a reply on Vue Components Not Rendering

@EJDELMONICO - Thank you for the help. Had I read better I would have realized I needed to run npm run dev so it would build the files. However I did take not of the things you pointed out and implemented it. Everything works now. Thank You!!

boldstar started a new conversation Vue Components Not Rendering

Hi, So I am using an example to to learn about multi-tenant architecture and I have hit a road block. My vue components are not rendering when I login into the home.blade.php file. I also don't get any alarms. One thing I have noticed is the structure of the code example I am using has been changed from what comes with laravel but regardless here is what i got

This is the home.blade.php file

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Ticketing System</title>

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

    <!-- Fonts anf CSS -->
    <link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">

</head>
<body>
    <div id="app">

    </div>
</body>
</html>

Here is the app.js file

window.Vue = require('vue');

//Imports
import Vue from 'vue'
import VueRouter from 'vue-router'
import Vuetify from 'vuetify'
import App from '@/App'
import routes from '@/routes.js'

//Load Plugins
Vue.use(VueRouter)
Vue.use(Vuetify)

//Router configuration
const router = new VueRouter({
    routes 
  })

const app = new Vue({
    el: '#app',
    router,
    render: h => h(App),
});

Here is the app.blade.php file

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.js"></script>

    <link href='https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons' rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/vuetify/dist/vuetify.min.css" rel="stylesheet">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui">   

</head>
<body>
    <div id="app">
        <v-app>
            <v-content>
                <v-container>
                    @yield('content')
                </v-container>
            </v-content>
        </v-app>
    </div>

    <script>
      new Vue({ el: '#app' })
    </script>
</body>
</html>

and this is what is in the webpack.mix.js file.

const mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')

mix.webpackConfig({    
    resolve: {      
      alias: {
        '@': __dirname + '/resources/assets/js'      
      },    
    },  
  })

Now This is the structure the /resources directory was changed to

assets: {
        js: {
            api:{},
            components: {},
            config:{},
            app.js,
            App.vue,
            routes.js,
            sidebarLinks.js
        }
},
lang: {},
views: {}

Any help would be greatly appreciated!!

09 Dec
2 months ago

boldstar started a new conversation Remote Database AWS EC2 Instance

So I configured a ec2 instance for my laravel project. I can ssh into the application through the command line with key, however trying to connect remotely from navicat keeps giving me the following alarm

2013 -  Lost connection to MySQL server at 'waiting on initial communication packet'`

From what I found I accessed my database through the command line and use the follwing command

GRANT ALL PRIVILEGES ON *.* TO 'YourUserName'@'%' IDENTIFIED BY "YourPassword"

And then in my ec2 instance I navigated to the security group and opened port "3306" to all for Mysql/Aurora.

Is there some type of configuration I am not doing? From what I research it has something to do with the firewall of the ec2 instance but everything I have tried is not working. I have a separate database I am accessing from navicat with no issues however the application is being hosted at digital ocean..

Any ideas would be greatly appreciated!

07 Dec
2 months ago

boldstar left a reply on How To Concat Or Insert Special Characters On To Query

@talinon , that is exactly what I was looking for! thank you for the help.

boldstar started a new conversation How To Concat Or Insert Special Characters On To Query

So, I am looking for a way that I can insert special characters into my query such as & or a ","(comma) when it is returned

Currently when I do my query like this

$clientName = Client::query()
                    ->select('clients.first_name', 'clients.last_name', 'clients.spouse_first_name' , DB::raw("CONCAT(clients.last_name,' ',clients.first_name,'  ',clients.spouse_first_name) as full_name"))
                    ->where('id', $request->client_id)
                    ->get();

        return response($clientName);

It returns Smith John Jane

But how could I make my returned response be Smith, John & Jane and also to make it more dynamic, if there is no spouse how could I drop the &?

boldstar left a reply on Best Way To Handle Passport Expirations

@zak & @erikverbeek thank you for the suggestions! I will give it a shot and let you know what the results are.

05 Dec
2 months ago

boldstar started a new conversation Best Way To Handle Passport Expirations

So my question is, if I put a time limit on my passort tokens such as

Passport::tokensExpireIn(now()->addDays(1));

What would be the best way to notify the user that there session will be ending soon or that there session has ended?

Just looking for ideas...

28 Nov
2 months ago

boldstar left a reply on Php Artisan Migrate Not Displaying In Remote Database

Im an idiot Lol had go down one level in the database tree. Tables are located under forge =)

boldstar started a new conversation Php Artisan Migrate Not Displaying In Remote Database

Perhaps this is a common issue, with the .env file but when I run php artisan migrate I see it migrate the data tables and when I run my --seed I see it succesfully seed through the command prompt

However when I check my database(connected remotely) and when I use mysql -uforge -p and then do show databases; the migrated tables are not there...

I have checked the git tree which is clean.

What could I be doing wrong or am I not understanding something?

Thanks in advance!

boldstar left a reply on Remote Database Configuration

@petrit, appologies got it figured out. Thank you for the help!!

boldstar left a reply on Remote Database Configuration

@petrit I am now getting alarm saying

`access denied for user '[email protected]_ipaddress'(using password: No)

Where do I set a password?

boldstar started a new conversation Remote Database Configuration

Hello I am having an issue trying to remote into database. I am not sure if it is a setting in forge or if my ssh is incorrect.

when I try to connect I get an error saying 'root'@'localhost' access denied. I am using navicat to connect. Any ideas??

I have been stuck on this issue for a while..

27 Nov
2 months ago

boldstar left a reply on Invalid Format Access Denied Public Key Laravel Forge

I had to run start-ssh-agent