Home > Software design >  Cannot access offset of type string on string while trying to access an array in an object in larave
Cannot access offset of type string on string while trying to access an array in an object in larave

Time:10-15

i am a bit confused as i have tried what i understand about fetching an item in an array in an object .

let me break down

in my client endpoint

 $client=Client::where('id',$client)->firstOrFail();

 $arr = json_decode($client->attributes);

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

when i return like this

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

i get

{
    "full_details_acknowledgement": "10",
    "offer_letter_acknowledgement": "10",
    "offer_letter": "10",
    "offer_letter_variables": [
        "basic_salary",
        "housing_allowance",
        "transport_allowance",
        "meal",
        "entertainment",
        "hazard_allowance",
        "leave_allowance",
        "utility",
        "monthly_gross_salary",
        "statutory_deductions",
        "employee_pension",
        "payee_tax",
        "total_deductions",
        "net_monthly_salary",
        "austin"
    ],
    "company": "global-manpower"
}

i am trying to get the values of offer_letter_variables and safe them in a variable

like this , this is also what i have tried

foreach ($client->attributes['offer_letters_variables'] as $variable){
           
            $offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );

        }

but if i try it as the above i have the error

"message": "Cannot access offset of type string on string"

heres a full view of my code(i commented out some parts)

 public function submitSingleUploadCandidates($client,Request $request){
       
        $request->validate([
            'job_role_id'=>'required',
            'mail_template_id'=>'required',
            'first_name'=>'required',
            'last_name'=>'required',
            'user_type'=>'required',
            'email'=>'required',
        ]);
        
        $job_level=JobLevel::find($request->job_level_id);

        $job_role=JobRole::findOrFail($request->job_role_id);

        $mail_template=MailTemplate::findOrFail($request->mail_template_id);

        $client=Client::where('id',$client)->firstOrFail();

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

        // $arr = json_decode($client->attributes);

        //dd($client);
        // return response()->json(gettype($arr));
        // return response()->json($arr);

        $offer_letters_variables=collect([]);
        
      //return response()->json($offer_letters_variables);
        
        // $var = $client->attributes[''];
        
        // dd($var);
        
        
        foreach ($client->attributes['offer_letters_variables'] as $variable){
           
            $offer_letters_variables->put($variable,isset($request->{$variable}) ? $request->{$variable} : 0 );

        }

        $attr=collect(['offer_letter_variables'=>$offer_letters_variables]);

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

        
        
        if ($user){
            Session::flash('fail', 'Candidate with email already exist');
            $payload=['status'=>'fail','details'=>'Candidate with email already exist'];
            return response()->json($payload, 200);
            return  redirect()->back()->withInput();
        }
            $password=Str::random(7);

            $job_level_id = $job_level->id ?? null;

            $new_user=User::create([
                'client_id'=>$client->id,
                'email'=>$request->email,
                'emp_num'=>$request->emp_num,
                'first_name'=>$request->first_name,
                'last_name'=>$request->last_name,
                'stage_id'=>1,
                'user_type'=>$request->user_type,
                'job_level_id'=>$job_level_id,
                'job_role_id'=>$job_role->id,
                'attributes'=>$attr,
                'password'=>Hash::make($password),
            ]);

            // $mail_constants['MacTay Signature Banner'] = '';

            $mail_constants = $this->getMailConstants($new_user);
            $mail_constants['candidate_password']=$password;
            $mail_constants['deadline']=Carbon::now()->addWeekdays(2)->format('D d M, Y');
            $mail_constants['admin_name']=auth()->user()->name;
            $mail_content=$this->convertMailTemplateToEmail($mail_template,$mail_constants);

            $mail_template->subject = str_replace('{{job_role}}', $mail_constants['job_role'], $mail_template->subject);
            $mail_template->subject = str_replace('{{client_name}}', $mail_constants['client_name'], $mail_template->subject);

            Mail::to($new_user->email)->send(new AdminSendMail($mail_content,$mail_template->subject));
            $message="Your account has been created on Mactay App. Email: {$new_user->email}, Temp Password: {$password}. URL: onboarding.mactay.com";

            SendSMSJob::dispatch($new_user->phone,$message);

            activity()->withProperties(['client_id' => $client->id])->log('Upload single candidate to '.$client->name);
            Session::flash('success', 'Successfully Uploaded Single Candidates Details');
          
            $payload=['status'=>'success','details'=>'Successfully Uploaded Single Candidates Details'];
            return response()->json($payload, 200);

    }

please what am i doing wrong, please help , thanks in advance

CodePudding user response:

You forgot to json_decode $client->attributes

$clientAttributes = json_decode($client->attributes);

foreach ($clientAttributes->offer_letter_variables as $variable){
  $offer_letters_variables->put(
    $variable,
    $request->{$variable} ?? 'not set'
  );
}

$attr = collect(['offer_letter_variables' => $offer_letters_variables]);


if you want to access it like an array you can json_decode the value like as an associative array.

$clientAttributes = json_decode($client->attributes, true);

dd($clientAttributes['offer_letter_variables']);


Also not that you have misspelled offer_letter_variables as offer_letters_variables in you foreach loop.

CodePudding user response:

You will get offer_letter_variables like this.

$offerLetters = 0;
$client=Client::where('id',$client)->firstOrFail();
if(isset($client->attributes['offer_letter_variables'])){
   $offerLetters = $client->attributes['offer_letter_variables'];
}

CodePudding user response:

do you need to use the second parameter of json_decode ? For remember, used if it's an associative array

$client=Client::where('id',$client)->firstOrFail();
$arr = json_decode($client->attributes);

What return gettype() ? Array ?

CodePudding user response:

thanks to @maazin , the solution was to use json_decode $client->attributes and then use foreach like so

$clientAttributes = json_decode($client->attributes);

foreach ($clientAttributes->offer_letter_variables as $variable){
  $offer_letters_variables->put(
    $variable,
    $request->{$variable} ?? 'not set'
  );
}

$attr = collect(['offer_letter_variables' => $offer_letters_variables]);
  • Related