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.
This was solved by the answer of Khayam Khan; I don't know why he removed it, but this was his answer:
It gives you null because of the stateless nature of HTTP requests.
Each HTTP request to your Laravel application is handled independently. This means that for each request, a new instance of your controller is created.
What you can do is either create a service class or save that value in the session. For Example,
In
add_all
methodsession(['person_id' => $this->person->id]);
In
addPromHist
method$personId = session('person_id'); $this->person = Pers_info::find($personId);