Steve Steve - 3 months ago 7
PHP Question

undefined variable if not exists

If there donot exists a

$category
,
$category
goes undefined. so how can i pass
$category
if only it exists.

public function receive(Request $request)
{
if($request->ajax())
{
$id=$request->id;
if($id)
{
$receive=User::where(['id'=>$id])->first();
if($receive->category->name)
{
$category=$receive->category->name;
}

echo json_encode(array('status' => TRUE, 'receive'=>$receive,'category'=>$category)); die;
}

Answer

You could simply initialize $category within your Method to a null value. So that even when your conditional logic fails to override $category, we would have a null value to fall back on.....

<?php


    public function receive(Request $request) {
        $category   = null;     //<== INITIALIZE THE $category VARIABLE TO NULL.
        if ($request->ajax()) {
            if ($id = $request->id) {
                $receive = User::where(['id' => $id])->first();
                if (isset($receive->category->name)) {
                    $category = $receive->category->name;
                }

                die( json_encode([
                    'status'   => TRUE,
                    'receive'  => $receive,
                    'category' => $category
                ]));
            }
        }
    }

ALTERNATIVELY:

<?php

    public function receive(Request $request) {
        // CREATE A NEW ARRAY WITH KEYS CORRESPONDING TO RESPONSE KEY
        // THEN INITIALIZE EACH ELEMENT OF THE ARRAY TO NULL OR FALSE
        $response   = [
            'status'   => false,
            'receive'  => null,
            'category' => null              
        ];
        if ($request->ajax()) {
            if ($id = $request->id) {
                $receive = User::where(['id' => $id])->first();
                if (isset($receive->category->name)) {
                    $category = $receive->category->name;
                }
                // OVERRIDE THE VALUES OF THE $response ARRAY.
                // IF $receive OR $category ARE SET, WE USE THEIR VALUES
                // OTHERWISE WE SET THE VALUES TO NULL
                $response['status']     = true;
                $response['receive']    = isset($receive)?$receive:null;
                $response['category']   = isset($category)?$category:null;
            }
        }       
        // SINCE WE HAVE ACCESS TO $response, WE CAN NOW FINALLY
        // JSON_ENCODE IT & DIE-OUT THE RESULT...
        die( json_encode($response) );
    }