I'm a java developer; New to Laravel and PHP both. I learned how to define a global variable in Laravel controller class and used it as such. But it returns null in all other functions.
I have a class variable $person in my AddPersInfoController.php.
I initialize it first in a function because I need this ID to be saved with every record in different tables (handled by different functions in same controller) of the Database. But when I try to use it in any other function at the time of submitting form, it returns null.
Initialization function is called in get route as such:
Route in web.php
Route::get('/add_all/{persId?}',[AddPersInfoController::class,'add_all'])->name('add_all');
My AddPersInfoController.php controller
class AddPersInfoController extends Controller
{
private $person ;
public function add_all( int $user_id){
$pers = $this->person = Pers_info::find($user_id);
dd($pers); // This shows all values fetched from Database
.
.
}
Here I initialize it and copy it into a local variable pers to pass it to the view using compact() method with a few other local variables.
In the view, I enter the data in other fields as required and then save them using a post route.
In web.php
Route::post('/add/prom_hist',[AddPersInfoController::class,'addPromHist'])->name('add_prom_hist');
AddPersInfoController.php controller
public function addPromHist(Request $request)
{
$this->validate ( $request, [
......
]);
dd($this->person); // This returns null.
$promHist = new Prom_history();
$promHist-> pers_info_id = $this->person->id ; // I have to use it here
$promHist-> date =$request->date ;
It reutrns null in the above function.
person? Do you calladd_allin youraddPromHistbefore?add_allbecause I have already called it once before navigating to myview. Now I'm saving the records using the same controller. Should it not hold its values? And I've not given any default values to$person; I've declared it just above myadd_allfunction./add_all/{persId?}page first and then/add/prom_histpage and since you visited/add_all/{persId?}and intializedpersoninside that method, it should store it and be available to use when you visit/add/prom_hist?/add/prom_histis not a page, it's just a URL of thepostrequest which I sent from/add_all/page . And I used same controller for all of these requests..