boldstar

boldstar

Member Since 3 Months Ago

Experience Points 2,900
Experience
Level
Lessons Completed 4
Lessons
Completed
Best Reply Awards 0
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

16 Dec
1 day 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 days ago

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

*UPDATE

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

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

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

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

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

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

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

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

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

Here is my workflow

Vue login component

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

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

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

Here is the store action that I am calling

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

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

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

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

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

14 Dec
3 days 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
6 days 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
1 week 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
1 week 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
1 week 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 weeks 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 weeks ago

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

I had to run start-ssh-agent

boldstar started a new conversation Invalid Format Access Denied Public Key Laravel Forge

Hello, I am trying to ssh into my application from the command line however I am having issue with the ssh public key.

1st => I tried using PUTTTY to generate keys and save with appropriate name and extension id_rsa.pub which seem to work great

2nd => I ran this command ~/.ssh/id_rsa.pub to copy key and place it in the ssh key option on the laravel forge dashboard

3rd => I ran ssh [email protected]_id_address and it threw an alarm saying public key access denied

So then I found this website Click Here and followed the steps using the Git Bash command line to generate keys

The command ssh-keygen -t rsa -C "[email protected]" which worked to generate keys however I was unable to create passphrase??

Next I pasted the public key in the laravel forge dashboard

And then I used ssh [email protected] -i ~/.ssh/your-key as suggested and got the following alarm

Load key "/c/Users/username/.ssh/id_rsa.pub": invalid format
[email protected]_ip_address: Permission denied (publickey).

I have seen this as a common issue I guess but no luck with suggested fixes, any help would be greatly appreciated!!!

21 Nov
3 weeks ago

boldstar left a reply on Is There A Way To Return Extra Data With Passport Token?

@D9705996 - My main motivation is a front end package I am using to manage permissions is having issues with retrieving data after token. I was trying to determine if making one response would resolve my issue. Other than that the passport portion works great.

boldstar started a new conversation Is There A Way To Return Extra Data With Passport Token?

So I am using passport to create access tokens, and my question is...

Can I return the User with the access token response?

Here is my login method to get token

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());
        }
    }

and I would like to attach the User the token is created for with the response

return $response->getBody();

say I do a where method using the credentials sent with the token request and try to attach that with the response it will only return $user or vice versa..

$user = User::where('email', $request->username)->get();

return response($response->getBody(), $user);
15 Nov
1 month ago

boldstar left a reply on How To Query Entire Model For Value

Well thanks for the help! I will take the advice.

boldstar left a reply on How To Query Entire Model For Value

@CRONIX - Adding a * solved it. Thank you! any recommended courses on getting better at raw expressions?

boldstar left a reply on How To Query Entire Model For Value

@CMDOBUENO - thank you for the clarity, so it seems to be working as far as CONCAT, however the data returned is only the name object which is created by the CONCAT.

So if I do a search for John It simply returns whatever name matches instead of the entire record like so

{
     name:  'John Smith'
}

Where as it should return the record for John Smith like

{
    first_name: 'John'
    last_name: 'Smith'
    engagements: [
            { engagement: 1},
                { engagement: 1},
                { engagement: 1},
        ]
}

Here is the set up

public function search(Request $request) {

    $client = $request->validate([
        'keyword' => 'required|string'
    ]);
    
    $results = Client::query()
->select(\DB::raw("CONCAT(first_name,' ',last_name) AS name") )       
    ->havingRaw( " name LIKE '%$request->keyword%'")
    ->with('engagements')
    ->get();

    return response()->json($results);
}

I am not sure if I mentioned that I am doing this through ajax if that makes a difference? again thank you for the help!

boldstar left a reply on How To Conditionally Delete Record

@SHUSHKIN - So the method would work, the problem was in my front end code. After a while I realized that the id being collected to delete was incorrect. Now the original method I was using is working correctly however I have modified the code to look like this

 public function destroy(Status $status)
    {
        $statusToDelete = Status::where('id', $status->id)->first();

        $engagements = Engagement::where('workflow_id', $statusToDelete->workflow_id)->get();

        $statusInUse = $engagements->containsStrict('status', $statusToDelete->status);

        if($statusInUse === false) {
            $statusToDelete->delete();
        } else {
            return response('Status Is In Use', 401);
        };

        return response('Status Has Been Deleted', 200);
    }

boldstar left a reply on How To Conditionally Delete Record

*Update

I have switched to try using containsStrict() however it is still having the same issue.

public function destroy(Status $status)
    {
        $statusToDelete = Status::where('id', $status->id)->first();


        $engagements = Engagement::where('workflow_id', $statusToDelete->workflow_id)->get();

        if($engagements->containsStrict('status', $statusToDelete->status)) {
            return response('Status Is In Use', 401);
        };

        $statusToDelete->delete();

        return response('Status Has Been Deleted', 200);
    }

boldstar left a reply on How To Conditionally Delete Record

@shushkin , thank you for the help however my trouble is at this line

foreach($engagements as $engagement) {
            if ($statusToDelete->status === $engagement->status ) {
                return response()->json('Status Is Currently Assigned To Engagements, Please Re-assign Engagements Before Delete', 401);
            }
        };

the if() statement.

boldstar started a new conversation How To Conditionally Delete Record

So I am trying to conditionally delete a record based on if values match or not.

Essentially I retrieve the record of the status I want to delete and compare it to any engagement->status where both have a matching workflow_id.

If it finds that a status is in use I would like to respond with 401

If the record is not in use then delete()

My problem is that It seems to return that the record is in use regardless of if it actually is or not. If that makes sense? I am wondering if my if() statement should be phrased differently?

here is the controller function

 public function destroy(Status $status)
    {
        $statusToDelete = Status::where('id', $status->id)->first();

        $engagements = Engagement::where('workflow_id', $statusToDelete->workflow_id)->get();

        foreach($engagements as $engagement) {
            if ($statusToDelete->status === $engagement->status ) {
                return response()->json('Status Is Currently Assigned To Engagements, Please Re-assign Engagements Before Delete', 401);
            }
        };

        $status->delete();

        return response('Status Has Been Deleted', 200);
    }
14 Nov
1 month ago

boldstar left a reply on How To Query Entire Model For Value

@CMDOBUENO - I gave your method a shot and I get the following alarm

call to member function select() on array

boldstar left a reply on How To Query Entire Model For Value

@CRONIX - Well thanks for the info! I will check out the options provided and see what I can come up with.

I understand the issue of unpredictable conditions I was just throwing out ideas!

boldstar left a reply on How To Query Entire Model For Value

@CRONIX - Well In the instance of Oscar De La Cruz Jr perhaps it would require an if() statement that checks for structure of string? if that is even possible Lol

For instance if given $keyword is more than first_name + last_name run this

Client::where('first_name', 'LIKE', '%'.$keyword.'%')
    ->orWhere('last_name', 'LIKE', '%'.$keyword.'%')
    ->orWhere(...)
    ->get();

boldstar left a reply on How To Query Entire Model For Value

@CRONIX - Yeah so If I send a search $keyword from my search input as John Smith It will look for a record where first_name + last_name matches the given $keyword string...

boldstar left a reply on How To Query Entire Model For Value

@CRONIX - Thanks! I will vote that as best answer for the question however I was wondering...

What if I wanted to do a query where it checks for

first_name + last_name

for instance the $keyword being 'John Smith' or 'Jo Sm'?

boldstar started a new conversation How To Query Entire Model For Value

So I am wondering if there is a way to query a model for values but in a way that it checks the entire model instead of a certain column.

For instance if I use

$client = Client::where('first_name', $request->keyword)->with('engagements')->get();

        return response()->json($client);

It will return any record where the first_name column exactly matches the given $keyword

Or if i use

$client = Client::where('first_name', 'LIKE', '%'.$keyword.'%')->get();

Will return clients where the first_name column is like the the given $keyword

But what if I want it to check more than just the first_name column?

Hopefully what I am asking makes sense...

13 Nov
1 month ago

boldstar left a reply on How To Return Relationship With Created Record

Yes!!! that's what I needed thank you!

boldstar started a new conversation How To Return Relationship With Created Record

Hi, I am trying to return a user with the associated role after I create the new user. I am not sure if this is possible but currently it will return all users with roles because I am using the get() function. Is there a method I can use to only return the newly created user with roles?

Here is the controller currently

public function register(Request $request)
    {

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);

       

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]);

         $user->roles()->attach(Role::where('name', 'Admin')->first());

    $newUser = $user->with('roles')->get(); // here is the line I have an issue with

         return response($newUser, 200);
    }
09 Nov
1 month ago

boldstar left a reply on Eloquent Method Does Not Exist

@D9705996 - Now it makes sense, thank you for the help!

boldstar left a reply on Eloquent Method Does Not Exist

@D9705996 - Okay I'll check it out, I guess I was wondering why it is not

$workflow->statuses()

??

boldstar left a reply on Eloquent Method Does Not Exist

Okay I'll check it out, I guess I was wondering why it is not

$workflow->statuses()

boldstar left a reply on Eloquent Method Does Not Exist

@D9705996 - @d9705996 , I appreciate you taking the time to make your example, however I don't understand this line

$workflow->statuses->each->delete();

How is it accessing the Status table? Also how does it know which statuses to delete?

boldstar left a reply on Eloquent Method Does Not Exist

@SERGIU17 - Looks like it work! Thank you for the help. I'm not sure if this is outside the scope of this discussion but now I am getting an issue with trying to use whereIn()

$workflow->statuses()->**whereIn('workflow_id', $validated['id'])**->delete();

Do I have to iterate over the Status table separately to delete multiple records?

boldstar left a reply on Eloquent Method Does Not Exist

@SERGIU17 - So how can I call statuses()?

boldstar left a reply on Eloquent Method Does Not Exist

@D9705996 - Getting this alarm when I do that

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

I am trying to access the Status table, don't I have to call $workflow->statuses() in order to do that? based off my eloquent model description...

boldstar started a new conversation Eloquent Method Does Not Exist

So I am trying to call a method from my eloquent model however it tells me it doesn't exist. Looking to see if some body could tell me what I am doing wrong. here is the controller

public function updateWorkflowStatuses(Request $request)
    {
    
        // validate form data
        $validated = $request->validate([
            'id' => 'required|integer',
            'statuses' => 'required|array',
        ]);

        $workflow = Workflow::where('id', $validated['id'])->get();

        $statuses = $validated['statuses'];

        $workflow->statuses()->whereIn('workflow_id', $validated['id'])->delete();
       
        foreach($statuses as $status){
            $workflow->statuses()->create([
                'status' => $statuses['status'],
                'order' => $statuses['order']
            ]);
        };

        return response('Update Succesful', 200);

    }

here is the model

class Workflow extends Model
{
    protected $fillable = [
        'workflow'
    ];

    public function statuses()
    {
        return $this->hasMany('App\Status');
    }

    public function engagements()
    {
        return $this->hasMany('App\Engagement');
    }
}
06 Nov
1 month ago

boldstar left a reply on How To Access Values Inside Array To Update Records

Got this solution

$statuses = $oldStatuses['statuses'];
       
        foreach($statuses as $status){
            $workflow->statuses()->where('id', $status['id'])->update([
                'status' =>  $status['status']
            ]);
        };

boldstar left a reply on How To Access Values Inside Array To Update Records

@Cronix, I get this alarm when I try to access value like $status->status

"Trying to get property of non-object"

The array of statuses Is coming from ajax request, when I do return response that is the structure that it shows it as...

boldstar left a reply on How To Access Values Inside Array To Update Records

@munazzil, status() is an undefined function. statuses() is defined on my eloquent Workflow model like so

 public function statuses()
    {
        return $this->hasMany('App\Status');
    }

so thats why I am calling it inside the foreach().. I think I need to access this $status for the status value but I am not sure how...