How to create remember me action using laravel auth - laravel-4

i have a checkbox with my login form , which will remember user when checked . I am using following code but it doesnot works for me :
VIEW :
#extends('layouts.main')
#section('title') Dashboard
#stop
#section('content')
{{ Form::open(array('url'=>'users/signin', 'class'=>'form-signin')) }}
<h2 class="form-signin-heading">Please Login</h2>
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password')) }}
{{ Form::checkbox('remember_me','false',false,array('class'=>'input-block-level')) }}
{{ Form::submit('Login', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
#stop
CONTROLLER :
public function postSignin() {
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password'),'active' => 1),Input::has('remember_me'))) {
return Redirect::to('users/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
Please help me out on this , This function does not remembers user .
If you have some better code then please tell me that .
Thanks.

if you want to remember a user pass the third parameter true
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user is being remembered...
}
Your code:
public function postSignin() {
$rememberMe = false;
if(Input::has('remember_me')) {
$rememberMe = true;
}
if (Auth::attempt(array('email'=> Input::get('email'), 'password'=> Input::get('password') ), $rememberMe )) {
return Redirect::to('users/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}

Related

How to update user status using button without update all parameters in laravel

i want to update status user just pass parameter of 'status'.
this is my code, but i don't know, why i can not update user status. how to fix this problem?
my controller
public function activation()
{
// dd('test');
$action = Input::get('status');
if (Input::get('activate'))
{
$this->activateUser($action);
}
elseif (Input::get('inactivate'))
{
$this->deactivateUser($action);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
public function activateUser($user)
{
//dd('active');
User::findOrNew($user)->update(['status' => "1"]);
}
public function deactivateUser($user)
{
// dd('nonactive');
User::findOrNew($user)->update(['status' => "0"]);
}
my route
Route::post('admins-users/status', 'Backend\StatusController#activation');
my view
{!! Form::open(array('url' => 'admins-users/status')) !!}
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
After trying several ways. finally, i was found the answer for this problem using Ajax and select option. i add hash id before pass to controller and decode again in controller. i thinks id that pass must be concerned.
my controller
public function control(Request $request){
$status = $request->status;
$iduser = $request->iduser;
$key = Hashids::connection('main')->decode($iduser)[0] ?? abort(404);
$update = User::where('id', $key)->update(['status'=> $status]);
if($update)
{
return redirect(route('admins-users.index'))->with('message-post', 'Status user was updated successfully');
}
}
my form
using hash id to encode id user
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
{!! Form::hidden(null,$parameter, ['id'=> 'iduser'.$parameter ])!!}
{!! Form::select(
'status',
array(1=>'Active',0=>'Not Active'),
$user->exists ? $user->status : null,
[
'id' => 'action'.$parameter,
'placeholder' => 'Choose a status'
]
)
!!}
script
$(document).ready(function(){
#foreach($users as $user)
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
$("#action{{ $parameter }}").change(function(){
var status = $("#action{{ $parameter }}").val();
var iduser = $("#iduser{{ $parameter }}").val();
if(status==""){
alert("Please select an option");
}
else{
if (confirm('Do you want to change {{ $user->name }} status to {{ $user->status ? 'InActive' : 'Active' }}?')) {
$.ajax({
url: '{{ url("/action") }}',
data: 'status=' + status + '&iduser=' + iduser,
type: 'get',
success:function(response){
console.log(response);
}
});
document.location.reload();
}
}
});
#endforeach
});
Try with this
{!! Form::open(['url' => 'admins-users/status', 'method' => 'get' !!}
<input type="hidden" name="user_id" value="{{ $user->id }}">
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
Your route
Route::get('admins-users/status', 'Backend\StatusController#activation');
Your Controller Method
public function activation(Request $request)
{
$user_id = $request->user_id
if ($request->acticate) {
$this->activateUser($user_id);
}
elseif ($request->inactiavte) {
$this->deactivateUser($user_id);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
Hope this helps :)

Message not appear on page after function is performed in laravel

Maybe is something simple but can't understand why I don't see my message.
I have this in the controller after the function is submitted
return redirect()->route('item.show', $id)->with('alert-success', ' Review submitted successfully.');
And this in item page
#foreach (['danger', 'warning', 'success', 'info','message'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
The form is submitted successfully, data is saved in the database, the page is reloaded but the message does not appear for success.
update
array(4) {
["_token"]=>
string(40) "snB4uoaR087wrvXOuh8epR56cjtC2OCSmZJd9smn"
["_previous"]=>
array(1) {
["url"]=>
string(29) "http://example.com/item/17"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
["login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d"]=>
int(9)
}
Route
Route::group(['namespace' => 'Frontend', 'middleware' => 'web'], function () {
Route::post('items/review/{item}', 'ItemController#reviewSubmit')->name('item.review');
....
}
Use flash for message stuffs:
Controller
$request->flash('alert-success', ' Review submitted successfully.');
return redirect()->route('item.show', $id);
item page:
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div>
Check about flash message with laravel documentation
NOTE: Make sure the middleware not applied twice, this is also be the cause of this issue. Check this

Why my form is not sending data with POST in Laravel?

I'm creating my login page with Laravel
I want send my login form datas with POST method, but is not working
// /view/login.blade.php
/*
{{ Form::open([
"route" => "user/login",
"autocomplete" => "off",
'method' => 'POST'
]) }}
{{ Form::label("username", "Usuário:") }}
{{ Form::text("username", Input::old("username"), [
"placeholder" => "john.smith"
]) }}
{{ Form::label("password", "Senha:") }}
{{ Form::password("password", [
"placeholder" => "*******"
]) }}
{{ Form::submit("Entrar") }}
{{ Form::close() }}
//---------------------------------------
// routes.php
Route::any( '/', [
"as" => "user/login",
"uses" => "UserController#loginAction"
] );
//---------------------------------------
// /controllers/UserController.php
class UserController extends Controller
{
public function loginAction()
{
echo Input::server( "REQUEST_METHOD" ); // This line is ever print "GET"
return View::make( 'user/login' );
}
}*/
[Code edited]
// view/login.blade.php
<form action="{{URL::to('/')}}" method="post">
<input name="login" type="text"/><br/>
<input type="password" name="senha" id=""/><br/>
{{ Form::submit('Enviar') }}
</form>
// routes.php
Route::any('/', function()
{
echo Request::getMethod(); is returning GET forever
return View::make( 'login' );
});
Apparently, my form will send datas with POST method, but I can never get they in $_POST, why?
You should use:
Input::all()
to get all the data
or Input::get('username'), Input::get('password') and so on to get selected data.

Laravel 4 :: custom validation error message is not displaying?

I'm trying to create an online form and to display my own error messages. But for some reason it's not working correctly. Here's my controller code, CategoryController.php:
class CategoryController extends BaseController
{
public function add()
{
return View::make('admin');
}
public function validate_add()
{
$rules = array('category_name' => 'Required|Alpha|Min:4');
$messages = array('category_name.Required' =>'Please enter the category name');
$input = Input::all();
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin')->withErrors($validator)->withInput(Input::all());
}
else
{
echo '<h1>WOW! your are are awesome!!! <3<h1> ';
}
}
}
And the admin.blade.php is following:
#extends('common')
#section('body')
<h1>Add Category</h1>
{{ HTML ::ul($errors->all(), array('class'=>'errors')) }}
{{ Form::open(array( 'url'=>'admin', $title="Admin Control Panel")) }}
<p>
{{ Form::label('Category Name:') }}
{{ Form::text('category_name', Input::old('category_name')) }}
</p>
<p>
{{Form::label('Parent Category') }}
{{ Form::select('Network', array('0' => 'Maincategory')) }}
</p>
<p>
{{ Form::submit('Submit') }}
</p>
{{ Form::close() }}
#stop
Interesting - I tried this on my local Laravel project and it looks like although you can specify your rules in mixed case, you need to specify the custom messages in lower case.
So if you changed your rules and your message override to; 'required' instead of 'Required' etc., it should work.

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources