Laravel, Pass input variables from page to other using session - php

Please note that I'm new in Laravel, so I need serious help and since 3 days looking for solution but no luck.
All I need just to view or display the value of the input text from the form booking-form to customer/dashboard page, please note that can't send the input data untill you login and this is working fine, but how to pass data and display in the next page?
Please answer with code please
Form:
<form id="booking-form">
<input class="indexinput" type="text" id="country" name="country"
placeholder="Country">
<input class="indexinput" type="text" id="state" name="state"
placeholder="State">
<input class="indexinput" type="text" id="city" name="city" placeholder="city">
</form>
<button class="button getbids" >GET BIDS</button>
<script type="text/javascript">
$(document).on('click', '.getbids', function() {
var loggedIn = {{ auth()->check() ? 'true' : 'false' }};
if (loggedIn)
window.location.replace('customer/dashboard');
if(!loggedIn)
$('#loginModal').modal('show');
});
</script>
Route
Route::group(['middleware'=>['rolecustomer']], function () {
Route::get('/customer/dashboard', 'HomeController#index')->name('customer.dashboard');
});
controller:
public function index()
{
return view('index.customer.customerdashboard');
}

To store the value in the session, pass the value of the input to laravel's session like this.
Session::set('input_field', 'field_value');
And to retrieve the session use the following piece of code.
Session::get('input_field');
More informations on laravel session here.

If you want to put something something permanently for entire session, you can use $session->put('key', 'value').
In your case,
public function bids(Request $request){
$request->session()->put('country', $request->country);
$request->session()->put('state', $request->state);
$request->session()->put('city', $request->city);
return redirect()->route('route_name');
}
Then in next page, just, use Session::get($key).
<div>
<p>Country : {{ Session::get('country') }}</p>
<p>State: {{ Session::get('state') }}</p>
<p>City: {{ Session::get('city') }}</p>
</div>
Or, a more convenient way to access a Session is first check if the value is in the Session or not by Session::has('key_name').
<div>
<p>Country : {{ (Session::has('country') ? Session::get('country') : '' ) }}</p>
.....
</div>

Related

Laravel 8 pass variable to be used in foreach loop for comparison

I'm trying to pass a predefined variable with a value into the #if part of the statement for comparison. This is for Laravel v8.0 on the blade.php. It only works if I hardcoded the value in it but not through the variable $value. I would need to have a placeholder variable to pass the value for comparison, as it will be inputted from user. Hence may I know what is the proper way to declare the variable as in this case? Sorry I'm just starting learning Laravel. Thanks for your help.
Eg:
$value = "abc123";
#foreach($surveys as $survey)
#if($survey->Unit_code == {{$value}})
<form action="" method="">
#csrf
<div class="form-group">
<label for="name">Name</label> <br>
<input type="text" name="Name" class="form-control" value="{{$survey->name}}">
</div>
<input type="submit" value="Save">
</form>
#endif
#endforeach
Just so this is in an answer form for other users that encounter this problem as a developer just learning laravel; the issue here is there was an output to the dom using {{}} where the blade directives (things that start with #) use the PHP vars as is an example of this would be as follows:
#if($survey->Unit_code == $value)
the other issue he was having, in this case, is assigning raw PHP on the blade file, this works the same way. Although, to add raw PHP to the dom you would use the #php directive
#php
$value = "abc123";
#endphp
#foreach($surveys as $survey)
#if($survey->Unit_code == $value)
<form action="" method="">
#csrf
<div class="form-group">
<label for="name">Name</label> <br>
<input type="text" name="Name" class="form-control" value="{{$survey->name}}">
</div>
<input type="submit" value="Save">
</form>
#endif
#endforeach
if the data of $value needed to be completely dynamic based on the backend then I would recommend passing it to the blade file via the view() function instead and assigning the value there or as nullable on the first pass of the function. Hope that helps!
You dont have to use {{ }} in #if condition .
When you use #if( ) everthing inside of it can translate into php .
So , you instead of using :
#if($survey->Unit_code == {{$value}})
Use :
#if($survey->Unit_code == $value )
Hope that works .

How to get value of input in blade.php

I need to get a value of input to use below, how to do that?
I tried to like this but error says
Undefined variable: name
<div class="col-md-10 col-md-offset-1">
<input id="name" type="text" name="name" />
</div>
<div class="col-md-10 col-md-offset-1">
#php
$nameValue=$_GET['name'];
#endphp
<input id="name2" type="text" name="name2" value="{{$nameValue}}" />
</div>
$nameValue=Request::input('name')
From the blade template you can access the request parameters with the Request facade, you can also print it directly:
{{Request::input('name')}}
In latest versions you can also use:
{{request()->input('name')}}
You have to be aware that your input-values (here "name") ist only available after submitting the form.
If you want to access the form-values before submitting you should take a look at VueJS or any other frontend-framework (React, Angular). Or simply use jQuery.
Therefor you have to use JavaScript if you want to use the input-value before submitting.
Like the others said in the comments, you can access your form-values within your controller and then pass it to your view.
For example (from the documentation):
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function formSubmit(Request $request)
{
$name = $request->input('name');
return view('form', ['name' => $name])
}
}
Now you can use the value within your view:
<input id="name2" type="text" name="name2" value="{{$name}}">
Another possibility would be to "by-pass" your controller and return your view directly from your routes.php:
Route::get('/form-submit', function(){
return view('form');
});
But I'm not sure if this is working and you could access $_GET/$_PSOT directly without using Laravels Request.
You can get inputs array from Request class:
Request::all()['your_input']
Also you can check if that input you want is exists not:
#isset(Request::all()['your_input'])
{{-- your input existed --}}
#else
{{-- your input does not existed --}}
#endisset

laravel use session to store input field and pass to another page

Im new in laravel I have form with input fields but I want to send the input values and dispaly in other page using session to check them later
Please answer with code please
Form:
<form id="booking-form">
<input class="indexinput" type="text" id="country" name="country"
placeholder="Country">
<input class="indexinput" type="text" id="state" name="state"
placeholder="State">
<input class="indexinput" type="text" id="city" name="city" placeholder="city">
</form>
<button class="button getbids" >GET BIDS</button>
<script type="text/javascript">
$(document).on('click', '.getbids', function() {
var loggedIn = {{ auth()->check() ? 'true' : 'false' }};
if (loggedIn)
window.location.replace('customer/dashboard');
if(!loggedIn)
$('#loginModal').modal('show');
});
</script>
Route
Route::group(['middleware'=>['rolecustomer']], function () {
Route::get('/customer/dashboard', 'HomeController#index')->name('customer.dashboard');
});
controller:
public function index()
{
return view('index.customer.customerdashboard');
}
You can put values in session (in the controller) like this :
$request->session()->put('sampleid', $samplevalue);
And retrieve them on blade page like this:
#if(Session::has('sampleid'))
<div class="alert alert-success">
{{Session::get('sampleid')}}
</div>
#endif
And in controller like this:
if($request->session()->has('sampleid'))
{
$request->session()->get('collegeid');
}
It looks like you're trying to redirect an user if the user is not logged in on a certain request. In laravel there is middleware to take care of this. Have a look at the documentation. It's not that hard to setup.
All this authentication rules can be handled with Laravel middleware.
Documentation Middleware: https://laravel.com/docs/5.5/middleware
By looking at your code, i understand that you are trying to check whether a user is authenticated after clicking the submit button. If he is authenticated, you are redirecting him to customer/dashboard. If he is not authenticated, you are displaying a login modal.
The problem is you are redirecting the user to a page using javascript and you can't get the data submitted using the form. So i guess you are trying to use session to get the form data in customer/dashboard. you can achieve what you want way simply like below.
<form id="booking-form" method="POST" action="{{ route('customer.dashboard') }}">
change your javascript code to
<script type="text/javascript">
$(document).on('click', '.getbids', function() {
var loggedIn = {{ auth()->check() ? 'true' : 'false' }};
if (loggedIn)
$('#booking-form').submit();
if(!loggedIn)
$('#loginModal').modal('show');
});
</script>
Now make your route as
Route::any('/customer/dashboard', 'HomeController#index')->name('customer.dashboard');

Laravel - Method Not Allowed HTTP Exception (RouteCollection.php line 218)

I'm currently new on Laravel and trying to develop my first project. I have this MethodNotAllowedHttpException in RouteCollection.php line 218 error during my development for inserting data into database. I have searched both Google & Stackoverflow for solutions but non are related to my current problem and some of them way too complex for this simple problem (I think so...).
I have my form in my checklist page:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<div class="text-left">
<input type="hidden" name="schmFK" value="{{$id}}">
<div class="col-sm-6">
<h4>
<label>Section</label>
<select class="selectpicker form-control" data-live-search="true" name="sctionPK">
<option selected>Select the Section</option>
#foreach ($sction as $key=>$slct1)
<option value="{{$slct1->ssctionPK}}">{{strtoupper($slct1->ssctionName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-2">
<button type="button" data-toggle="modal" data-target=".bs-example-modal-lg" class="btn btn-primary btn-sm" style="margin-top:33px; padding-top:7px; padding-bottom:7px;">Add Section</button>
</div>
<div class="col-sm-4">
<h4>
<label>Severity</label>
<select class="selectpicker form-control" name="svrityPK">
<option selected>Select the Severity</option>
#foreach ($svrity as $key=>$slct2)
<option value="{{$slct2->severityPK}}">{{strtoupper($slct2->severityName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-12">
<h4>
<label>Question</label>
<input class="form-control" type="text" placeholder="Question" name="question">
</h4>
</div>
<div class="col-sm-6">
#include('widgets.button', array('class'=>'primary btnaddstd', 'size'=>'lg', 'type'=>'submit', 'value'=>'Add Checklist'))
</div>
</div>
</div>
</div>
</form>
Then I have this route for inserting data from the form into database:-
Route::post('/addchecklist', function (Request $request){
// Create instance to store record
$scheme = new App\checklists;
$scheme->schmFK = $request->schmFK;
$scheme->schSectionFK = $request->sctionPK;
$scheme->severityFK = $request->svrityPK;
$scheme->clQuestion = $request->question;
$scheme->save(); // save the input
// Sort all records descending to retrieve the newest added record
$input = App\checklists::orderBy('cklistPK','desc')->first();
// Set search field variable default value of null
$src = isset($src) ? $src : null;
// Get Checklist reference from cklists_stddetails with the designated ID
$chkstd = App\Cklists_stddetail::where('cklistFK', $input->cklistPK)
->join('stddetails', 'stdDtlFK', '=', 'stddetails.sdtlPK')
->get();
// Get the newest stored record
$chcklst = App\checklists::where('cklistPK', $input->cklistPK)->firstOrFail();
// Get all data from table 'stddetails'
$stddetail = App\stddetails::all();
// Get all data from table 'standards'
$stndrd = App\standard::all();
// Get all data from table 'sections'
$sction = App\Section::all();
// Redirect to 'addref.blade' page with the newest added record
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
My scenario is this, I have a form for user to input data in it. Then when the data is saved, they will be redirected to the page of that data to do something there. The data is successfully saved in the database but the redirection to the designated page (addref.blade) with the newest record ID return error:-
But the URL goes where I wanted it to go (means the URL is right):-
As you can see, the usual solution from the net that I found are:-
Make sure both method from routes and the form is the same, and mine it is:-
method="POST"
Route::post
Make sure the URL routes can recognize the form's action URL, and mine it is:-
<form action="{{url('addchecklist')}}" method="POST">
Route::post('/addchecklist', function (Request $request)
Include CSRF token field in the form, and mine it have been included:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
I have tried those simple solution provided on the net and nothing is helpful enough. I'm still wondering what else I have missed and hoped that anyone here can assist on solving my issue.
I think the error is that you have a redirect which you have not registered in your routes or web.php file.
Sample redirect:
Route::post('/addchecklist', function (Request $request){
//some post process here...
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
Route::get('addref/{id}', function(Request $request){
//show the blade.php with data
});
Can you please write :
url('/addchecklist')
instead of :
url('addchecklist')
and then print_r('in');
and die; and check what you get.
Route::post('/addchecklist', function (Request $request){
print_r('in');
die;
});

Laravel GET method for search

I create form in Laravel:
<form action="/redeem" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="key" class="form-control" placeholder="ENTER VOUCHER CODE">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
and now when I try to submit that I get:
http://localhost:8888/redeem?key=NBtGJ5pZls&search=
but I need to get just:
http://localhost:8888/redeem/NBtGJ5pZls
also in route I have:
Route::get('/redeem/{key}', 'OrdersController#redeem');
How to get redirected to redeem/NBtGJ5pZls with my form?
Change your route to:
Route::post('/redeem', 'OrdersController#redeem');
And then get key in controller:
public function redeem(Request $request)
{
$key = $request->key;
And finally, change your form:
<form action="/redeem" method="post" class="sidebar-form">
{{ csrf_field() }}
You've got 2 options:
The first is let your frontend code be the way it is, update the route, and work with the GET parameter.
The second one is using some javascript to rewrite the URL you want to access.
For example this (it's using jQuery):
$('#search-btn').click(function() {
var key = $('input[name=key]').val();
window.location.href = '/redeem/' + key;
});
I prefer the first one, because javascript can be modified by the end-user.

Categories