this is the route in web.php:
Route::put('/users.status', [\App\Http\Controllers\dashboard\UsersController::class, 'status'])->name('users.status');
and here is the code in Controller:
public function status(User $user) {
try{
$user->is_active = 1;
$user->update();
//$user->update(['is_active' => 1 ]);
}catch (\Exception $ex) {
return redirect()->route('users.index')->with('status', "you couldn't update this record");
}
return redirect()->route('users.index')->with('status', 'User Updated successfully');
}
here is the code in a view, it just a button, when click on it, I need to change the status:
<td class="border px-4 py-2">
<form method="POST" action="{{route('users.status', $user)}}">
#csrf
<input type="hidden" name="_method" value="put"/>
<button type="submit"
class="{{ $user->is_active==1 ? "bg-green-500" : "bg-red-500" }} hover:bg-red-700 text-white font-bold py-1 px-1 rounded">
{{$user->is_active==1 ? "Active" : "Inactive"}}
</button>
</form>
</td>
after the button above has clicked, give me this message:
User Updated successfully
but nothing updated in database
First which User you are trying to fetch from route to controller method? You are trying to inject a User $user object to controller method but you did not specified a user param on route definition.
And on the update part; after you set $user->is_active = 1; you need to run $user->save();
So; you need to add a user param to your route:
Route::put('/users/{user}/status', [\App\Http\Controllers\dashboard\UsersController::class, 'status'])->name('users.status');
and run save() method on updated $user ;
public function status(User $user)
{
try {
$user->is_active = 1;
$user->save();
} catch (\Exception $ex) {
return redirect()->route('users.index')->with('status', "you couldn't update this record");
}
return redirect()->route('users.index')->with('status', 'User Updated successfully');
}
You should call $user->save(); not $user->update();
Also, you can call $user->update(['is_active'=>1]); to have only one line of code.
Related
I want to display an error in a form, but it cannot be checked via validation.
Blade
<form action="/githubuser" methode="GET">
<div class="error">{{ $errors->first('CustomeError') }}</div>
<input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
#if($errors->has('userName'))
<div class="error">{{ $errors->first('userName') }}</div>
#endif
<input type="submit" value="SUBMIT">
</form>
The Problem is that I start an api call after validation. and if I don't get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.
Controller
public function show(Request $request)
{
$rules = ['userName' => 'required'];
$validator = \Validator::make($request->input(), $rules);
if ($validator->fails()) {
return redirect('/')
->withErrors($validator)
->withInput();
}
$data = $this->gitHubUserService->getUserData($request->input('userName'));
/* User on Github not Found **/
if (! $data) {
// >>> THE LINE BELOW IS MY PROBLEM! <<<
return view('form')->withErrors($validator);
}
// ....
}
At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.
Is this possible? Thanks in advance!
The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:
if(! $data){
$validator->errors()->add('customError', 'Github User not found!');
return view('form')->withErrors($validator);
}
Controller
public function index()
{
//load session library
$this->load->library('session');
if($this->session->userdata('user')){
// redirect('home');
$this->load->view('heropage');
}
else{
$this->load->view('login_page');
}
}
public function login(){
$email = $_POST['email'];
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if($data)
{
$id=$data[0]->id;
$first_name=$data[0]->firstname;
$last_name=$data[0]->lastname;
$grade=$data[0]->grade;
$points=$data[0]->points;
$this->session->set_userdata('user_id',$id);
$this->session->set_userdata('lname',$last_name);
$this->session->set_userdata('user', $email);
$this->session->set_userdata('fname',$first_name);
$this->session->set_userdata('grade',$grade);
$this->session->set_userdata('pts',$points);
$this->getImg();
redirect('home');
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found'); }
}
View
<?php if(isset($_SESSION['success'])) :?>
<div class="alert alert-success"><?=$_SESSION['success'];?></div>
<?php endif; if(isset($_SESSION['error'])) :?>
<div class="alert alert-warning"><?=$_SESSION['error'];?></div>
<?php endif;?>
<!-- End alerts -->
<form action="<?php echo base_url();?>index.php/User/login" method="post" accept-charset="utf-8">
<div class="form-group">
<label>Email:</label>
<input type="text" class="form-control" name="email" placeholder="Email">
<?php echo form_error('email'); ?>
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" class="form-control"name="password" placeholder="Password">
<?php echo form_error('password'); ?>
</div>
<div class="form-group">
<button class="btn btn-sm btn-success" type="submit" align="center" name="login" class="submit">Log in</button>
</div>
</div>
</form>
model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email'=>$email));
if($query->num_rows() == 1 )
{
return $query->result();
}
}
Upon trying to log in, I got the error page cant be found. I want it to go to the home page if the session is correct. here is the error message:
404 Page Not Found
The page you requested was not found.
How can I solve the error because I have also set as needed in the routes
I think your form action should be <?php echo base_url(); ?>user/login
Also in your model you're not checking for password anywhere.
You're also not returning anything if the email is not found or more than 1 results are found -
($query->num_rows() == 1)
Model
public function login($email,$password)
{
$query = $this->db->get_where('users', array('email' => $email, 'password' => $password))->result(); // you should use row() here to return only 1 row.
return $query; // you should check the uniqueness of email on registration, not here -- not allow duplicate email on registration
}
Controller
public function login(){
$email = $_POST['email']; // $this->input->post('email');
$password = $_POST['password'];
$data = $this->Users_model->login($email, $password);
if( !empty($data) ) // if no result found it'll be empty
{
// your code
}
else{
header('location:'.base_url().$this->index());
$this->session->set_flashdata('error','Invalid login. User not found');
}
}
See, if this helps you.
In my Laravel-5.8 application, I have two submit buttons for different purposes:
Controller
public function store(StoreLeaveRequestRequest $request)
{
DB::beginTransaction();
try {
//check which submit was clicked on
if ($request->has('apply')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
if($employeelinemanagerid == $employeehodid )
{
$leaverequest->line_manager_notified = 1;
$leaverequest->hod_notified = 1;
}else{
$leaverequest->line_manager_notified = 1;
}
$leaverequest->save();
$this->getLineManagerUserId();
} elseif($request->has('draft')) {
$leaverequest = new HrLeaveRequest;
$leaverequest->authorized_days = $request->authorized_days;
$leaverequest->available_days = $request->available_days;
$leaverequest->no_of_days = $days;
$leaverequest->save();
}
DB::commit();
Session::flash('success', 'Leave Request is created successfully');
return redirect()->route('service.leave_requests.index');
}
catch (Exception $exception)
{
dd($exception->getMessage());
DB::rollback();
Session::flash('error', 'Action failed!');
return redirect()->route('service.leave_requests.index');
}
}
view
<form action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" name="apply" class="btn btn-primary">Submit</button>
<button type="submit" name="draft" class="btn btn-warning">Save as Draft</button>
</div>
</form>
I used name="apply" for
($request->has('apply'))
and name="draft" for
($request->has('draft'))
When I click on any of the submit buttons, I got this error:
"Undefined variable: request"
I tried to check, I don't know where the error is coming from
Where did I get it wrong?
Kindly assist.
Thanks
I want to delete a record: remove a routine,that belongs to a user, on button click (hasMany). I have set up the view, models and relationship within,delete route, and the controller method to delete.
When I try to click the button to remove the routine from the db, it does nothing. why does it not removing the record?
Here's my code: route:
Route::post('routine/delete', 'RoutineController#delete'); // Delete a routine for a user.
Controller:
public function delete(Request $request)
{
$id = $request->input("id"); // Getting the id via. the ajax request.
$routine = \App\Routine::find($id); //Fetching the routine object from the db ifentified by the id passed via ajax
if ($routine)
{
$routine->delete();
}
return ["status" => "success"];
}
View:
<div class="col-lg-2">
<!-- When this button is clicked, we determine which routine to remove. -->
<button class="btn btn-danger remove_routine" data-id="{{$routine->id}}" data-token="{{csrf_token()}}" style="display:inline">Delete</button>
</div>
User Model:
public function routine()
{
return $this->hasMany('App\Routine');
}
Routine model:
public function user()
{
return $this->belongsTo('App\User');
}
Thanks in advance!
Don't know if it exactly answers your question, and I don't use AJAX, but I always do my deletes like this:
View
#foreach($database-thing as $item)
<form method="POST" action="$yourActionHere" style="display:inline" >
<input name="_method" type="hidden" value="DELETE">
<button type="submit" class="btn btn-danger btn-xs"><i class="fa fa-trash"></i> Delete</button>
</form>
#endforeach
// Even easier with laravelcollective/forms
#foreach($database-thing as $item)
{!! Form::open([
'method'=>'DELETE',
'url' => [$yourUrl, $item->id // <-- Very important],
'style' => 'display:inline'
]) !!}
{!! Form::button('<i class="fa fa-trash"></i> Verwijder', ['type' => 'submit', 'class' => 'btn btn-danger btn-xs']) !!}
{!! Form::close() !!}
#endforeach
Controller
public function destroy($id)
{
YourModel::destroy($id);
// All your other logic like redirects and stuff
}
Working delete, based on the code above and this updated controller function:
public function delete(Request $request,$id)
{
$user=Auth::user();
$routine = \App\Routine::findOrFail($id); // find or throw an error if you don't find the routine id in db.
// Makes if() statement redundant, since it checkes for that id already.
// Need to check that the owner of the routine is the current authenticated user.
if ($user->id != $routine->user->id)
{
Session::flash('flash_message', 'No routine found.');
}
else
{
$routine->delete();
Session::flash('routine_deleted','Routine deleted!');
}
// No need to return $routine since I am deleting it, otherwise it will throw and error of trying to get property of non-object.
return redirect()->back()->with('user') ;
//return view('view_routine')->with('user', 'routine');
}
There you go
$remove = 2;
$filtered = $c->filter(function ($value, $key) use($remove){
return $value['id']!=$remove;
});
I'm trying to get a login form to 'remember' the user logging in and I just can't work out how to do it.
Here's my controller
public function getLogin()
{
// Return the view with the data
return View::make('users.login');
}
public function postLogin()
{
// Gather Sanitized Input
$input = array(
'email' => Binput::get('email'),
'password' => Binput::get('password'),
'rememberMe' => Binput::get('rememberMe')
);
// Set Validation Rules
$rules = array (
'email' => 'required|min:4|max:64|email',
'password' => 'required|min:6'
);
//Run input validation
$v = Validator::make($input, $rules);
if ($v->fails())
{
// Validation has failed
return Redirect::to('users/login')->withErrors($v)->withInput();
}
else
{
try
{
//Check for suspension or banned status
$user = Sentry::getUserProvider()->findByLogin($input['email']);
$throttle = Sentry::getThrottleProvider()->findByUserId($user->id);
$throttle->check();
// Set login credentials
$credentials = array(
'email' => $input['email'],
'password' => $input['password']
);
// Try to authenticate the user
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Sentry::loginAndRemember($user);
}
catch (Cartalyst\Sentry\Users\UserNotFoundException $e)
{
// Sometimes a user is found, however hashed credentials do
// not match. Therefore a user technically doesn't exist
// by those credentials. Check the error message returned
// for more information.
Session::flash('error', 'Invalid username or password.' );
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Users\UserNotActivatedException $e)
{
echo 'User not activated.';
Session::flash('error', 'You have not yet activated this account.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
// The following is only required if throttle is enabled
catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e)
{
$time = $throttle->getSuspensionTime();
Session::flash('error', "Your account has been suspended for $time minutes.");
return Redirect::to('users/login')->withErrors($v)->withInput();
}
catch (Cartalyst\Sentry\Throttling\UserBannedException $e)
{
Session::flash('error', 'You have been banned.');
return Redirect::to('users/login')->withErrors($v)->withInput();
}
return Redirect::to('/');
}
}
/**
* Logout
*/
public function getLogout()
{
Session::flush();
Sentry::logout();
return Redirect::to('/');
}
And here's my View
#extends('layouts/master')
{{-- Web site Title --}}
#section('title')
#stop
{{-- Content --}}
#section('content')
<div class="tck-well span6 offset3">
<h1>Login</h1>
<form class="" action="{{ URL::to('users/login') }}" method="post">
{{ Form::token(); }}
<div class="control-group {{ ($errors->has('email')) ? 'error' : '' }}" for="email">
<label class="control-label" for="email">E-mail</label>
<div class="controls">
<input name="email" id="email" value="{{ Request::old('email') }}" type="text" class="input-xlarge" placeholder="E-mail">
{{ ($errors->has('email') ? $errors->first('email') : '') }}
</div>
</div>
<div class="control-group {{ $errors->has('password') ? 'error' : '' }}" for="password">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input name="password" value="" type="password" class="input-xlarge" placeholder="New Password">
{{ ($errors->has('password') ? $errors->first('password') : '') }}
</div>
</div>
<div class="control-group" for"rememberme">
<div class="controls">
<label class="checkbox inline">
<input type="checkbox" name="rememberMe" value="1"> Remember Me
</label>
</div>
</div>
<div class="form-actions">
<input class="button button-large button-secondary" type="submit" value="Log In">
Forgot Password?
</div>
</form>
</div>
#stop
Can someone help point me in the right direction please?
You could also use the helper method:
if( Input::get('rememberMe') ) {
$user = Sentry::authenticateAndRemember($credentials)
} else {
$user = Sentry::authenticate($credentials, false);
}
Similar to Devo's
// Try to log the user in
Sentry::authenticate(Input::only('email', 'password'), Input::get('remember-me', 0));
// For the view page
<input type="checkbox" name="remember-me" id="remember-me" value="1" /> Remember me;
Instead of,
$user = Sentry::authenticate($credentials, $input['rememberMe']);
Use,
if(!empty($input['rememberMe'])) {
$user = Sentry::authenticate($credentials, true);
} else {
$user = Sentry::authenticate($credentials, false);
}
And make sure you are getting some value in $input['rememberMe'].
From GitHub it seems setting gc_maxlifetime in php.ini (or .htaccess) is sometimes necessary as well..
session.gc_maxlifetime = 2592000
In app/config/session.php add this lines:
'lifetime' => 999999,
'expire_on_close' => false,