A simple question: how do I modify (hash) the request value before saving it with Laravel Backpacker CRUD admin?
As far as i understand, it should be done somewhere before these methods are executed in the crud controller:
public function store(StoreRequest $request)
{
return parent::storeCrud();
}
public function update(UpdateRequest $request)
{
return parent::updateCrud();
}
but I have no idea how to do it correctly.
Edit: the request is not a Request object, but rather StoreRequest or UpdateRequest that looks something like this:
Fix:
public function update(UpdateRequest $request)
{
// Hash password before save
if (!empty($request->password)) {
$request->offsetSet('password', Hash::make($request->password));
}
return parent::updateCrud($request); // <-- Pass the modified request, otherwise the CRUD reads it again from post data
}
You can update $request values using the offsetSet method
$request->offsetSet('name', $newName);
Edit: To update user password you can do something like this:
public function update_password(Request $request)
{
$user = User::find(Auth::user()->id);
if (Hash::check($request->old_password, $user->password)) {
$user->fill([
'password' => Hash::make($request->password)
])->update();
return redirect()->back()->with('message' => 'Your password has been updated.');
}
else {
return redirect()->back()->with('message' => 'The password entered do not match our records.');
}
}
I did not check the code but it should work. Now update it to your needs.
If you're asking about how to modify data in $request variable, you can just do this:
$request->property = 'New value';
Also, you can add data to reuqest itself (not into variable):
request()->request->add(['key' => 'value']);
Related
my delete function like this:
help me guys before I added this line return Redirect::route('attribute.index');
I had no error but after I have this error
405 Method Not Allowed
public function update($id)
{
$input = Input::all();
$validator = Validator::make($input, CapacityModel::rules());
// process the save
if ($validator->fails()) {
Session::flash('message', trans('messages.error_save'));
} else {
// store
$this->capacity->update($input['capid'], $input);
// redirect
Session::flash('message', trans('messages.success_save'));
return Redirect::route('attribute.index');
}
}
my route like this:
Route::resource('/reference/attribute','nez\attribute\SeiAttributeController',['names'=>'attribute']);
my controller's index like this:
public function index()
{
return View::make($this->view_path.'.index');
}
This looks questionable:
$this->capacity->update($input['capid'], $input);
Where does $this->capacity get resolved? Are you certain the attribute is always set at this point in the method?
The update method typically takes a single parameter, which is an array of keys with their new values.
If you have correctly resolved $this->capacity to the record you want to update, then you would be best off with something along these lines:
$this->capacity->update([
'field_1' => Arr::get($input, 'field_1'),
'field_2' => Arr::get($input, 'field_2'),
//...etc
]);
I want check if my form value equals in database value in laravel
Here is my controller class
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id , 'sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
What i do wrong?
update to
DB::table('users')->where(['id',$id ])->where([ 'sms_token_in'
,$sms_token])->update(['sms_verify'=>'1' ]);
The most simple way to use where is
two parameters, 1: database field name, 2: value
three parameters (field name, operator, value) ('1', '>=', 3)
DB::table('users')->where('id',$id)->where('sms_token_in', $sms_token)->update([
'sms_verify'=>'1'
]);
Try
DB::table('users')->where([
['id',$id],
['sms_token_in', $sms_token]
])->update([
'sms_verify'=>'1'
]);
First you must accept two parameter from your function. Look like only you are passing only one.
change function parameter to
public function code_post(Request $request, $id = 0)
then
if(!empty($id)){
User::where(['id' => $id,'sms_token_in' => $sms_token])->update([
'sms_verify'=>'1'
]);
}
// you can do this in two way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where('id',$id)->where('sms_token_in' ,$sms_token)->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
//2nd way
public function code_post(Request $request, $id)
{
$sms_token_in = $request->sms_token_in;
$sms_token=Auth::user()->sms_token;
DB::table('users')->where(['id',$id , 'sms_token_in' ,$sms_token])->update([
'sms_verify'=>'1'
]);
return redirect('/panel')->with('edit','pending');
}
The best whey to do it is on Validators in laravel so, if it don't exist create a classe validator that extends "LaravelValidator" and do it:
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'sms_token_in' => 'required|unique:your_table_name',
],
ValidatorInterface::RULE_UPDATE => [],
]; protected $messages = [
'sms_token_in.unique' => 'Your duplicate message!'
];
In your controller instantiate your validator in construct like it:
public function __construct(MyValidatorClass $validator)
{
$this->validator = $validator;
}
And in your controller function store do it, before your persist on database.
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
In this way, you can use validator from Laravel to check and return anything you want to your user.
function check(Request $request){
//validate
$request->validate([
'email'=>'required|email',
'user_pass'=>'required|min:5|max:12'
]);
$userInfo=Employee::where('email','=',$request->email)->first();
if(!$userInfo){
return back()->with('fail','We do not recognize your email address');
}else{
//check password
if($request->user_pass=$userInfo->user_pass){
$request->session()->put('LoggedUser', $userInfo->emp_id);
return redirect('/employee/dashboard');
}else{
return back()->with('fail','Incorrect password');
}
}
}
In this method im check if the user_pass from request is equal to $userInfo->user_pass that query from database.
if($request->user_pass=$userInfo->user_pass)
I'm working on a laravel 5.7 project and I want to have my own authentication scenario.
Well, I'll give a mobile from my user and send her a one time pass to her phone and then check if she is giving me the correct code.
So, I do not use laravel authentication system at this point at all.
My Controller is something like this :
/*
* Show Login Form
*/
public function showLoginForm()
{
return view('auth.custom.login');
}
/*
* Login
*/
public function login(Request $request)
{
$mobile = $request->mobile;
$this->validate($request, [
'mobile' => 'iran_mobile|required'
]);
$check = User::where('mobile', $mobile)->first();
if( $check === null )
{
Session::flash('toasterr', 'is not registered yet');
Session::put('mobile', $mobile);
return redirect(route('register'));
}
else
{
$singleTimePass = Str::random(4);
sendSms($mobile, 'your code:' . PHP_EOL . $singleTimePass . PHP_EOL . 'Insert that bla bla');
Session::put('singleTimePass', $singleTimePass);
Session::put('mobile', $mobile);
return redirect(route('check_pass'));
}
dd($check);
}
/*
* Show Check Pass page
*/
public function showCheckPass()
{
return view('auth.custom.pass');
}
/*
* Check Pass For Login
*/
public function checkPassForLogin(Request $request)
{
$this->validate($request, [
'pass' => 'required|regex:/^[\w-]*$/'
]);
if( $request->pass == Session::get('singleTimePass'))
{
$user = User::where('mobile', Session::get('mobile'))->first();
// dd($user->id);
Auth::login($user->id);
return redirect(route('game'));
}
else
{
Session::flash('toasterr', 'pass is wrong');
return redirect(route('check_pass'));
}
}
/*
* Show Register Form
*/
public function showRegisterForm()
{
return view('auth.custom.register');
}
/*
* Register
*/
public function register(Request $request)
{
$this->validate($request, [
'name' => 'persian_alpha|required',
'family' => 'persian_alpha|required',
'username' => 'required|min:4|max:255|string',
'mobile' => 'iran_mobile|required',
]);
return $request->all();
}
Ok! Every thing seems to be good but now, I expect laravel that give me abilities like Auth::check() or Auth::user() and...
So I know that I have an error at this line: Auth::login($user->id); and I want to know how can I do something like this manually for mentioned goal.
May be it is because of my poor knowledge about laravel authentication architecture but it would be appreciate if you let me know how do that because googled this for a while and there's not direct answer to this question-or I did not searched enough-.
Based on the documentation the login method expects a User object to log you in. So you can either try
Auth::login($user);
// or
Auth::loginUsingId($user->id);
I'm using yii framework. I have made a condition where users are not allowed to insert a same data.
here is my code
model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('DEP_CD', 'length', 'max'=>5),
array('DEP_CD', 'required'),
array('DEP_CD', 'cekPK'),
);
}
public function cekPK()
{
$model = self::findByPk(array($this->DEP_CD));
if ($model)
$this->addError('field1', 'Data sudah ada');
}
this code works for not allowing user to insert a same data. but when they edit/update the data, it keep saying that data is exist. I need to make users allowed to edit but not inserting the same data only
thanks
A work around could be:
public function cekPK()
{
if ($this->isNewRecord)
{
$model = self::findByPk(array($this->DEP_CD));
if ($model)
$this->addError('field1', 'Data sudah ada');
}
}
I am new to laravel.I have a controller called userController to mangae user in my application.Here i have a user authentication and profile system.It will send the user to its own profile after login.Sometimes user may wish to search for a random username or id field in the url to search for a user.If desired user is found ,their profile info will be shown in the profile section.But if no user is found i want my application to get the current logged in user and show his/her info instead.How i can do that?
if my user name is 'zim' i can write the url mydomain/user/zim ,it will get my profile,But if i search an invalid name say 'zi' mydomain/user/zi , i want my application to return mydomain/user/zim again
All i can manage here is to show a flash message if no user is found.Can't figure out how to retrieve the current logged user.Tried to use the Request class but seems not working
loginUser function():
public function loginUser(Request $request){
$data = $request->all();
$rules = array(
'name' => 'required',
'password'=>'required'
);
// Create a new validator instance.
$validator = Validator::make($data, $rules);
if($validator->fails()){
$errors=$validator->messages();
return redirect()->back()->withErrors($validator);
}else{
if(Auth::attempt(['name'=>$request['name'],'password'=>$request['password']])){
return redirect()->route('user.show',[$request['name']]);
}else{
return redirect()->back()->with('data', 'wrong username or password');
}
}
}
show() method in userController:
public function show($user,Request $request) // tried with Request but failed
{
//
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if($info){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user');
return View::make('user.show');
}
}
You just need to change your show method slightly.
public function show($user,Request $request)
{
$indicator=is_numeric($user)?'id':'name';
$info=userModel::where($indicator,'=',$user)->get()->first();
if(empty($info)){
return View::make('user.show')->with('user',$info);
}else{
session()->flash('message','no user but here is your info :)');
return View::make('user.show')->with('user', Auth::user());
}
}
Edited for better logic.
public function show($username)
{
$info = userModel::where(username, $username)->get()->first();
if($info != null){
return View::make('user.show')->with('user', $info);
}
else{
session()->flash('message','No user found! But here is your info!');
return View::make('user.show')->with('user',Auth::user());
}
}
Here is a much simplified option. (Always allow the URL to collect only one type instead of checking if its id or username)