laravel validator not show errors - php

I am new to Laravel and other PHP frameworks.
Try simple form and validating, like examples in https://laravel.com/docs/5.1/validation
routes.php
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
create.blade.php
<html>
<head>
<title>Post form</title>
</head>
<body>
<h1>Create Post</h1>
<form action="/post/store" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" name='title'>
</div>
<button type="submit" class="btn btn-default">Save</button>
</form>
</body>
PostController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use View;
use Validator;
class PostController extends Controller
{
/**
* Show the form to create a new blog post.
*
* #return Response
*/
public function create()
{
return view('post.create');
}
/**
* Store a new blog post.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
$validator = Validator::make($request->all(), [
'title' => 'required|min:5'
]);
if ($validator->fails()) {
dd($validator->errors);
//return redirect('post')
//->withErrors($validator)
//->withInput();
}
}
}
When I post not valid data:
ErrorException in PostController.php line 37: Undefined property: Illuminate\Validation\Validator::$errors
Validator object nor have errors.
If enabled in controller
return redirect('post')->withErrors($validator)
->withInput();
and enabled in form
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Have error
ErrorException in c5df03aa6445eda15ddf9d4b3d08e7882dfe13e1.php line 1: Undefined variable: errors (View: /www/alexey-laravel-1/resources/views/post/create.blade.php)
This error in default get request to form and after redirect from validator.

For $errors to be available in the view, the related routes must be within the web middleware:
Route::group(['middleware' => ['web']], function () {
Route::get('/post/', 'PostController#create');
Route::post('/post/store', 'PostController#store');
});

Related

login autorization error getting Undefined variable: erros

I'm start learning laravel and want to create sample login authorization system on my html template. I watched a tutorial and when i do everything that was in video i get error Undefined variable: erros.
I'm new and I don't know good PHP but i want to learn while creating a website I know a little.
my rout code is my route code :
this is route for my login code
Route::get ('/main', 'MainController#index');
Route::get ('/main/checklogin', 'MainController#checklogin');
Route::get ('/main/successlogin', 'MainController#successlogin');
Route::get ('/main/logout', 'MainController#logout');
1.my login code
<div class="login slide-up">
<div class="center">
<h2 class="form-title" id="login"><span>sign</span>in</h2>
#if (isset(Auth::user()->email))
<script>window.location="/main/successlogin"</script>
#endif
#if ($message = Session::get('error'))
<div class ="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{$message}}</strong>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
#if(count($errors) >0 )
<div class="alert alert-danger">
<ul>
#foreach($erros->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
{{ csrf_field()}}
<div class="form-holder">
<input type="email" class="input" placeholder="email" />
<input type="password" class="input" placeholder="password" />
</div>
<button class="submit-btn">Sign in</button>
</div>
2.my successlogin code
<html>
<body>
#if (issets(auth::user()->email))
<p>gamarjoba {{Auth::user()->email}}}</p>
<a href="{{ url('/main/logout') }}" > logout </a>
else
<script>windows.location = "/main"; </script>
#endif
</body>
</html>
my main controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class MainController extends Controller
{
function index()
{
return view('front/login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:4'
]);
$user_data = array(
'email' => $request -> get('email'),
'password' => $request -> get('password')
);
if (Auth::attempt($user_data))
{
return redirect('main/successlogin');
}
else
{
return back()->with('error', 'wrong Login Details');
}
}
function successlogin()
{
return view('successlogin');
}
function logout()
{
Auth::logout();
return redirect('main');
}
}
Laravel made this easy:
Run php artisan make:auth

How to store input in session Laravel

I'm new in Laravel Here I am trying to post my input form in to a session but its not working I get this error without any message:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
I found nothing, here I am sharing some of my code.
My Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use \App\Product;
class ShopController extends Controller
{
public function index()
{
$categories = Category::with('products')->get();
return view('shop.index', compact('categories'));
}
public function category($id)
{
$products = Category::find($id)->products;
return view('shop.1', compact('products'));
}
public function addToShoppingCart(Request $request)
{
$request->session()->put('cart', 'id');
$request->session()->put('cart', 'number');
$request->session()->flash('status', 'Product is toegevoegd!');
return redirect()->back();
}
}
My view:
#extends('layouts.app')
#section('content')
#if(Session::has('id', 'number'))
<div class="alert alert-success">
{{Session::get('id', 'number')}}
</div>
#endif
#foreach ($products as $product)
<ul>
<li>{{ $product->name }}</li>
<li>{{ $product->description }}</li>
<li>{{ $product->price }}</li>
<li>{{ $product->amount }}</li>
</ul>
<form method="post" action="{{url('categories\{id}')}}">
#csrf
<div class="col-md-4">
<label for="number">Aantal:</label>
<input type="number" name="number">
<label for="id">Id:</label>
<input type="text" id="id" name="id" value= {{$product->id}}>
<button type="submit" class="btn btn-success">Add product</button>
</div>
</form>
#endforeach
{{var_dump(Session::get('cart'))}}
#endsection
My routes:
Route::get('/shop', 'Shopcontroller#index')->name('shop');
Route::get('/categories/{id}', 'ShopController#category');
Route::get('/cart/{id}', 'ShopController#addToShoppingCart');
I hope someone can help me out with my problem to put the input in the session of laravel.
You are trying to "post" using a "get" route. You should change Route::get by Route::post
First of all, i suggest you use the route() method. There is nothing wrong with the url() method but i just using the route() method.
So let's solve your problem out!
1. Add names to your routes and set the ROUTE to POST instead of GET
Route::get('/shop', 'Shopcontroller#index')->name('shop');
Route::post('/categories/{id}', 'ShopController#category')->name('category');
Route::get('/cart/{id}', 'ShopController#addToShoppingCart')->name('cart.add');
2. Pass your route as an action to your form
action="{{route('category',['id' => 'your_category_id_here'])}}
3. Add use Session;
Your controller is missing the use Session; statement, add it on the top of the controller page so you can be able to use sessions.

unique validation is in not working in laravel 5.4

I am making a todo list with validation using laravel 5.4.
When I click on the submit button, only the required validation is working but not the unique.
What am I doing wrong and how do I fix it so as to get it working as desired?
Below is my form (located at home.blade.php):
<div class="panel-body">
<form class="form form-control" action="/todo" method="post">
{{csrf_field()}}
<fieldset class="form-group">
<textarea class="form-control" name="textbox" id="textArea"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</form>
{{-- for dispaying the error --}}
#if (count($errors) >0)
{{-- expr --}}
#foreach ($errors->all() as $error)
<h3 class="text-danger">{{$error}}</h3>
#endforeach
#endif
</div>
Here, the content of my Todo controller (in my todocontroller.php file):
use Illuminate\Http\Request;
use App\todo;
public function store(Request $request)
{
$todo = new todo;
$todo->body = $request->textbox;
$this->validate($request,[
"body" => "required|unique:todos"
]);
$todo->save();
return redirect('/todo');
}
You should simply use the name of the field; you don't need to stress yourself.
Take a look at the snippet below:
<?php
namespace App\Http\Controllers;
use App\Todo;// following Laravel's standards, your model name should be Todo; not todo
use Illuminate\Http\Request;
class NameOfYourTodoController extends Controller
{
public function store(Request $request)
{
$todo = new Todo();
// use the name of the field directly (here, textbox)
$this->validate($request, [
'textbox' => 'required|unique:todos'
]);
// other code logics here.
}
}

Laravel 5: Data does not saved through blade form

I want to save a form input through Laravel 5.0
The page reloaded and back to the index page..But data does not save to mysql through routes.
Here is controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Pagination\LengthAwarePaginator;
use App\Http\Requests\CreateTaskRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Task;
use Input;
class TodoController extends Controller {
public function index()
{
$data=Task::all();
// $options=Option::whereNotIn('id',$activeCourse)->lists('option_name','id');
return view('home')->with('data',$data);
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//return view('home');
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(CreateTaskRequest $request)
{
// dd($request->all());
/*$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status'),
'description'=>Input::get('description'),
'task_img'=>Input::get('task_img'),
'dob'=>Input::get('dob')
];*/
$response=new Task();
$response->name=$request->input('name');
$response->status=$request->input('status');
$response->description=$request->input('description');
$response->description=$request->input('task_img');
$response->description=$request->input('dob');
$response->save();
// dd('working?');
//$response=Task::create(['name'=>$request->input('name'),'status'=>$request->input('status'),'description'=>$request->input('description')]);
if($response){
return redirect()->back()->with('success','Task Created Successfully');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$data=Task::find($id);
return view('todo_edit')->with('data',$data);
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update(CreateTaskRequest $request, $id)
{
$data=[
'name'=>Input::get('name'),
'status'=>Input::get('status')
];
$response=Task::find($id)->update($data);
if($response){
return redirect('/');
}
}
public function destroy($id)
{
$response=Task::find($id)->delete();
if($response){
return redirect('/')->with('success','Task Deleted Successfully');;
}
}
}
Here is my View Page:
#extends('app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12 ">
<div class="col-lg-12">
<div class="col-lg-6">
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
{!! Form::hidden('_token',csrf_token()) !!}
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Enter a task name"></br>
</br>
<lavel> <input name="status" type="radio" value="Complete"> Complete</lavel></br>
<label> <input checked="checked" name="status" type="radio" value="Incomplete"> Incomplete</label></br>
<textarea class="form-control" name="description" rows="3"></textarea></br>
<label>File input</label>
<input type="file" name="task_img"></br>
<input type="date" class="form-control datepicker" name="dob" style="width:95%">
{!! Form::submit('Save', array('class' => 'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
</div>
</div>
<h3> Todo Application </h3>
<table class="table table-striped table-bordered" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Task Name</td>
<td>Status</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($data as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->name }}</td>
<td>{{$row->status}}</td>
<td>
Edit
<form action="{{route('postDeleteRoute',$row->id)}}" method="POST" style="display:inline;"
onsubmit="if(confirm('Are you sure?')) {return true} else {return false};">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-danger" value="Delete">
</form>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#section('page-script')
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#example').DataTable();
} );
</script>
#stop
#endsection
And here is the routes :
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/',
'TodoController#index');
Route::post('/', 'TodoController#store');
Route::get('/{id}/edit',['as'=>'getEditRoute','uses'=>'TodoController#edit']);
Route::post('/{id}/edit',['as'=>'postUpdateRoute','uses'=>'TodoController#update']);
Route::post('/{id}/delete',['as'=>'postDeleteRoute','uses'=>'TodoController#destroy']);
//Route::get('home', 'HomeController#index');
Route::controllers([
'auth' => 'Auth\AuthController',
'password' => 'Auth\PasswordController',
]);
To save data from a form you can do as below :
In you form replace
{!! Form::open(array('route' =>'' ,'method'=>'post')) !!}
with
{!! Form::open(array('route' =>'form.store' ,'method'=>'post')) !!}
In you route replace
Route::post('/', 'TodoController#store');
with
Route::post('/store',array('as'=>'form.store',uses=>'TodoController#store');
And in your controller replace
public function create()
{
//return view('home');
}
with
public function store(Request $request) //Http request object
{
Task::create($this->request->all());//assumes that you want to create task.
return \Redirect::route('/')->with('message', 'Task saved sucessfully!!!');
}
If you want to explore more then please read the documentation from the below links :
Laravel Routes
Laravel Request
Laravel Controllers
Hope it helps. Happy Coding :) .

Laravel : BadMethodCallException Method [store] does not exist

I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.

Categories