Transfer variable from one to another function in controller - php

I am using Laravel at this time to secure a page when a user enters their password on a modal form before it opens. I initialized a variable named $crypt, which is hidden in the form, to make every page unique (to prevent other people from opening the page with a URL).
I want to pass the $crypt data to the PDFView. How can I do that? I've tried a lot of things but none worked.
Error
Undefined variable: crypts
Route:
Route::get('/pdfview/{id}/', 'HomeController#pdfview')->name('pdfview');
Generated key code
<div style="display: none">{{ $crypt = str_random(10)}}
Controller
public function encryptslip(Request $request, $crypt)
{
$crypts = $crypt;
$id = $request->nip;
$pass = $request->password;
$nip = Auth::user()->nip;
if (Hash::check($pass, Auth::user()->password)) {
return redirect('/pdfview/' . $nip . '/', ['crypts' => $crypts])->with('crypt', $crypt);
} else {
return redirect('/home')->with('alert', 'Incorrect password');
}
}
public function pdfview(Request $request, $id)
{
$route = url()->current();
$month = Carbon::now()->month;
$periodeinput = DB::table('payrollinput')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
$periodehistory = DB::table('payrollhistory')->where('nip', '=', $id)->orderBy('periode', 'desc')->pluck('periode')->implode('periode');
// if ($periodeinput !== $month && $periodehistory !== $month) {
// return redirect('home')->with('alert', 'Slip gaji anda siap.');
// } else {
if (Auth::user()->nip == $id) {
$employees = MasterEmployee::where('nip', '=', $id)->first();
$payrollhistory = MasterPayrollHistory::where('nip', '=', $id)->where('periode', '=', $month)->first();
$payrollinput = MasterPayrollInput::where('nip', '=', $id)->where('periode', '=', $month)->first();
view()->share('employees', $employees);
view()->share('payrollhistory', $payrollhistory);
view()->share('payrollinput', $payrollinput);
view()->share('id', $id);
// calculation code
return view('pdfview', ['id' => $id])->with('id', $id)
->with('earningtotal', $earningtotal)
->with('deductiontotal', $deductiontotal)
->with('takehomepay', $takehomepay)
->with('total', $total);
} else {
return redirect('home')->with('alert', 'Sorry it is personally confidential, you are not able to see it.');
}
}
View
<div><{{$crypts}}</div>

when you use return redirect() method that variable is passed to the view as a session variable and in the blade it must be called form
<div>{{session('crypts')}}</div>
to convert this session variable on $request
{{Form:hidden('crypts', json_encode(session('crypts'))}}

Related

Redirect with data back to where the form was completed laravel

I have a form from which the controller gets the data requested from the db. I want to then redirect to the same page as the form but with the data i got from the db. I am using laravel 5.5
This is my controller for the store:
public function listsStore(Request $request) {
$data = $request->all();
$user = $request->user;
$day = date('Y-m-d', strtotime($request->day));
$from = date('Y-m-d', strtotime($request->from));
$to = date('Y-m-d', strtotime($request->to));
$radio = $data['radio-btn'];
// dd($user, $from, $to);
// dd($radio);
if($radio === 'tasks') {
if($request->day) {
$tasks = Task::where('user_id', $user)
->whereDate('start', $day)
->orderBy('start','DESC')
->get();
// dd($tasks);
return redirect()->back()->with('tasks', $tasks);
}else{ // gets for the range of dates requested
$tasks = Task::where('user_id', $user)
->whereBetween('start',[$from, $to])
->orderBy('start','DESC')
->get()
->groupBy(function($date) {
return Carbon::parse($date->start)->format('Y-m-d');
});
// dd($tasks);
return redirect()->back()->with('tasks', $tasks);
}
}elseif($radio === 'timecards'){ //IF REQUEST IS TIMECARDS
if($request->day) { //gets for the day requested
$timecards = Timecard::where('user_id',$user)
->whereDate('checkin', $day)
->orderBy('checkin','DESC')
->get();
// dd($timecards);
return redirect()->back()->with('timecards', $timecards);
} else{ // gets for the range of dates requested
$timecards = Timecard::where('user_id', $user)
->whereBetween('checkin',[$from, $to])
->orderBy('checkin','DESC')
->get()
->groupBy(function($date) {
return Carbon::parse($date->checkin)->format('Y-m-d');
});
// dd($timecards);
return redirect()->back()->with('timecards', $timecards);
}
}
// return redirect('backend.list');
}
controller for the page:
public function lists() {
$users = User::all();
return view( 'backend.list', compact('users'));
}
and in the view i tried this way:
#if(session()->has('timecards'))
#foreach($timecards as $timecard)
<div>{{$timecard->checkin}}</div>
#endforeach
#endif
Thank you
Update: now i get the data but it is in a json like format, any idea of how i can manipulate it?
my view:
#if(session()->has('data'))
{{session('data')}}
#endif
Thankss
In listsStore()
return Redirect:: route('route-name')->with( ['data' => $data] );
and in your route you can read it with
Session::get('data');

session lost after reloading in laravel 6

Here is simple sigin method :
LoginController :
public function signin(Request $r)
{
$data['email'] = $r->email;
$data['password'] = md5($r->password);
if ($data['email'] == '' || $data['password'] == '') {
echo 'Please enter email or password.';
} else {
$userInfo = DB::table('users')->where('email', $data['email'])->get()->first();
if ($data['email'] == $userInfo->email && $data['password'] == $userInfo->password) {
$r->session()->put('userData', $data['email']);
$userData = $r->session()->get('userData');
return redirect('/userpanel')->with('status', $userData);
} else {
return redirect('/login');
}
}
}
HomeController :
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
return view('userDashboard')->with(['data' => $data]);
}
After login this method redirects to the user panel here display the session information. But if I reload here there don't display any session information. In my blade I print session by the following code :
<div class="alert alert-success" class="d-block">
<div id="userEmail" >{{ session('status') }}</div>
</div>
I use it in HomeController and LoginController. But problem is not fix.
Using with you are basically Flashing Data To Session which will remain in session only for next request, that why when you reload you are not getting that that again.
https://laravel.com/docs/5.8/session#flash-data
This is with() implementation, in which it flashes data using flash(), which will be remain for just for next request.
public function with($key, $value = null)
{
$key = is_array($key) ? $key : [$key => $value];
foreach ($key as $k => $v) {
$this->session->flash($k, $v);
}
return $this;
}
Change this code
public function user_index()
{
$data = DB::table('personals')
->join('companies', 'personals.companyId', 'companies.id')
->get();
session(['data' => $data]);
return view('userDashboard');
}
Add this in your blade file.
#if(\Session::has('status'))
<span>{{\Session::get('status')}}</span>
#endif

Laravel CustomRequest authorize, pass request data to validate the auth user customer id and the model id match

I'm trying to fix an if-else statement in the request for my controller. What I'm trying to do is: if the auth::user-companyID == $request-companyID then true else false; The companyID for the request is in a hidden field on the blade file.
CustomRequest
public function authorize()
{
$user = Auth::user();
if ($user->companyID == $request->companyID) {
return true;
} else {
return false;
}
}
Controller
public function edit(EquipmentRequest $request, $id)
{
$validated = $request->validated();
$user = Auth::user();
$equipment = EquipmentModel::where('id', '=', $id)->first();
$equipment->Year = $request->Year;
$equipment->Make = $request->Make;
$equipment->Model = $request->Model;
$equipment->Type = $request->Type;
$equipment->unitNumber = $request->unitNumber;
$equipment->AnnualInspectionDate = $request->AnnualInspectionDate;
$equipment->userID = $request->userID;
$equipment->companyID = $user->companyID;
$e = $equipment->save();
if ($e) {
$request->session()->flash('success', 'The equipment was successfully updated.');
} else {
$request->session()->flash('error',
'An error occurred while saving. Please refresh your browser and try again.');
}
return redirect()->route('equipmentlist');
}
This form worked before I started messing with it so I know the form is working correctly on the blade file. I'm not sure if you can pass the request data the way I'm doing it or if I have to do a construct to do it this way. I would really appreciate any advice.
use Illuminate\Http\Request;
public function authorize()
{
$user = auth()->user();
return $user->companyID === request()->companyID;
}

capture user id when login and save user id based on operations

I need to capture login user and when i add question i need to save the corresponding user id in the questions table.i'm getting user id when i login but it is not saving in the question table
Controller with store function
public function store(Request $request)
{
//
$last_que = Question::orderBy('question_id', 'desc')->first();
if ($last_que != null) {
$old_queId = $last_que->question_id;
$old_queId = $old_queId + 1;
} else {
$old_queId = 1;
}
$qorder=$request->input('order');
$question=new Question();
$quest=$question->checkDuo($qorder);
if(count($quest)==0)
{
$que=Question::create([
'question'=>$request->input('question'),
'question_id'=>$old_queId,
'question_type'=>$request->input('qtype'),
'question_schedul'=>$request->input('qschedule'),
'created_user_id'=>Session::get('created_id'),
'order_no'=>$request->input('order')
]);
if($que)
{
return redirect()->route('questions.index')->with('success', 'Successfully saved');
}
}
else
{
return redirect()->back()->with('fail', 'Unable to save..! Entry with same order no. already exist');
}
}
in Login index file this is i used capture the user id
<?php
if (!empty($id)) {
Session::put('created_id', $id);
}
?>
Login controller
public function postSignIn(Request $request)
{
if (Auth::attempt(['username' => $request['username'], 'password' => $request['password']])) {
$user = DB::table('users')->where([['username', '=', $request['username']], ['status', '=', '0']])->first();
$user_id = $user->user_id;
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
} else {
return redirect()->back();
}
}
Get user ID. use something like this.
Auth:user()->id;
Or you can use
Session::getId();
Change this line,
'created_user_id'=>Session::get('created_id'),
To,
'created_user_id'=>Auth::id(),
You used $user_id
return redirect()->route('dashboard', $user_id)->with('message', 'State saved correctly!!!');
Than asking:
if (!empty($id)) {
This $id will be always empty so use:
<?php
if (!empty($user_id)) {
Session::put('created_id', $user_id);
}
?>

Check for two variables on view page but send one from controller

I have one controller which checks if username is correct or not on user input and based on correct/not correct I send different variables to view page.
So what I have in controller is this
public function resSub() {
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
// not relevant stuffs
$enc = 'enc';
return View::make('users.page2', ['enc'=> $enc]);
}
Session::put('user_id', $user['user_id']);
return Redirect::to('/users/page2?_token=' . csrf_token());
}
public function encMess()
{
$data = Session::all();
$enc1 = 'enc1';
return View::make('users.page2', ['enc1'=> $enc1]);
}
In the view I have this
#if(!$enc)
<pre>{{ $enc1 }}</pre>
#else
<pre>{{ $enc }}</pre>
#endif
When I run the page I get either $enc or $enc1 not defined because it isn't sent to the view.
How can I make this?
public function resSub() {
$user = User::where('username', Input::get('username'))->first();
if (!$user) {
// not relevant stuffs
return View::make('users.page2', ['enc'=> $enc]);
}
Session::put('user_id', $user['user_id']);
return Redirect::to('/users/page2?_token=' . csrf_token()); }
public function encMess() {
$data = Session::all();
return View::make('users.page2', ['enc'=> $enc1]);
}
View:
{{ $enc }}
You are doing the same thing in your view so you don't need to pass two different variable name.
If you really need to have two seperated variable use can pass one with an empty value.

Categories