session lost after reloading in laravel 6 - php

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

Related

Too few arguments to function Illuminate\Http\Request::has(), 0 passed

I have seen many similar questions but most of the answers look complicated and do not seem too similar to my issues. Again, I am new to Laravel and would need the simplest form of explanation.
I want to don't show info in view, show up as long as I searched.
My Controller
public function index(Request $request)
{
$transactions = UserTransaction::query();
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
return view('admin.transaction.index',[
'transactions' => $transactions->paginate(5)->appends($request->except('page')),
'stats' => $stats
]);
}
My Blade
#if( $transactions->count() > 0 && request()->has() )
#foreach($transactions as $transaction)
{{ $transaction->id }}
{{ optional($transaction->user)->full_name }}
{{ $transaction->type }}
#endforeach
#endif
I get this error
I think you are looking for hiding view until user searched any one field.So you can do the following
#if( $transactions->count() > 0 &&collect($request->all())->filter()->isNotEmpty())
if you want to ignore page from checking then you can use except
collect($request->except('page'))->filter()->isNotEmpty()
Better don't execute query until one of the filter value is filled because any way you don't to display it in view
public function index(Request $request)
{
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
$transactions=[];
if(collect($request->all())->filter()->isNotEmpty()){
$transactions = UserTransaction::query();
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
$transactions->paginate(5)->appends($request->except('page'))
}
return view('admin.transaction.index',[
'transactions' =>$transactions,
'stats' => $stats
]);
}
Also instead of repeating collect($request->except('page'))->filter()->isNotEmpty() this in multiple place ,you can assign to variable in controller
You should check in the controller whether data has been entered or not. If not, then return the null for $transactions.
public function index(Request $request)
{
if(count($request->all()) > 0) {
$transactions = UserTransaction::query();
$userId = request()->get('userId');
$price = request()->get('price');
$type = request()->get('type');
$status = request()->get('status');
$ordering = request()->get('ordering');
if($userId){
$transactions->where('userId' , $userId);
}
if ($price) {
$transactions->where('price' , $price);
}
if ($type) {
$transactions->where('type' , $type);
}
if ($status) {
$transactions->where('status' , $status);
}
$transactions= $transactions->paginate(5)->appends($request->except('page'))
} else {
$transactions = null;
}
return view('admin.transaction.index',[
'transactions' => $transactions,
'stats' => $stats
]);
}
Then in your view just check $transactions->count() > 0

SESSION in laravel for page protection

I want to make a Login Registration system in laravel 8. In which User when login only can access a particular page else redirect to login page. I did this like that. what's wrong in it.
//Login Code
function login(Request $req){
$results = DB::table('crud_users')
->where('email', '=', $req -> post('email'))
->where('password', '=', $req -> post('password'))
->get();
foreach ($results as $value) {
$value ->email;
$value ->password;
$name = $value ->name;
$user_type = $value ->user_type;
echo $id = $value ->id;
session()->put('id', $id);
session()->put('name', $name);
}
$req -> validate([
'email' => 'required',
'password' => 'required',
]);
$email = $req -> input('email');
$password = $req -> input('password');
if ($user_type == 'admin') {
if (($email == $value ->email) && ($password == $value->password)) {
return redirect('admin');
}
} else if($user_type == 'user') {
if (($email == $value ->email) && ($password == $value->password)) {
return redirect('user');
} else{
return redirect('login');
}
// session()->flash('success','You are registered! Please login!');
// return redirect('login');
}
}
//Session Code
if (session()->has('id')) {
Route::get('logout','App\Http\Controllers\User#logout');
Route::view('user','user');
Route::view('admin','admin');
Route::view('edit/{id}','edit/{id}');
}else{
Route::get('/', function () {
return view('welcome');
});
you can use the default authentication in laravel8 using laravel application Jetstream starter kit and use the auth() middleware to go to a particular page.
you can see this [blog]1
or see the laravel's documentation from [here]2
for your code you're i think you're call session by this way session() it's wrong you should call the session class or use this way like this $request->session()->has('id')
or
Session::has('id')
I always use like following code
Session::put('id',$id);
Session::put('name',$name);
And in your conditional value you have to use like
if(Session::get('id')!=''){
Route::get('logout','App\Http\Controllers\User#logout');
...
}
else{
return redirect('/');
}
you can use auth() middleware for login authentication.
for more info https://laravel.com/docs/7.x/authentication

Transfer variable from one to another function in controller

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'))}}

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);
}
?>

Can't delete a record in Laravel 5

I'm having trouble in deleting a record that has file in it. Below is the code.
delete file method :
private function deletePDF(Journal $journal) {
$exist = Storage::disk('file')->exists($journal->file);
if (isset($journal->file) && $exist) {
$delete = Storage::disk('file')->delete($journal->file);
if ($delete) {
return true;
}
return false;
}
}
Destroy method :
public function destroy(Journal $journal, EditionRequest $request) {
$this->deletePDF($journal);
$journal->delete();
return redirect()->route('edition', ['id' => $request->id]);
}
The result game me nothing, it's just return to the page where the record belongs and does not deleting the record. I used the same code for another project with the same laravel version and it's working, but for some reasons it doesn't work here and I'm a lil bit confused.
Update :
EditionRequest :
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
} else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
If it returns to the same page as before, you probably have a validation error in your request!
You can check the errors easily by adding the following snippet to your view:
#if(count($errors) > 0)
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
With this you should be able to see what's going wrong. Let me know if it worked :)
edit
public function rules() {
// Cek apakah CREATE atau UPDATE
$id = $this->get('id');
if ($this->method() == 'PATCH') {
$volume_rules = 'required|integer|unique_with:edition,number,' . $id;
$number_rules = 'required|integer';
}
else if($this->method() == 'DELETE'){
//your delete validation rules rules
$volume_rules = ''
$number_rules= '';
}
else {
$volume_rules = 'required|integer|unique_with:edition,number';
$number_rules = 'required|integer';
}
return [
'volume' => $volume_rules,
'number' => $number_rules,
'cover' => 'sometimes|image|max:15000|mimes:jpeg,jpg,bmp,png',
];
}
You might even want to not use the request youre using now, which would give you this:
public function destroy(Journal $journal, Request $request)

Categories