boldstar

boldstar

Member Since 2 Months Ago

Experience Points 1,750
Experience
Level
Lessons Completed 1
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.

14 Nov
16 hours ago

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 day 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
5 days 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 week 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...

05 Nov
1 week ago

boldstar started a new conversation How To Access Values Inside Array To Update Records

Hello, I am trying to use a foreach() loop, to loop through array of objects and update status field with value from array of objects.

Here is my data structure of statuses

[
    {
    id: 1,
    status: receive,\ value I want to update status field
    },
    {
    id: 1,
    status: receive,
    },
    {
    id: 1,
    status: receive,
    },
    {
    id: 1,
    status: receive,
    }
]

Here is the controller

public function workflowStatuses(Request $request, Workflow $workflow)
    {
        // validate form data
        $data = $request->validate([
            'workflow' => 'required|string',
        ]);

            // validate form data
        $statuses = $request->validate([
            'statuses' => 'required|array'
        ]);

        // validate form data
        $newStatuses = $request->validate([
            'newStatuses' => 'required|array',
        ]);
        

        $workflow->update($data);

        foreach($statuses as $status){
            $workflow->statuses()->update([
                'status' =>  $status\ this is the line where I am having issues
            ]);
        };

        $workflow->statuses()->saveMany($newStatuses);
        
        return response($workflow, 200);

        }

I am looking for way to access the status value from my array of objects, anyhelp would be greatly appreciated!

25 Oct
2 weeks ago

boldstar left a reply on FindOrFail Returns Incorrect Value

@thomaskim, thanks for the reply! I was unaware of the actual sql meaning.

boldstar left a reply on FindOrFail Returns Incorrect Value

I ended up switching to this method

$user = User::where('id', $request->assigned_to)->value('name');

boldstar left a reply on How To Mutate Array Of Objects

So I was provided a solution in a different forum.

Here is the link Click

boldstar started a new conversation FindOrFail Returns Incorrect Value

So I'm trying to get the value('name') of a User by there Id. However regardless of what Id I submit with my form it still returns the same value. I am using this method in another controller and it works fine, not sure what I am missing in this situation?

Here is the controller

 public function updateCheckedEngagements(Request $request)
    {

        $engagements = $request->validate([
            'engagements' => 'required|array',
            'assigned_to' => 'required|integer',
            'status' => 'required|string',
        ]);

        $user = User::findOrFail($request->assigned_to)->value('name');

        Engagement::whereIn('id', $request->engagements)->update([ 
            'assigned_to' => $user,
            'status' => $request->status 
        ]);

        $engagements = Engagement::whereIn('id', $request->engagements)->get();
        foreach ($engagements as $engagement) {
            $engagement->tasks()->update([ 
                'user_id' => $request->assigned_to 
            ]);
        };
        
        return response($engagements, 200);
    }

I have done a return response($request->assigned_to) to make sure the id I submit is the correct one and it is..

boldstar started a new conversation How To Mutate Array Of Objects

Hi, I am trying to mutate my array after updating objects with the new values. Currently when I use splice() it has been for only mutating single object. Perhaps I am looking for simple javascript method but I am trying to figure out how mutate array if I am updating multiple objects simultaneously?

This is the store action I am using to commit response.data

updateCheckedEngagements(context, checkedEnagements) {  
      axios.patch('/engagementsarray', {
        engagements: checkedEnagements.engagements,
        assigned_to: checkedEnagements.assigned_to,
        status: checkedEnagements.status
      })
      .then(response => {
          console.log(response.data)
          context.commit('updateCheckedEngagements', response.data)
      })
      .catch(error => {
          console.log(error.response.data)
      })           
    },

here is the mutation I have currently set up but I do not think it is correct

updateCheckedEngagements(state, engagement) {
      const index = state.engagements.findIndex(item => item.id == engagement.id);
      state.engagements.splice(index, 1, {
        'id': engagement.id,
        'assigned_to': engagement.assigned_to,
        'status': engagement.status,
      })
    },

Also since I am passing checkedEngagements as my parameter in the store action, does that also have to be the 2nd parameter for the mutation?

24 Oct
3 weeks ago

boldstar left a reply on Call To A Member Function WhereIn() On Array

@Snapey, getting this alarm which I checked in data base to make sure I have the task and engagement on the engagement_task table prior to running

Here is the alarm

"Method Illuminate\Database\Eloquent\Collection::tasks does not exist."

boldstar started a new conversation Call To A Member Function WhereIn() On Array

Hello, trying to update task that has a belongsToMany() relationship with engagement. Here is the controller currently

public function updateCheckedEngagements(Request $request)
    {

        $engagements = $request->validate([
            'engagements' => 'required|array',
            'assigned_to' => 'required|integer',
            'status' => 'required|string',
        ]);

        $user = User::findOrFail($request->assigned_to)->value('name');

        Engagement::whereIn('id', $request->engagements)->update([ 
            'assigned_to' => $user,
            'status' => $request->status 
        ]);

        Engagement::whereIn('id', $request->engagements)->tasks()->update([ 
            'user_id' => $request->assigned_to 
        ]);

        return response($engagements, 200);
    }

My issue is at this line

 Engagement::whereIn('id', $request->engagements)->tasks()->update([ 
            'user_id' => $request->assigned_to 
        ]);

My tasks() call is referenced in the Engagement model here

public function tasks()
    {
        return $this->belongsToMany('App\Task', 'engagement_task', 'engagement_id', 'task_id');
    }

I am wanting to update each engagement that has task on the user_id field with the $request data...

boldstar left a reply on How To Do Batch Update

@Cronix, my issue was with how I was sending the data. My controller looks like this now. I changed 'engagements.* back to just 'engagements'

public function updateCheckedEngagements(Request $request)
    {

        $engagements = $request->validate([
            'engagements' => 'required|array',
            'assigned_to' => 'required|integer',
            'status' => 'required|string',
        ]);

        $user = User::findOrFail($request->assigned_to)->value('name');

        Engagement::whereIn('id', $request->engagements)->update([ 
            'assigned_to' => $user,
            'status' => $request->status 
        ]);

        Engagement::whereIn('id', $request->engagements)->tasks()->update([ 
            'user_id' => $assigned_to 
        ]);

        return response($engagements, 200);
    }

Everything works now, except for this line of code

 Engagement::whereIn('id', $request->engagements)->tasks()->update([ 
            'user_id' => $assigned_to 
        ]);

I am trying to figure out how I can update the task table that the engagement has a belongsToMany relationship with..

Im trying to use a statement that will do foreach engagement find the task and update the user_id field...

23 Oct
3 weeks ago

boldstar left a reply on How To Do Batch Update

@Cronix, here is how I am sending it currently

  1. When I do the check box it adds the Id's to my v-model
<th scope="row"><input type="checkbox" :value="engagement.id" v-model="checkedEngagements"></th>

Here is the data function

data() {
    return {
      checkedEngagements: [],
      engagement: {
        status: null,
        assigned_to: null,
      },
}

And then I dispatch the store

...mapActions(['updateCheckedEngagements']),
    updateChecked() {
      this.updateCheckedEngagements({
        engagements: this.checkedEngagements,
        assigned_to: this.engagement.assigned_to,
        status: this.engagement.status
      }) 
    },

Which runs this method

updateCheckedEngagements(context, engagement) {
      console.log(engagement)
      axios.patch('/engagementsarray', {
        engagements: engagement.checkedEngagements,
        assigned_to: engagement.assigned_to,
        status: engagement.status,
      })
      .then(response => {
          console.log(response)
          context.commit('updateCheckedEngagements', response.data)
      })
      .catch(error => {
          console.log(error.response.data)
      })           
    },

And when i run the console.log(engagement) it shows all three fields being sent..

assigned_to: 24
engagements: (2) [54, 56, __ob__: Observer]
status: "Scanned"

I'm not sure if this answers your question...

boldstar left a reply on How To Do Batch Update

@Cronix, So when I do that the console.log(response) shows the data as an empty string

data: ""

Which doesn't make sense, how do I pass the validation for an array if it is empty?

boldstar left a reply on How To Do Batch Update

@Cronix, what is the best way to hit the controller to show me the response? Through the browser? or through something like postman? I'm getting weird responses when I placed the dd($request->engagements);

  1. In my browser console it shows me Access-Control-Allow-Origin alarm

boldstar left a reply on How To Do Batch Update

@Cronix, yeah I'm not using foreach() anywhere unless it percieves whereIn() as a foreach?

public function updateCheckedEngagements(Request $request)
    {

        $engagements = $request->validate([
            'engagements.*' => 'required|array',
            'assigned_to' => 'required|integer',
            'status' => 'required|string',
        ]);

        $user = User::findOrFail($request->assigned_to)->value('name');

        Engagement::whereIn('id', $request->engagements)->update([ 
            'assigned_to' => $user,
            'status' => $request->status 
        ]);

        return response($engagements, 200);
    }

boldstar left a reply on How To Do Batch Update

It looks like engagements.* works thanks for the documentation, however now I am getting this error

Invalid argument supplied for foreach()

boldstar left a reply on How To Do Batch Update

@Cronix, do you know why I would be failing when validating

$engagements = $request->validate([
            'engagements' => 'required|array',
        ]);

Even though it is clearly sending the array of Id's with the form-data?

boldstar left a reply on How To Do Batch Update

@Cronix and @anonymouse703 thanks for the help, I am still working on being able to send the correct data to the endpoint. I am not sure if it is my front end(vue) code or if I am doing something incorrectly on the backend(laravel)

This image is showing what I am sending and the response I get from laravel

This is the controller that is processing the request. I am trying to get past the validation of the data. The other issue I have is

  1. How do I loop through the id's and update with the subsequent data?
22 Oct
3 weeks ago

boldstar started a new conversation How To Do Batch Update

I am looking for best practice way of batch updating multiple records based off the ID

Typically if I wanted to update a single record I would send the ID of the record in my API route like this

Here is the ajax request sent from front end

updateCheckedEngagements(context, engagement) {
      axios.patch('/engagements/' + engagement.id, {
        assigned_to: engagement.assigned_to,
        status: engagement.status,
      })
      .then(response => {
          context.commit('updateCheckedEngagements', response.data)
      })
      .catch(error => {
          console.log(error.response.data)
      })           
    },

here is the api route I would use

Route::patch('/engagements/{engagement}', '[email protected]');

But if I am updating multiple engagement.id's at the same time, would the way I receive the data into the controller need to be different?

How can I pass in an array of ID's for Laravel to loop through and update with the subsequent data?

16 Oct
4 weeks ago

boldstar left a reply on Call To A Member Function Where() On Integer

@Snapey, it is not a relation. Perhaps the user could have a relationship with the engagement but it would have to be through the Task model. Atleast that is how I have it described right now. However I've only seen the option for hasManyThrough() and I only need one not many...

  1. I have placed a user_id field on the Task model

  2. I have placed a client_id field on the Engagement model

  3. A User can have many Tasks

  4. A Client can have many Engagements

  5. I have a pivot table set up called engagement_task to create a relationship between the task and engagement

15 Oct
4 weeks ago

boldstar started a new conversation Call To A Member Function Where() On Integer

I am getting alarm when trying to submit data. The data coming in uses the user_id to create a new record of a related model Task. but I would like to use the 'user_id' to pluck() the name off the User table and use that data to insert on the model Engagement for the field assigned_to.

  1. Here is the controller I am using to insert the data
public function store(Request $request)
    {
        $data = $request->validate([
            'client_id' => 'required|integer',
            'return_type' => 'required|string',
            'year' => 'required|string',
            'assigned_to' => 'required|integer',
            'status' => 'required|string',
            'done' => 'required|boolean'
        ]);
        
        $user = $request->assigned_to;
        $userName = $user->where($user, auth()->user()->id)->pluck('name');

        $engagement = Engagement::create([
            'client_id' => $request->client_id,
            'return_type' => $request->return_type,
            'year' => $request->year,
            'assigned_to' => $userName,
            'status' => $request->status,
            'done' => $request->done,
        ]);

        $task = Task::create([
            'user_id' => $request->get('assigned_to'),
            'title' => $request->get('return_type')
        ]);

        $engagement->tasks()->attach($task->id);

        return response($engagement, 201);
    }

The alarm I get when I run the store() method is at this section of the controller

$user = $request->assigned_to;
$userName = $user->where($user, auth()->user()->id)->pluck('name');

This is the alarm

Call to a member function where() on integer

I have not seen much information on this issue so any help would be greatly appreciated..

12 Oct
1 month ago

boldstar left a reply on How To Change Format Of Response Data?

I used this

public function questionindex($client_id)
    {
        $engagements = Engagement::where('client_id', $client_id)->with('questions')->get();

        $questions = $engagements->pluck('questions');

        $flatten = $questions->flatten(1);

        return response($flatten);
    }

it returns a response of questions only like so only belonging to client

[
    {
        "id": 28,
        "engagement_id": 57,
        "question": "This is a new question??",
        "answer": "<p>Why isnt this working?</p>",
        "answered": 1,
        "created_at": "2018-10-05 18:48:48"
    },
    {
        "id": 36,
        "engagement_id": 57,
        "question": "What happens if add a new questions?",
        "answer": "<p>But this doesnot work</p>",
        "answered": 1,
        "created_at": "2018-10-06 14:45:29"
    },
    {
        "id": 37,
        "engagement_id": 65,
        "question": "Just adding a new question?",
        "answer": "<p>So does this work now to?</p>",
        "answered": 1,
        "created_at": "2018-10-06 14:50:10"
    }
]

One array of objects.

boldstar left a reply on How To Change Format Of Response Data?

using this method

public function questionindex($client_id)
    {
        $engagements = Engagement::where('client_id', $client_id)->with('questions')->get();

        return response($engagements);
    }

It will give me a response like this

[
    {
        "id": 63,
        "client_id": 10,
        "return_type": "1040",
        "year": "2018",
        "assigned_to": "Lissa",
        "status": "Recieved",
        "done": 0,
        "created_at": "2018-10-05 21:32:47",
        "updated_at": "2018-10-05 21:32:47",
        "questions": [
            {
                "id": 32,
                "engagement_id": 63,
                "question": "Just testing out the workflow?",
                "answer": null,
                "answered": 0,
                "created_at": "2018-10-05 21:33:08"
            }
        {
                "id": 32,
                "engagement_id": 63,
                "question": "Just testing out the workflow?",
                "answer": null,
                "answered": 0,
                "created_at": "2018-10-05 21:33:08"
            }
        ]
    },

    {
        "id": 63,
        "client_id": 10,
        "return_type": "1040",
        "year": "2018",
        "assigned_to": "Lissa",
        "status": "Recieved",
        "done": 0,
        "created_at": "2018-10-05 21:32:47",
        "updated_at": "2018-10-05 21:32:47",
        "questions": [
            {
                "id": 32,
                "engagement_id": 63,
                "question": "Just testing out the workflow?",
                "answer": null,
                "answered": 0,
                "created_at": "2018-10-05 21:33:08"
            }
        ]
    }
]

is there not a foreach method that will tell it foreach engagement only show questions?

boldstar left a reply on How To Change Format Of Response Data?

@Snapey, yes I guess that's not conventional? without diving to deep into my frontend I am using the Client Id to find the engagements. So I have a view where I am showing questions for the client... Is there not away to constrain the response to only show the nested data?

@D9705996 , I tried it out. Even tried out the has method to, and it would only return the engagement. the whereHas would alarm out on me. Because the Question:: class is not defined on the Model that knows the client_id...

boldstar left a reply on How To Change Format Of Response Data?

@D9705996 , no it gave me the alarm for definingengagement() instead of engagements()

boldstar left a reply on How To Change Format Of Response Data?

@D9705996, no you are correct I have changed it to engagements() and the alarm is from the questions() method. I miss read the alarm.

Client::find($client_id)
   ->engagements()
   ->questions() // error is here
   ->get();

Which also doesn't make sense because I have questions() defined in my Engagement model...

boldstar left a reply on How To Change Format Of Response Data?

@D9705996 , I have the inverse defined I just removed it for the sake of this discussion. However changing the method to engagements() so it matches my Model will return this error

BadMethodCallException: Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::questions() in file C:\laragon\www\traxit\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php on line 50
Stack trace:

boldstar left a reply on How To Change Format Of Response Data?

Okay well I don't think that I do. Here is the model for my Client

class Client extends Model
{
    protected $fillable = 
    [
        'category',
        'referral_type', 
        'first_name', 
        'middle_initial', 
        'last_name', 
        'occupation', 
        'dob', 
        'email', 
        'cell_phone', 
        'work_phone',
        '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', 
    ];

    protected $hidden = ['created_at', 'updated_at'];

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

}

and here is the Engagement model

class Engagement extends Model { protected $fillable = [ 'client_id', 'return_type', 'year', 'assigned_to', 'status', ];

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

}


And on the controller I have only imported `use App\Engagement` can I import `use App\Client` as well?

boldstar left a reply on How To Change Format Of Response Data?

@Snapey, yes. It works fine retrieving the engagements and questions, however I don't need the engagements data for this particular instance so reducing the response to just the questions is my ideal goal...

boldstar left a reply on How To Change Format Of Response Data?

@D9705996, I am using echo because I ONLY want the questions. Perhaps there is a better method for doing that?

@Snapey, 1:many. I use the client_id to know which list of engagements to get, but from the engagements I only want the questions. I dont actually need the engagements data.

  1. Clients hasMany Engagements
  2. Engagements hasMany Questions

No direct relationship between client and questions....

boldstar started a new conversation How To Change Format Of Response Data?

Hello, I am wanting to change the format of a response that I am getting when I do the following in my controller

public function questionindex($client_id)
    {
        $engagements = Engagement::where('client_id', $client_id)->with('questions')->get();
    
        foreach($engagements as $engagement) {
            echo($engagement->questions);
        }

        return response($engagements);
    }

Currently the response is in a unusable format. I would like for it to be a single array of objects. Any suggestions on helpers I can use to make this happen?

here is what the I currently get back

[{"id":32,"engagement_id":63,"question":"Just testing out the workflow?","answer":null,"answered":0,"created_at":"2018-10-05 21:33:08"}][{"id":63,"client_id":10,"return_type":"1040","year":"2018","assigned_to":"Lissa","status":"Recieved","done":0,"created_at":"2018-10-05 21:32:47","updated_at":"2018-10-05 21:32:47","questions":[{"id":32,"engagement_id":63,"question":"Just testing out the workflow?","answer":null,"answered":0,"created_at":"2018-10-05 21:33:08"}]}]

This is what I would like it to be

[
    {
        "id":32,
        "engagement_id":63,
        "question":"Just testing out the workflow?",
        "answer":null,
        "answered":0,
        "created_at":"2018-10-05 21:33:08"
    }

    {
        "id":32,
        "engagement_id":63,
        "question":"Just testing out the workflow?",
        "answer":null,
        "answered":0,
        "created_at":"2018-10-05 21:33:08"
    }

    {
        "id":32,
        "engagement_id":63,
        "question":"Just testing out the workflow?",
        "answer":null,
        "answered":0,
        "created_at":"2018-10-05 21:33:08"
    }
]

boldstar left a reply on How To Do HasManyThrough() Query??

@Cronix, sorry for the late response. I will apply these changes, thanks for the advice!!

11 Oct
1 month ago

boldstar left a reply on How To Do HasManyThrough() Query??

@impbob, well for my use case I actually didn't have to use the hasManyThrough() method at all.

I just did this

 public function index()
    {
        return Task::where('user_id', auth()->user()->id)->with(['engagements', 'engagements.client'])->get();
    }

Adding the engagements.client did the trick.

I found the solution here

10 Oct
1 month ago

boldstar started a new conversation How To Do HasManyThrough() Query??

Hi, so I am trying to retrieve data using the hasManyThrough() relationship and at this point I am able to get a response but the data is missing. Im not sure if it is including the client_id to grab the correct client from the table but im looking for any suggestions. Thanks.

My relationships are 1.Engagement belongsTo Client 2.Client hasMany Engagements 3.Task belongsTo User 4.User hasMany Tasks 5.Tasks belongsToMany Engagements and of course vise versa.

I have a engagement_task pivot table storing the task_id and engagement_id

Now I referenced this article to get going with it link

However mine still looks different, although it is the closest I have gotten to retrieving everything

When I try to mimic the article I will get alarm. If you want to see that let me know or if you have a better suggestion all together let me know..

I will include image at bottom showing what I am currently getting

here is the Pivot model

<?php
namespace App\Pivots;
    
use Illuminate\Database\Eloquent\Relations\Pivot;

class EngagementTask extends Pivot {
    
    
    public function client()
    {
        return $this->hasManyThrough('App\Client', 'App\Engagement');
    }
   
}

here is the Task model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable =
    [
        'user_id',
    ];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function engagements()
    {
        return $this->belongsToMany('App\Engagement', 'engagement_task', 'task_id', 'engagement_id');
    }

    public function client()
    {
        return $this->hasManyThrough('App\Client', 'App\Pivots\EngagementTask', 'engagement_id', 'id', 'id', 'engagement_id');
    }
}

And here is the TasksController that I am using to make the query

public function index()
    {
        return Task::where('user_id', auth()->user()->id)->with(['engagements', 'client'])->get();
    }

boldstar left a reply on How To Update Multiple Tables At The Same Time?

Apologies I think I have figured it out at least my use case. Please comment for better options. Here is my solution

  1. My Task.php did not have the fillable for the user_id
  2. My TasksController was sending a update to all tasks belonging to the user

Now it is set up like this in the Task.php

class Task extends Model
{
    protected $fillable =
    [
        'user_id',
    ];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function engagements()
    {
        return $this->belongsToMany('App\Engagement', 'engagement_task', 'task_id', 'engagement_id');
    }
}

This is the TasksController.php now

public function update(Request $request, Task $task)
    {

        if ($task->user_id !== auth()->user()->id) {
            return response()->json('Unauthorized', 401);
        }

        $data = $request->validate([
            'user_id' => 'required|integer',
        ]);

        $task->update($data);

        $status = $request->validate([
            'status' => 'required|string'
        ]);
        
        $task->engagements()->update($status);

        return response($task, 200);
    }