Laravel 4 login validation issue - validation

I'm having trouble logging in. Even when there are no validation errors to be found, it goes to the else statement block in my postIndex method and brings me back to the login page. Any idea on what the problem is and what do i need to change to fix it?
routes.php
<?php
Route::get('/', 'HomeController#getGuestIndex');
Route::controller('login', 'LoginController');
?>
HomeController.php
<?php
class HomeController extends BaseController {
public function getGuestIndex()
{
return View::make('guests.index');
}
public function getAdminIndex()
{
return View::make('admin.index');
}
}
?>
LoginController.php
<?php
class LoginController extends BaseController {
public function getIndex()
{
// Check if we are already logged in.
if (Auth::check()) {
return Redirect::action('HomeController#getAdminIndex')
->with('message', 'You are already logged in');
}
return View::make('guests.login')
->with('title', 'Login');
}
public function postIndex()
{
// Get all the inputs
$user = array(
'username' => Input::get('username'),
'password' => Input::get('password')
);
$validation = User::validate($user);
if ($validation->passes()) {
// Try to log the user in.
if (Auth::attempt($user)) {
return Redirect::action('HomeController#getAdminIndex')
->with('message', 'You have logged in successfully');
}
return Redirect::to('login')
->withErrors($validation)
->withInput(Input::except('password'));
} else {
// Something went wrong.
return Redirect::back()
->withErrors($validation)
->withInput(Input::except('password'));
}
}
}
?>
BaseModel.php
<?php
class BaseModel extends Eloquent {
public static function validate($inputs)
{
return Validator::make($inputs, static::$rules);
}
}
?>
User.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends BaseModel implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password');
protected static $rules = array(
'username' => 'required|alpha_dash|min:4',
'email' => 'required|email',
'password' => 'required|alpha_num|min:8|confirmed',
'password_confirmation' => 'required|alpha_num|min:8'
);
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword()
{
return $this->password;
}
public function getReminderEmail()
{
return $this->email;
}
}
?>
login.blade.php
#extends('layouts.master')
#section('content')
<h2>Login into your account</h2>
{{ Form::open(array('url' => 'login')) }}
<p>
{{ Form::label('username', 'Username') }}
{{ Form::text('username', Input::old('username')) }}
</p>
<p>
{{ Form::label('password', 'Password') }}
{{ Form::password('password') }}
</p>
<p>
{{ Form::submit('Login') }}
</p>
{{ Form::close() }}
<p>{{ $errors->first('username') }}</p>
<p>{{ $errors->first('password') }}</p>
#stop

Based on your question and example script the validation is failing.
The problem is likely with the model based validation implementation. You are validating login with registration rules.
One set of validation rules does not fit all situations.
If you add the following lines to your login.blade.php I think you will see additional errors:
<p>{{ $errors->first('email') }}</p>
<p>{{ $errors->first('password_confirmation') }}</p>
To fix it, you will need to either change the validation rules on your model, or change the validation implementation. These two excellent tutorials show a couple approaches:
https://tutsplus.com/lesson/validation-services/
https://tutsplus.com/lesson/validating-with-models-and-event-listeners/

Related

Laravel authentication fails to redirect

I'm trying to make an auth system to block any access without login but the authenticated method always loads the login page. I override all methods in AuthenticatesUsers because I changed the users' table name and columns but always seem to end up loading the login page. I can return a view in the authenticated method but these will redirect me to the login page if I try to go to another page.
my DB
my login form
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ Form::open(['action' => 'Auth\LoginController#login','methode' => 'POST']) }}
{{Form::text('login', old('username') ?: old('email'),['class'=>''.$errors->has('email')||$errors->has('username') ? 'is-invalid' : ''.' form-control' ,'placeholder'=>'Nom d\'utilisateur ou email' ,'required', 'autofocus'])}}
#if ($errors->has('username') || $errors->has('email'))
<span class="invalid-feedback">
<strong>{{ $errors->first('username') ?: $errors->first('email') }}</strong>
</span>
#endif
{{Form::password('mot_de_passe', ['class'=>''.$errors->has('password')? 'is-invalid' : ''.' form-control','placeholder'=>'Mot De Passe' , 'required'])}}
#if ($errors->has('password'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
<button type="submit" class="btn btn-outline-info btn-block"><i class="ft-unlock"></i>
{{ __('Login') }}
</button>
{{ Form::close() }}
</body>
</html>
PagesController
class PagesController extends Controller
{
protected $redirectTo = '/'; // Redirect after successfull login
public function __construct()
{
$this->middleware('auth');
}
public function tableau_bord()
{
return view('pages.tableau_bord');
}
}
Methods using when login in LoginController
class LoginController extends Controller
{
protected $redirectTo = '/';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->username = $this->findUsername();
}
public function findUsername()
{
$login = request()->input('login');
$fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' :
'nom_utilisateur';
request()->merge([$fieldType => $login]);
return $fieldType;
}
public function login(Request $request)
{
$this->validateLogin($request);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
protected function validateLogin(Request $request)
{
$request->validate([
$this->username => 'required|string',
'mot_de_passe' => 'required|string',
]);
}
protected function attemptLogin(Request $request)
{
return $this->guard()->attempt(
array($this->username => $request->login, 'password' =>
$request > mot_de_passe)
);
}
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
protected function authenticated(Request $request, $user)
{
return redirect()->to($this->redirectPath());
}
public function redirectPath()
{
if (method_exists($this, 'redirectTo')) {
return $this->redirectTo();
}
return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
}
public function redirectTo()
{
return $this->redirectTo;
}
protected function sendFailedLoginResponse(Request $request)
{
throw ValidationException::withMessages([
$this->username() => [trans('auth.failed')],
]);
}
public function username()
{
return $this->username;
}
protected function credentials(Request $request)
{
return $request->only($this->username(), 'mot_de_passe');
}
}
if any one has this problem i solved by rename the table to users and the email/password fields in the DB & login form & loginController & config/auth.php ...
basically back to stage after make:auth command apparently laravel hate change the users table :(

Laravel 5.3 How to use multiple controllers in one view

I'm working with a view that at first displays all products, and on the sidebar, users can see a list of categories. My aim is when users press on any categories, it will display products of that category only. However, since there are 2 controllers is interacting with this view and send the same data, one is not running(CategoriesController). It does not show any error, just when I click on the link of each of the categories, it does not reload the page.
Here is my ProductsController:
class ProductsController extends Controller
{
// display all products and categories
public function index() {
$products = Product::all();
$categories = Category::all();
return view('frontend.product', compact('products','categories'));
}
And my CategoriesController:
class CategoriesController extends Controller
{
public function showProducts($category_id) {
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products'));
}
Here is my view:
// Products part
#foreach($products as $product)
{{ $product->name }}
#endforeach
//Categories part
#foreach($categories as $category)
{{ $category->name }}
#endforeach
And route:
Route::get('/products', [ 'as' => 'products', 'uses' => 'frontend\ProductsController#index']);
Route::get('/categories/{category_id}', ['as' => 'categories', 'uses' => 'backend\CategoriesController#showProducts']);
Just include all of the categories in your showProducts function, and omit the current category:
public function showProducts($category_id)
{
$categories = Category::whereNotIn('id', $category_id)->get();
$products = Category::find($category_id)->products;
return view('frontend.product', compact('products', 'categories'));
}
Now there will be no discrepancies between the variables that are being used.
If I have not misunderstood, I thought you can use #inject in blade. For example:
namespace App\Presenters;
use App\User;
class UserPresenter
{
/**
* 是否顯示email
* #param User $user
* #return string
*/
public function showEmail(User $user)
{
if ($user->show_email == 'Y')
return '<h2>' . $user->email . '</h2>';
else
return '';
}
}
and
<div>
#inject('userPresenter', 'MyBlog\Presenters\UserPresenter')
#foreach($users as $user)
<div>
{!! $userPresenter->showEmail($user) !!}
</div>
</div>

Passing data to email view Laravel 5.3

I have this scenario in my app where I have to send user's password and username to their email right away after their account created by admin. Here is what I've done so far :
Controller :
public function store(Request $request) {
$data = $request->all();
$validasi = Validator::make($data, [
'name' => 'required|max:255',
'username' => 'required|max:255|unique:users',
'email' => 'required|email|max:150|unique:users',
'password' => 'required|confirmed|min:6',
'level' => 'required|in:admin,author',
]);
if ($validasi->fails()) {
return redirect('user/create')->withInput()->withErrors($validasi);
}
$data['password'] = bcrypt($data['password']);
$email = $data['email'];
Mail::to($email)->send(new UserAdded());
User::create($data);
return redirect('user');
}
The email will send successfully but I want to pass $data['username'] and $data['password'] to email view as well.
email view :
<div class="row">
<div class="col-sm-12 col-xs-12">
<h2><span>Welcome new User!</span></h2>
<p>Your username </p>
<p>Your password</p>
</div>
Mailable function :
class UserAdded extends Mailable
{
use Queueable, SerializesModels;
public function __construct()
{
}
public function build()
{
return $this->view('email/newuser');
}
}
How to do it ? where will I define the $user data ? thanks for the help!
First of all, you need a class that builds the view. There you can define properties which you'll pass to the class. They'll be accessable in the view then.
<?php
namespace App\Mail;
use App\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class UserAdded extends Mailable
{
use Queueable, SerializesModels;
public $username;
public $password;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
public function build()
{
return $this->view('reference.your.view.path.here'); //CHANGE
}
}
You can now access the variables in your view.
<div class="row">
<div class="col-sm-12 col-xs-12">
<h2><span>Welcome new User!</span></h2>
<p>Your username: {{$username}} </p>
<p>Your password: {{$password}} </p>
</div>
Calling your view can be realized like this:
Mail::to($email)->send(new UserAdded($data['username'],$password));

How to show the comments which belongs to the post?

I'm creating a news feed kind of thing where users can post anything and the post will have comments also. I'm able to create the newsfeed and the comment section, but my real problem is I'm not able to show the comments which belongs to the post. Right now all the comments are displayed under every news feed. Though I've declared the eloquent relationship between feed and comment but still I'm not able to save the feed_id in comment table.
This is my FeedsController:-
<?php namespace App\Http\Controllers;
use Request;
use Auth;
use Sentinel;
use App\Feed;
use App\Http\Requests;
use App\Blog;
use App\Http\Controllers\Controller;
use App\Comment;
class FeedsController extends Controller
{
public function index() {
$comments = Comment::latest()->get();
$feeds = Feed::where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index')->with('feeds', $feeds)->with('comments', $comments)->with('blogs', $blogs);
}
public function store(Requests\CreateFeedRequest $request){
$requet = $request->all();
$request['user_id'] = Sentinel::getuser()->id;
Feed::create($request->all());
return redirect('home');
}
public function storecomment(Requests\CommentRequest $request, Feed $feed)
{
$comment = new Comment;
$comment->user_id =Sentinel::getuser()->id;
$comment->feed_id = $request->feed_id;
$comment->comment = $request->comment;
$comment->save();
return redirect('home');
}
}
This is the models:
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
Feed model:
use Illuminate\Database\Eloquent\Model;
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
User model:-
<?php namespace App;
use Cartalyst\Sentinel\Users\EloquentUser;
use Illuminate\Database\Eloquent\SoftDeletes;
class User extends EloquentUser {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes to be fillable from the model.
*
* A dirty hack to allow fields to be fillable by calling empty fillable array
*
* #var array
*/
protected $fillable = [];
protected $guarded = ['id'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* To allow soft deletes
*/
use SoftDeletes;
protected $dates = ['deleted_at'];
public function feeds()
{
return $this->hasMany('App\Feed');
}
public function comment()
{
return $this->hasMany('App\Comment');
}
}
This is my feed.blade.php where I'm displaying the feeds output and commnets
#foreach($feeds as $feed)
<article class="media">
<div class="well">
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'.$feed->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
<strong>{{ $feed->user->first_name }}
{{ $feed->user->last_name }}
<small> posted </small>
</strong>
{{ $feed->created_at->diffForHumans() }}<br><hr>
{{ $feed->feed_content }}
<hr>
{!! Form::open(['url' => 'home/{storecomment}']) !!}
<div class="form-group">
{!! Form::text('comment', null, ['class'=>'form-control', 'rows'=>3, 'placeholder'=>"Comment"]) !!}
</div>
<div class="form-group feed_post_submit">
{!! Form::submit('Comment', ['class' => 'btn btn-default btn-xs']) !!}
</div>
{!! Form::close() !!}
#foreach($comments as $comment)
<div class="pull-left">
<img class="profile" src="{{ URL::to('/uploads/users/'. $comment->user->pic) }}" class="img-responsive" alt="Image" style="width:48px;height:48px;padding-right : 10px;padding-bottom: 5px;">
</div>
{{ $comment->user->first_name }}
{{ $comment->created_at->diffForHumans() }}
{{ $comment->comment }}<hr>
#endforeach
</div>
</article>
#endforeach
Can anyone tell me how to store the feed_id into comment table and displaying the comments according to the feed. Thank You. I'm using Laravel 5.1
Based on our lengthy convo -
To save the feed_id (which is our foreign key for future relationships), you need to set/send the feed_id in your POST request. Laravel is not magic and won't know this automatically. You can do this by adding a hidden input, like so:
<input type="hidden" name="feed_id" value="{{ $feed->feed_id }}" />
In your FeedController, change your index to this:
public function index() {
// $comments = Comment::latest()->get(); remove this
// notice the "with" below. I'm eager loading in relations here
$feeds = Feed::with('comments', 'user')->where('user_id', Sentinel::getUser()->id)->latest()->get();
$blogs = Blog::latest()->simplePaginate(5);
$blogs->setPath('blog');
return view('action.index', compact('feeds', 'blogs'));
}
Feed Model should have the correct relationships, as below:
class Feed extends Model
{
protected $fillable = [
'feed_id',
'user_id',
'feed_content'
];
public function user()
{
return $this->belongsTo('App\User', 'id', 'user_id');
}
public function comments()
{
return $this->hasMany('App\Comment', 'feed_id', 'feed_id');
}
}
Comment Model should have the correct relationships, as below:
class Comment extends Model
{
protected $fillable = [
'comment',
'user_id',
'feed_id'
];
public function feed()
{
return $this->belongsTo('App\Feed');
}
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id');
}
}
Now you should be able to run your foreach as you currently have it.

Laravel 4 - get images of item in blade view

I'm new in Laravel and stuck with a noob problem. I have 3 tables, users, items, item_images. When i post a item i save the images to item_images with the item_id and the other input data to the items table. now, how to get the first of x images for the item in my foreach loop?
This is my view
#foreach ($items as $item)
<div class="item">
<div class="item-image">
<img src="/uploads/{{ $item->image }}"/>
</div>
{{ $item->title }}
{{ $item->type }}
{{ $item->label }}
</div>
#endforeach
This is the ItemImages Controller
<? class ItemImages extends Eloquent {
protected $fillable = array(
'item_id',
'image'
);
protected $table = 'item_images';
public function item() {
return $this->belongsTo('Item');
}
}
The Item Controller
<? class Item extends Eloquent {
protected $fillable = array(
'user_id',
'type',
'title',
'label'
);
protected $table = 'items';
public function item() {
return $this->hasMany('ItemImages');
}
}
And the home controller
<?php class HomeController extends BaseController {
public function home() {
$items = Item::all();
$images = ItemImages::all();
$users = User::orderByRaw("RAND()")->take(2)->get();
return View::make('home', array(
'items' => $items,
'users' => $users,
'images' => $images
));
}
}
thanks in advance.
Looks like you have not defined relationships. I believe doing that will make the answer much simpler than the following:
<img src="/uploads/{{
$images->filter(function($image) use( $item ) {
return $image->item_id == $item->id;
})->values()->image
}}"/>

Resources