When you validate your data using a request service how do you return the the errors in json format like e.g.
return response->json(array("errors' => true, 'errors' => $errors));
Request Service:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Auth;
class MyRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
protected $action;
public function authorize()
{
if(Auth::check()) {
return true;
}
}
public function validate() {
return parent::validate();
}
public function all()
{
}
public function messages()
{
}
public function rules()
{
}
}
Controller:
public function store(MyRequest $request) {
$mymodel = new MyModel();
$mymodel->title = 'test';
$model->save();
}
You don't have to do it manually, it will automatically sends an errors response, which could be use like:
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
OR
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
OR
Skip Request and do Validator::make() and in the end do:
return response($validatorObject->messages(), 500);
Related
I'm using a custom encryption trait on my Journal model. I didn't create this code and vaguely understand how it works, but the original code can be found here on this Laracast forum post.
Encryption.php
<?php
namespace App;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if (in_array($key, $this->encryptable)) {
$value = Crypt::decrypt($value);
return $value;
}
return $value;
}
public function setAttribute($key, $value)
{
if (in_array($key, $this->encryptable)) {
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
}
Journal.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Journal extends Model
{
use Encryptable;
protected $encryptable = [
'content'
];
protected $fillable = ['content','user_id'];
}
I'm getting two problems:
Call to a member function toRfc822String() on null (View: /Applications/MAMP/htdocs/thought-records/resources/views/journal/index.blade.php)
When I remove toRfc822String() from my blade file it throws this error: The payload is invalid.
Here is the index.blade.php
<div class="card-body">
#if($entries->isEmpty())
<p>There is nothing here!</p>
#else
#foreach($entries as $entry)
<h3>{{ $entry->created_at }}</h3>
<div v-html="markdown('{{ htmlentities($entry->content) }}')"> </div>
<hr>
#endforeach
#endif
</div>
The getAttribute method has to return something. Your method returns void. Every attribute you try to access via the dynamic property, $model->attribute, will be null because of this.
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 :(
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.
I am getting error on this code so I start it from blade, then controller then modle kindly give me solution why this problem happened.
blade:
#extends ('lay')
#section('content')
<h1>Write a New Article</h1>
<hr>
{!!Form::open(['url'=>'articles'])!!}
<div class="form-group">
{!!Form::label('title','Title:')!!}
{!!Form::text('title','',['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::label('body','Body:')!!}
{!!Form::textarea('body','',['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::label('published_at','Published on:')!!}
{!!Form::input('date','published_at',date('Y-m-d'),['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!!Form::submit('Add Article',['class'=>'btn btn-primary form-control','name'=>'submit'])!!}
</div>
{!!Form::close()!!}
#stop
controller: this is my controller of the program all this is made in laravel
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Articles;
use Request;
use Carbon\Carbon;
class ArticlesController extends Controller {
public function index()
{
/*$art=[
'title'=>'ashwani',
'body'=>'rathi',
'published_at'=>'Carbon\Carbon::now()'
];
Articles::create($art);*/
$articles=Articles::latest()->get();
return view('articles.index', compact('articles'));
}
public function show($id)
{
$article=Articles::findorFail($id);
return view('articles.show',compact('article'));
}
public function create(){
return view('articles.create');
}
public function store()
{
//$input=Request::all();
//$input['published_at']=Carbon::now();
//Articles::create($input);
Articles::create(Request::all());
return redirect('articles');
}
}
model: this is model where i using date and its not working
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
class Articles extends Model {
protected $fillable= [ 'title', 'body', 'published_at' ];
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFormFormat('Y-m-d|', $date);
}
}
It looks like this is stemming from a small typo.
You have put createFormFormat, where you have spelt Form instead of From.
You just need to correct this in your function:
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
You can use
public function getPublishedAtAttribute($date){
return Carbon::parse($date)->format('Y-m-d');
}
public function setPublishedAtAttribute($date){
$this->attributes['published_at'] = Carbon::parse($date);
}
in place of
public function setPublishedAtAttribute($date){
//$this->attributes['published_at'] = Carbon::createFormFormat('Y-m-d', $date);
return $this->attributes['published_at']->format('Y-m-d');
}
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/