I'm new in Laravel4 world, and I'm trying to convert my site to laravel framework. But at beginning I have a little problem. On index I have two jquery modal: first for singin and second for registration. So, I want to when user try to login and make a mistake to show him an error. Same for registration. But when I have error in singin form, I get register form...My english is bad, so here is code:
routes.php
Route::get('/', function()
{
return View::make("index.index");
}
Route::post('/', array('as'=> 'singin', function()
{
$data = Input::all();
$rules = array(
'username' => 'min:3',
'password' => 'min:6'
);
$validation = Validator::make($data, $rules);
if($validation->passes())
{
return View::make('users.main');
}
Input::flash();
return Redirect::to('/')->withErrors($validation);
}));
Route::post('/', array('as'=> 'register', function()
{
// same as previous function
]
index.blade.php
<div id="signin" class="reveal-modal" #if($errors->all())
style="display:block; visibility:visible;" #endif >
<header class="reveal-modal-header">
Sign in
</header>
<div class="cont">
<div class="indication">
Sign In
</div>
{{ Form::open(array(
'route' => 'singin',
'class' => 'signin')) }}
<p class="clearfix">
{{ Form::label('username', 'Username') }}
{{ Form::text('username')}}
</p>
<p class="clearfix">
{{ Form::label('password', 'Password') }}
{{ Form::password('password')}}
</p>
<p class="without-label clearfix">
{{ Form::submit('') }}
</p>
#if($errors->all())
<div id="logindiverror" style="" class="alert alert-error">
#foreach($errors->all('<li>:message</li>') as $message)
{{ $message }}
#endforeach
</div>
#endif
{{ Form::close() }}
</div>
<a class="close-reveal-modal" id="close1" href="#">×</a>
</div>
<div id="signup" class="reveal-modal" #if($errors->all())
style="display:block; visibility:visible;" #endif >>
<header class="reveal-modal-header">
Sign up
</header>
<div class="cont">
<div class="indication">
Register
</div>
{{ Form::open(array(
'route' => 'register',
'class' => 'signup')) }}
<p class="clearfix">
<em>(<abbr>*</abbr>) All fields are required</em>
</p>
<p class="clearfix">
<label>Username:<abbr>*</abbr></label>
{{ Form::text('username')}}
</p>
<p class="clearfix">
<label>Email:<abbr>*</abbr></label>
{{ Form::text('email') }}
</p>
<p class="clearfix">
<label>Password:<abbr>*</abbr></label>
{{ Form::password('password1'); }}
</p>
<p class="clearfix">
<label>Password (repeat):<abbr>*</abbr></label>
{{ Form::password('password2'); }}
</p>
<p class="checkboxes clearfix">
<span class="niceCheck">{{ Form::checkbox('agree', '0') }}</span>
I agree with LinkyPlanet Terms & Privacy Policy
</p>
<p class="without-label clearfix">
{{ Form::submit('') }}
</p>
#if($errors->all())
<div id="logindiverror" style="" class="alert alert-error">
#foreach($errors->all('<li>:message</li>') as $message)
{{ $message }}
#endforeach
</div>
#endif
{{ Form::close() }}
</div>
<a class="close-reveal-modal" id="close2" href="#">×</a>
</div>
So, problem is when user try to sing in, and he make a mistake in password (pass is shorter than 6 chars), script redirect him to index and open modal for registration and there show an error, not in sing in modal. Where is mistake?
Cheers :)
The problem is that you have 2 "different" routes using the same URI (/) and the same method (POST), but you cannot.
Only the first one will work, by precedence. Something like this could be better:
Route::post('/singin', array('as'=> 'singin', function()
{
}));
Route::post('/register', array('as'=> 'register', function()
{
}));
Or you can keep one of them on / and change the other one:
Route::post('/', array('as'=> 'singin', function()
{
}));
Route::post('/register', array('as'=> 'register', function()
{
}));
EDIT:
You are using the same name for everything ($errors in register and sign in). If you have ONE view for both, you need to have different names. You can use
return Redirect::to('/')->with('registerErrors', $validation->messages());
and
return Redirect::to('/')->with('signInErrors', $validation->messages());
But on tedirects they are bound to your session, so you'll have to get them this way:
#if(Session::has('registerErrors'))
<div id="logindiverror" style="" class="alert alert-error">
#foreach(Session::get('registerErrors')->all('<li>:message</li>') as $message)
{{ $message }}
#endforeach
</div>
#endif
Related
Yesterday I started with Laravel, currently busy with my first project, a simple news page.
Unfortunately, I've met some problems while validating my post request, I've tried to search on Google for my issue. And I tried to use those fixes, but strange enough I had no result.
The problem is:
When I post data the normal 'form page' will be shown without any errors. I'm aware that I have double error outputs, it's just for the test.
What do I want to reach?
I want that the validation error will be shown
routes.php
<?php
Route::group(['middleware' => ['web']], function() {
Route::get('/', function() {
return redirect()->route('home');
});
Route::get('/home', [
'as' => 'home',
'uses' => 'HomeController#home',
]);
Route::get('/add_article', [
'as' => 'add_article',
'uses' => 'HomeController#add_article',
]);
Route::post('/add_article', [
'as' => 'add_article.newarticle',
'uses' => 'HomeController#post_article',
]);
});
HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\News;
class HomeController extends Controller
{
public function home(News $news)
{
$articles = $news->orderBy('id','desc')->take(3)->get();
return view('home.home')->with('articles', $articles);
}
public function add_article()
{
return view('home.add_article');
}
public function post_article(Request $request)
{
$this->validate($request, [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
}
}
add_article.blade.php
#extends('templates.default')
#section('content')
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 offset-md-3 offset-lg-3 offset-xl-3">
<p class="lead">New news article</p>
<div class="card">
<div class="card-header">
<h5 class="mb-0"> </h5>
</div>
<div class="card-body">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('add_article.newarticle') }}">
<div class="form-group">
<label for="title" style="margin-bottom:0px;">
Title:
</label>
<input class="form-control" type="text" name="title" placeholder="Please enter your title!" id="title">
#if ($errors->has('title'))
{{ $errors->first('title') }}
#endif
</div>
<div class="form-group">
<label for="content" style="margin-bottom:0px;">
Content:
</label>
<textarea class="form-control" rows="3" name="content" placeholder="Please enter your message!" id="content" style="resize:none;"></textarea>
#if ($errors->has('content'))
{{ $errors->first('content') }}
#endif
</div>
<div class="form-group text-right">
<button class="btn btn-primary" type="submit">
Create news
</button>
</div>
{{ csrf_field() }}
</form>
</div>
</div>
</div>
</div>
#endsection
I hope someone can help me to resolve this issue!
use App\Http\Requests;
Remove This from HomeController.php and try.
Your validation is passing but you are not doing anything after so it's not going to show anything unless you tell it to.
Also make sure you use $request->all() instead of $request in the validator as the first one will return the actual input values that were submitted.
use Validator;
public function post_article(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|max:64',
'content' => 'required|max:2048',
]);
if ($validator->fails()) {
return redirect('home')
->withErrors($validator)
->withInput();
}
// $newNews = new News;
// $newNews->title = $request->title;
// $newNews->content = $request->content;
// $newNews->save();
return redirect()->route('home')->with('message', 'Article created.');
}
}
Then in your view add the following at the top:
#if(Session::has('message'))
<div class="alert alert-success">
×
{{ Session::get('message') }}
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Based on those validation rules you will only see errors when the title is empty or longer than 64 characters, or the content is empty or longer than 2048 characters. Make sure the data you are testing with is long enough to trigger any errors.
For data that passes validation the code currently does not save (commented out), nor does it return a new location or view so it will show a blank page. You should probably save the data and redirect to the index or a show page with a success message.
newbie here practicing laravel, im making an inventory for movies using laravel 5.6.. where I can do basic CRUD functionalities.
In here, Im sorting movies by genre. however I came up with this error Invalid argument supplied for foreach();
here is my Route: web.php
Route::resource('movies', 'MoviesController');
Route::get('movies/year/{movie}', 'MoviesController#released');
Route::get('movies/genre/{genre}', 'MoviesController#getgenre');
here is my controller: MoviesController.php
public function getgenre($genre){
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();
return view('genre', compact('movies'));
}
here is my view: genre.blade.php
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-md-10">
#if($movies->count() < 1)
<h1 style="text-align: center">No Movie Found</h1>
#else
#foreach($movies as $movie)
<div class="card" style="margin-bottom: 10px;">
<div class="card-body">
<div class="card-title">
{{ ucwords($movie->title) }}
</div>
<div class="card-text">
{{ ucfirst($movie->genre) }} | {{$movie->released}} |
#if($movie->seen == 1)
Seen: Yes
#else
Seen: No
#endif
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.edit', $movie->id], 'class' => 'formupdate', 'method' => 'GET']) }}
{{ Form::submit('Update', ['class' => 'btn btn-primary col-md-2']) }}
{{ Form::close() }}
</div>
<div style="margin-top: 5px">
{{ Form::open(['route' => ['movies.destroy', $movie->id], 'class' => 'formdelete', 'method' => 'DELETE']) }}
{{ Form::hidden('hidden', 'hidden') }}
{{ Form::submit('Delete', ['class' => 'btn btn-danger col-md-2']) }}
{{ Form::close() }}
</div>
</div>
</div>
</div>
#endforeach
<div class="pagination" style="margin-top: 10px; text-align: center;">
{{ $movie->links() }}
</div>
#endif
</div>
<div class="col-md-2">
</div>
</div>
#stop
I tested it dd(): and it has results:
tried testing it using dd()
here is the error:
here is the error
thanks,
you have two issues:
1- Update this whereIn expects array and you use pagination in view and you do not return the data as pagination
$movies = Movie::where('genre', $genre)->whereIn('status', [1])>orderBy('title', 'asc')->paginate(10);
2- in the view you written $movie->links(); update it to
$movies->links();
Update this line, whereIn expects array
$movies = Movie::where('genre', $genre)->whereIn('status', [1])->orderBy('title', 'asc')->get();
I'm making a discussion forum app with laravel and i face this error:
Trying to get property of non-object (View:
C:\xampp\htdocs\fourm\resources\views\discussion\show.blade.php) at
PhpEngine->evaluatePath('C:\xampp\htdocs\fourm\storage\framework\views/a2f2c494b8859e0552bfa22c40ceb4065b2efbe5.php',
array('__env' => object(Factory), 'app' => object(Application),
'channels' => object(Collection), 'errors' => object(ViewErrorBag),
'd' => null, 'best_answer' => null))in CompilerEngine.php (line 59)
This is my controller code:
public function show($slug)
{
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
This is my view code:
#extends('layouts.app')
#section('content')
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $d->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $d->user->name }}, <b>( {{ $d->user->points }} )</b></span>
#if($d->is_being_watch_by_user())
unwatch
#else
watch
#endif
</div>
<div class="panel-body">
<h4 class="text-center">
<b>{{ $d->title }}</b>
</h4>
<hr>
<p class="text-center">
{{ $d->content }}
</p>
<hr>
#if($best_answer)
<div class="text-center" style="padding: 40px;">
<h3 class="text-center">BEST ANSWER</h3>
<div class="panel panel-success">
<div class="panel-heading">
<img src="{{ $best_answer->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $best_answer->user->name }} <b>( {{ $best_answer->user->points }} )</b></span>
</div>
<div class="panel-body">
{{ $best_answer->content }}
</div>
</div>
</div>
#endif
</div>
<div class="panel-footer">
<span>
{{ $d->replies->count() }} Replies
</span>
{{ $d->channel->title }}
</div>
</div>
#foreach($d->replies as $r)
<div class="panel panel-default">
<div class="panel-heading">
<img src="{{ $r->user->avatar }}" alt="" width="40px" height="40px">
<span>{{ $r->user->name }} <b>( {{ $r->user->points }} )</b></span>
#if(!$best_answer)
#if(Auth::id() == $d->user->id)
Mark as best answer
#endif
#endif
</div>
<div class="panel-body">
<p class="text-center">
{{ $r->content }}
</p>
</div>
<div class="panel-footer">
#if($r->is_liked_by_user())
Unlike <span class="badge">{{ $r->likes->count() }}</span>
#else
Like <span class="badge">{{ $r->likes->count() }}</span>
#endif
</div>
</div>
#endforeach
<div class="panel panel-default">
<div class="panel-body">
#if(Auth::check())
<form action="{{ route('discussion.reply', ['id' => $d->id ]) }}" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="reply">Leave a reply...</label>
<textarea name="reply" id="reply" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<button class="btn pull-right">Leave a reply</button>
</div>
</form>
#else
<div class="text-center">
<h2>Sign in to leave a reply</h2>
</div>
#endif
</div>
</div>
#endsection
You're getting this error because both queries return null:
$discussion = Discussion::where('slug', $slug)->first();
$best_answer = Reply::where('best_answer', 1)->first();
So, you need to check for empty result manually with is_null() or empty() or just:
if (!$discussion) {
abort(404);
}
Or use findOrFail() to throw an exception if no record found.
You are trying to access property with null objects, and that's why you got the error like "Trying to get property of null object".
As per our discussion in comments, you are getting null values in both queries and that's the reason for error!
Try to add if..else condition like below:
if (!$d) {
session()->flash('error', 'Discussion not found.');
return redirect()->back();
} else {
return view('discussion.show')->with('d', $discussion)->with('best_answer', $best_answer);
}
Hope this helps you!
Make sure you're not returning an object and accessing it as an array. It can be a common error.
I solved mine by adding: <?php error_reporting(0);?> on page where i got error. :D
I have created a form in Laravel so here are the following files:
The form that someone should submit some details,
contact.blade.php:
#extends('layouts.layout')
#section('content')
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Laravel demo</h1>
<p class="lead text-muted">Please fill the form</p>
#if(count($errors) > 0)
#foreach($errors->all() as $error)
<div class="alert alert-danger">
{{$error}}
</div>
#endforeach
#endif
</div>
</section>
<div class="album text-muted">
<div class="container">
{!! Form::open(['url' => 'contact/submit']) !!}
{!! csrf_field() !!}
<div class="form-group">
{{Form::label('name', 'Name') }}
{{Form::text('name', 'Enter Name', ['class'=> 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('email', 'E-Mail Address') }}
{{Form::text('email', 'example#gmail.com', ['class'=> 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('message', 'Enter Message') }}
{{Form::textarea('message', 'Enter Message', ['class'=> 'form-control'])}}
</div>
<div>
{{Form::submit('Submit', ['class'=> 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</main>
#endsection
Controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MessageController extends Controller
{
public function submit(Request $request){
$this->validate($request, [
'name' => 'required',
'email' => 'required'
]);
return 'SUCCESS';
}
}
*
In the Routes web.php file i have included the method as post:
Route::get('/', function () {
return view('home');
});
Route::get('/contact', function () {
return view('contact');
});
Route::post('/contact/submit', 'MessageController#submit');
The error message is " RouteCollection.php (line 251)" .After searching for similar occassions here the problem ussually occurs when in the Routes you use a different method to the specified route method. I'm using POST method for submiting details, I still cannot understand why I get this.
Any help would be appreciated.
Instead of this {!! Form::open(['url' => 'contact/submit']) !!}
Try this.
{!! Form::open(['method'=>'POST','action'=>'MessageController#submit']) !!}
Add the back slash to the url of the form like so :
{!! Form::open(['url' => '/contact/submit']) !!}
For some reason I can't understand, when I'm using the Redirect::intended() method after login I'm always sent to the fournisseurs/ax_getListProduits URL of my routes file, whatever is my real intended URL, with 2 exceptions:
if I remove the post fournisseurs/ax_getListProduits route, everything is OK
if I add a echo Session::get('url.intended'); call before the login page display, the correct intended URL is displayed, and it works (but if I add this code after Auth::attempt, I'm sent to fournisseurs/ax_getListProduits).
I can't understand what's happening… I can't find any similar problem here or in the Laravel Github repository, which leads me to think I'm doing something wrong, but I can't find it… I posted this question as a possible bug on Github, but without success, here : https://github.com/laravel/framework/issues/2668.
Below are my routes file and my login controller code:
routes.php
Route::group(array('before' => 'auth'), function() {
Route::get('/', array("as"=>"home", function() {
return Redirect::to("fournisseurs");
}));
Route::resource('usergroups', 'UsergroupsController');
Route::get('fournisseurs/ax_produits', 'FournisseursController#ax_produits');
Route::post('fournisseurs/ax_getProduit', 'FournisseursController#ax_getProduit');
Route::post('fournisseurs/ax_updProduit', 'FournisseursController#ax_updProduit');
Route::post('fournisseurs/ax_getListProduits', 'FournisseursController#ax_getListProduits');
Route::resource('fournisseurs', 'FournisseursController');
Route::resource('adresses', 'AdressesController', array('only' => array('store', 'destroy', 'edit', 'update')));
Route::get('/adresses/create/{frs_id}', array('as'=>'adresses.create', 'uses'=>'AdressesController#create'));
Route::resource('contacts', 'ContactsController', array('only' => array('store', 'destroy', 'edit', 'update')));
Route::get('/contacts/create/{frs_id}', array('as'=>'contacts.create', 'uses'=>'ContactsController#create'));
});
Route::get('login', array('as' => 'login', 'uses' => 'SessionsController#create'));
Route::get('logout', array('as' => 'logout', 'uses' => 'SessionsController#destroy'));
Route::resource('sessions', 'SessionsController', array('only' => array('create', 'store', 'destroy')));
Login controller:
class SessionsController extends BaseController {
public function create() {
// if I uncomment the following line, everything is OK
// echo Session::get('url.intended');
return View::make('sessions.create');
}
public function store() {
$input = Input::all();
$attempt = Auth::attempt(array(
"nom" => $input["nom"],
"password" => $input["password"]
));
if($attempt) return Redirect::intended("/");
return Redirect::back()->with("flash_error", "Nom ou mot de passe invalide")->withInput();
}
public function destroy() {
Auth::logout();
return Redirect::home();
}
}
view create.blade
#extends("layouts.default")
#section("content")
<div class="login_form">
<div class="row"><div class="col-md-4 col-md-offset-4">
<h2>Identification</h2>
</div></div>
<div class="row">
<div class="col-md-4 col-md-offset-4">
{{ Form::open(array('route' => 'sessions.store', 'class' => 'form', 'role' => 'form')) }}
<div class="form-group">
{{ Form::label('nom', 'Nom') }}
{{ Form::text('nom', '', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('password', 'Mot de passe') }}
{{ Form::password('password', array('autocomplete'=>'off', 'class' => 'form-control')) }}
</div>
{{ Form::submit("Connexion", array("class"=>"btn btn-primary")) }}
{{ Form::close() }}
</div>
</div>
</div>
#stop
And default.blade layout
<!DOCTYPE html>
<html lang="fr">
<head>
(...) head removed for code clarity
</head>
<body>
<div class="container">
#if(Session::get("flash_msg"))
<div class="row fox-info"><div class="col-md-12">
<div class="alert alert-info">
{{ Session::get("flash_msg") }}
</div>
</div></div>
#endif
<nav class="navbar navbar-default" role="navigation">
<a class="navbar-brand" href="#">EK | FOX</a>
<ul class="nav navbar-nav">
#yield("trail")
</ul>
<ul class="nav navbar-nav navbar-right">
#if(Auth::user())
<li class="dropdown">
{{ Auth::user()->nom }} <b class="caret"></b>
<ul class="dropdown-menu">
<li>Déconnexion</li>
</ul>
</li>
#endif
</ul>
</nav>
#if(Session::get("flash_error"))
<div class="row"><div class="col-md-12">
<div class="alert alert-danger">
{{ Session::get("flash_error") }}
</div>
</div></div>
#endif
#yield("content")
</div>
(...) js scripts removed for code clarity
</body>
</html>
I found some time to look after this issue, and the problem came from an unfortunate ajax post call to the "unwanted route" (fournisseurs/ax_getListProduits). This ajax call was made after the page creation, and even if it returns a 404 error, Laravel was updating the url.intended Session variable between page creation and form submission.