将一个方法变量获取到同一个类中的其他方法并显示在路径中 - Laravel 5.2

时间:2017-11-16 06:38:20

标签: php laravel laravel-5.2

我有一个控制器。有两个功能。现在我想从一个函数到另一个函数获取变量(它是随机字符串)值,并将此值打印到Route(url)中。

控制器:

class PrizeCalculateController extends Controller
{
      public function calculatePrize($id, $randomStr=0)
    {
        $randomStr = str_random(5);
        return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);  
    }

    public function showPrizePage($id, $randomStr=0)
    {
        //get random string from calculatePrize function
        $getStr = PrizeCalculateController::calculatePrize($randomStr);
        return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
    } 
}

我试图以这种方式从calculatePrize函数到showPrizePage函数获取随机字符串:

$getStr = PrizeCalculateController::calculatePrize($randomStr);

如果我dd($getStr),那么我得到null。现在我如何从calculatePrize函数到showPrizePage函数获取此变量。

想要路线:

Route::get('/prize/{getStr}','PrizeCalculateController@showPrizePage');

2 个答案:

答案 0 :(得分:1)

你应该试试这个:

use Illuminate\Http\Request;
use Session;

    public function calculatePrize($id, $randomStr=0)
        {
            $randomStr = str_random(5);
            Session::set('randomString', $randomStr);
            return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);  
        }

        public function showPrizePage($id,$randomStr=0)
        {
            if(Session::has('randomString')) {
                $randomStr = Session::get('randomString');
            } else {
              $randomStr = 0;
            }

            $getStr = PrizeCalculateController::calculatePrize($randomStr);
            return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
        } 

答案 1 :(得分:0)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_single_record);

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);


    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getExtra("ID");
    System.out.println("TempItem=============>"+TempItem )

    //Calling method to filter Student Record and open selected record.
    if(null != TempItem){
     HttpWebCall(TempItem);
    }else{
      Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
    }



    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}


//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}


// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");







                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);





    }
}

试试这个希望它可以帮到你。如果有任何问题,请告诉我。