Passing the same variable to multiple laravel controller functions - laravel

I'm trying to create a variable accessible by two different controller functins in laravel. How can I do that. The first function gets a value from a blade, it stores it in a variable and then I want to pass that variable with value to another controller function. For example, the following blade passes obj_id to controller:
1) My blade:
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>test</title>
</head>
<body>
<form method='post' action="/hard">
{{csrf_field()}}
<br>
<legend><i> Fill Data </i></legend>
<br>
<label>
OBJECT ID:
<input name='obj_id' type='text' minlength="8" required="" oninvalid="this.setCustomValidity('8 char at least')">
</label>
<br>
<input type='submit' value="Submit!">
</form>
<br>
<br>
</body>
</html>
2) My controller function Roger correctly gets obj_id (I have tested ot with dd)
public function Roger(Request $p)
{
$t = $p-> get('obj_id'); //I want $t to be global variable
//dd($t);
}
3) and then I want to pass $t to function Roger1 in the same controller
public function Roger1()
{
dd($t);
}
I have tried to declare $t as global with no success. I'm a little bit confused with $this and tried several combinations with no success.
Could you assist please?

You can use the session to store a variable
public function Roger(Request $p)
{
$t = $p-> get('obj_id'); //I want $t to be global variable
$p->session()->put('myvalue', $t);
}
public function Roger1(Request $p)
{
$p->session()->get('myvalue);
}
https://laravel.com/docs/5.8/session#storing-data

Scenatio #01
IF both methods are in the same controller AND your second method is called inside the first method (in the same call), you can just do:
class CoolController extends Controller {
public $var;
public function first_method(Request $value)
{
// Example 1: passing the value as a parameter:
$this->second_method($value);
// Example 2: passing the value through a class variable:
$this->var = $value; // $value: 'some-text'
$this->third_method();
}
public function second_method($value)
{
dd($value); // 'some-text'
}
public function third_method()
{
dd($this->var); // 'some-text';
}
}
Scenatio #02
Now, in the case you want to make a request from your view to set a value in your first method, and then another request calling your second method and getting that value that was "stored" in the first call.. well you can use any of this approaches. Why? because both call are in different lifecycles.
When the first call ended the value assigned in the first method (stored in memory) will be erased when the request is finished. That's why your second call will get a null value if you try to use it.
To store a temporary variable you have several paths:
Store it in the database.
Store it in the cache.
Send the value as a request parameter when doing the second call.

Related

Fail to retrieve Post data with Laravel

I try to learn Laravel (v.9) from scratch but fail to do a simple basic task:
I just want to send "post_var" by POST request and display the var.
My form (blade template):
<form action="/post_and_show" method="POST">
#csrf
#method('post')
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
My Route (in web.php) with some dd() i tried to find the problem
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !!
// chrome debugger network tab show clearly its a POST request...
dd($request->all()); // returns empty Array
dd($request->post_var); // returns null
dd($request->getContent()); // returns string but i want param only
// "_token=yBBYpQ303a1tSiGtQF6zFCF6p6S7qadVfHMk4W7Q&_method=post&post_var=12345"
});
What am i doing wrong here?
Tried several methods i found in the documentation but non worked so far.
EDIT: I removed "#method('post')"
Btw.: My initial version that did not work either had no "#method('post')". I added it later on in the hope it might help...
<form action="/post_and_show" method="POST">
#csrf
<input type="text" name="post_var">
<input type="submit" value="send">
</form>
But have still the same problems:
Route::post('/post_and_show', function (Request $request) {
dd($request->method()); // returns GET ?? !! but chrome says its a post request
dd($request->post_var); // returns null
dd($request->get('post_var'));// returns null
dd($request->getContent()); // returns complete body and header in one string
dd($request->all()); // return empty Array
});
EDIT 2:
Googleing i found "createFromGlobals":
use Illuminate\HTTP\Request; // just added this to show which class i use here...
use Illuminate\Support\Facades\Route;
Route::post('/post_and_show', function () {
dd(Request::createFromGlobals()->get('post_var')); // returning expected value
});
This works for me, but i can't find this method in documentation. Sorry, i am new to laravel and even php, so this seems all completely crazy to me.. ;-)
EDIT 3:
If i use a simple Controller it works too...
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
public function show(Request $request)
{
dd($request->post_var); // returns expected value...
}
}
Route:
Route::post('post_and_show', [FormController::class, 'show']);
So only in case i use the $request immediatly in the callback it does not work as expected. ( Either by design or bug??)

How to send a value to route in laravel

I want to send a value to route that i am received from the controller.!How can i do it.
My controller:
public function payment_history($id)
{
$payment_details=AmountDrvPaidHistoryModel::where('driver_id',$id)->get();
return view('admin.driver_payment_history')->with('payment_details',$payment_details)->with(array('id'=>$id));
}
Here is my blade:
<form action="{{URL::to('driver_payment_history/'.$id)}}" method="post">
How can i get the value of id in action tag that is send to another route.
just remove array from this
->with('id'=>$id);
You code will be:
public function payment_history($id)
{
$payment_details = AmountDrvPaidHistoryModel::where('driver_id',$id)->get();
return view('admin.driver_payment_history', compact('payment_details', 'id'));
}
With compact you can get the variable data, so $id will pass on to the view.
Than you can get the id with this code:
<form action="{{ url('driver_payment_history/'.$id) }}" method="post">
EDIT
<form action="{{ url('driver_payment_history/'.$payment_details[0]->driver_id) }}" method="post">
Hope this works!
You have to reference the $id inside your function, initiating it to be passed by the specific function.
public function payment_history($id) //<-this is the parameter passed into the function
{
$payment_details=AmountDrvPaidHistoryModel::where('driver_id',$id)->get();
$new_var_id = $id; //<- Assign the $id to a new variable (eg. $new_var_id)
return view('admin.driver_payment_history',compact('payment_details','new_var_id');
}
You will then access the variable as such
<form action="{{ url('driver_payment_history/'.$new_var_id) }}" method="post">
However keep in mind that you are already doing a get request with the $id variable, and sending all the results to the page. This means that you can just access the specific id in the view by accessing the objects properties without re initiating the $id variable.
<form action="{{ url('driver_payment_history/'.$payment_details->driver_id) }}" method="post">
If you do use this, you can remove $new_var_id(or whatever you named it) from your controller, as well as removing it from compact()

Laravel 4 search function

From my previous question, I've gotten this code from a user.
// app/routes.php
Route::get('characters', 'CharactersController#all');
Route::get('characters/{name}', 'CharactersController#detail');
// app/controllers/CharactersController.php
class CharactersController extends BaseController
{
public function all()
{
// show all characters
}
public function detail($name)
{
// find character by name & show detail for example
return View::make('acc.test');
}
}
// app/views/acc/test.blade.php
// HTML::style('css/style.css') loads CSS file located at public/css/style.css
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
{{ HTML::style('css/style.css') }}
</head>
<body>
</body>
</html>
also, the search function:
<form action="{{ URL::action('CharactersController#search') }}" method="get">
<input type="text" name="search-term">
<input type="submit" value="Search">
public function search()
{
$name = Input::get('search-term');
$searchResult = Character::where('name', '=', $name)->get();
....
}
Route::get('characters/search', 'CharactersController#search');
how could I in the :
public function detail($name) { // find character by name & show detail for example return View::make('acc.test'); }
how could I find the character by name? I've tried doing something like
$name = $player->name
(I have a model called players, I've also changed Character::where to Player::where), what do I have to insert there? also, how could I display it in the view?
So I mean when I search a player by name it displays the players name ($player->name) for every specific player.
Also do I have to change the relations in the model toHasMany or something like that?
You can do it this way
public function detail($name) {
$player = Player::where('name', '=', $name)->first();
}
If more players can have same name I would rather pass ID instead of name, so in this case use this solution
public function detail($id) {
$player = Player::findOrFail($id);
}

Attempting to access View from blade template causes blank body in Laravel4

I have a project which is using laravel4 and its blade view engine. Occasionally I have had the need to call controller methods via a view file to output dynamic data; incidentally this time its a call to a method that generates javascript code for the page. Regardless of whether this is the best way to go about things is a moot point atm as I am simply upgrading from L3 to L4.
My View is similar to:
#extends('en/frontend/layouts/default')
{{-- Page title --}}
#section('title')
Page Title
#parent
#stop
{{-- Page content --}}
#section('pageContent')
...
#stop
{{-- Scripts --}}
#section('scripts')
<?php echo CaseStudy::script(); ?>
#stop
I have set up CaseStudy to load via the laravel facades and the class at current is simply:
class CaseStudy
{
public function display()
{
}
/**
* Returns the javascript needed to produce the case study
* interactivity
*
* #return \Illuminate\View\View|void
*/
public function script()
{
$language = \Config::get('app.locale');
$scriptElementView = $language . '.frontend.elements.casestudy_script';
if ( ! \View::exists($scriptElementView))
{
$scriptElementView = "Training::" . $scriptElementView;
}
return \View::make($scriptElementView, array());
}
}
It would appear that echoing the response of CaseStudy::script is what is causing the blank body; however with no further error message I do not know what is going on. I assume that this is because my static CaseStudy's instance of View is conflicting with the instance being used by the blade engine. How would I go about having CaseStudy::script() returning a string form of the rendered view?
Thank you.
In your view
{{-- Scripts --}}
#section('scripts')
{{ CaseStudy::script() }}
#stop
In your library
class CaseStudy
{
public function script()
{
$string = "your script here";
return $string;
}
}
Note - CaseStudy should really be a "library" or "helper" or something. Not a controller - that does not really conform to MVC approach.

IF Statement For Session - Formatting Q

So I have this IF statement in my view. it works and all, but wondering if there's a better way to write this. Having both session calls seem unneccessary...
if($this->session->userdata('campaign_name')){
echo $this->session->userdata('campaign_name');
}
else {
echo 'this';
}
Note this function will be used inline on a text input. So I'm looking for as minimal code as possible.
Note that CI's Session class's userdata method will return false if no campaign_name exists. So assign a variable to the potentially undefined array key (campaign_name)
$campaign_name = $this->session->userdata('campaign_name');
if($campaign_name)
{
echo $campaign_name;
}
else
{
echo 'this';
}
OR
if($campaign_name = $this->session->userdata('campaign_name'))
{
echo $campaign_name;
}
Controller Method (/application/controllers/test_controller.php)
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Test_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
}
public function myFunction()
{
$data['campaign_name'] = $this->session->userdata('campaign_name');
$this->load->view('test_view',$data);
}
}
View (/application/view/test_view.php)
<html>
<head></head>
<body>
<input type="text" value="<?php echo $campaign_name; ?>">
</body>
</html>
In your controller, you can store the value of that session data into a variable and pass that along to the view. In the view, you can then have your if else statements that just look at the variable. I would advise against setting a variable in the view as RPM did. While it works, it breaks the separation of concerns you have going.
Also, look into using the alternative PHP syntax for views in CodeIgniter. It'll make your code neater and more maintainable.
Edit: I see now that RPM has updated his answer to set the variable in the controller. That's a good example to follow.

Resources