Validation not working in laravel 5.5 - laravel

I installed a new Laravel 5.5 app and created a form in test.blade.php view:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="POST" action={{ route('contact') }}>
{{ csrf_field() }}
<input type="text" name="title">
<input type="text" name="body">
<input type="submit" value="click">
</form>
</body>
</html>
and created my PageController :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Pagecontroller extends Controller
{
public function index(Request $request){
$this->validate($request,[
'title' => 'required',
'body' => 'required',
]);
return View('View');
}
}
and in the web.php add my routes:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/test',function(){
return View('test');
});
Route::post('/contact',['uses'=>'PageController#index','as'=>'contact']);
My problem is when I submit the form with or without data nothing happen and the page just reload and when I remove the validation code:
$this->validate($request,[
'title' => 'required',
'body' => 'required',
]);
it return the requests I can't understand what is the problem because I tested it before and it was working in Laravel 5.4. Can any one help me?

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class Pagecontroller extends Controller
{
public function index(Request $request){
$request->validate([
'title' => 'required',
'body' => 'required',
]);
return View('View');
}
}
And your view code should be:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="POST" action={{ route('contact') }}>
{{ csrf_field() }}
<input type="text" name="title">
<input type="text" name="body">
<input type="submit" value="click">
</form>
</body>
</html>

Related

Laravel: Login system problem for learning

I'm trying to make a login for learning, so I followed a video from youtube with the same coding. It should be able to check the format of the inputted data, check whether user already login or not, check whether user accessing the next page wihthout login, but in the end, it will always only showed email and password required errors even if I already inputted the right input. Please help. Here are my codes.
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/main', 'MainController#index');
Route::post('/main/checklogin', 'MainController#checklogin');
Route::get('main/successlogin', 'MainController#successlogin');
Route::get('main/logout', 'MainController#logout');
login.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Login</title>
<!--CSS-->
<link rel="stylesheet" href="{{ asset('css/styles.css') }}" type="text/css">
<link rel="stylesheet" href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' />
<script type="text/javascript" src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>
</head>
<body>
<div class="login-page-frame">
<div class="header-login-page-frame">
<h3>Login</h3>
</div>
<div class="inner-login-form-frame">
#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"></button>
<strong>{{$message}}</strong>
</div>
#endif
#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="{{ url('/main/checklogin') }}" class="login-form">
{{ csrf_field() }}
<input type="email" placeholder="email" name="login-email" class="form-control">
<br>
<input type="password" placeholder="pass" name="login-password" class="form-control">
<br>
<input type="submit" name="login" class="btn-login" value="login">
</form>
</div>
</div>
</body>
</html>
halamanUtama.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Halaman Utama</title>
</head>
<body>
<div class="container box">
<h3 align="center">Selamat Datang</h3>
<br />
#if(isset(Auth::user()->email))
<div class="alert alert-danger success-block">
<strong>Welcome {{ Auth::user()->email }}</strong>
<br />
Logout
</div>
else
<script>window.location="/main";</script>
#endif
</div>
</body>
</html>
MainController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
use Input;
class MainController extends Controller
{
//
function index(){
return view('login');
}
function checklogin(Request $request){
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:3'
]);
$user_data=array(
'email' => $request->get('login-email'),
'password' => $request->get('login-password')
);
if(Auth::attempt($user_data)){
return redirect('main/successlogin');
}else{
return back()->with('error', 'Wrong Login Details');
}
}
function successlogin(){
return view('halamanUtama');
}
function logout(){
Auth::logout();
return redirect('main');
}
}
I won't comment on whether any of your other code works, but the cause of your validation errors is that the name of your form inputs does not match the name of the fields you are trying to validate.
In your form, your inputs are called login-email and login-password. However, in your controller, you are validating that a field called email and a field called password are provided (because they are required).
So either change your form names to email and password or change your validation fields to login-email and login-password.

Laravel 5.8 image upload

After creating a Laravel site with user login, I wanted to add file upload ability. I followed a simple tutorial but when it came to do php artisan migrate it didn’t work because Base table or view already exists so I created an images table manually in MySQL.
Finally, I navigated to my websites image upload page http://localhost/sites/mywebsite/public/image and attached an image. The error I got was The POST method is not supported for this route. Supported methods: GET, HEAD.
This is the line in my image.blade.php file:
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
Note; When I created an images table manually in MySQL I only added 'id' and 'image' columns and I wasn't 100% sure how to format them.
Any help very much appreciated.
Here's my ImageController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator, Redirect, Response, File;
use App\Image;
class ImageController extends Controller
{
public function index()
{
return view('image');
}
public function save(Request $request)
{
request()->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($image = $request->file('image')) {
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert[]['image'] = "$profileImage";
}
}
$check = Image::insert($insert);
return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}
}
Image.blade.php
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<style>
.container {
padding: 10%;
text-align: center;
}
</style>
</head>
<body>
<div class="container">
<h2 style="margin-left: -48px;">Laravel 5.7 Multiple Image Upload Example - Tutsmake.com</h2>
<br>
<br>
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
<br>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Opps!</strong> There were something went wrong with your input.
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
<br>
#endif
<form action="{{ url('save') }}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
#csrf
<div class="avatar-upload col-6">
<div class=" form-group avatar-edit">
<input type='file' id="image" name="image[]" accept=".png, .jpg, .jpeg" />
<label for="imageUpload"></label>
</div>
</div>
<div class="form-group col-3">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
</body>
</html>
Migration table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateImagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->increments('image');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('images');
}
}
Follow Any Method :
<form action="{{ url('save') }}" method="get" accept-charset="utf-8" enctype="multipart/form-data">
And Change Migartion $table->text('image');
OR
Route::post('save', 'ImageController#save');
And Change Migartion $table->text('image');
You need to create a POST method route in routes/web.php.
A get route does not support posting form data
Route::post('save', 'ImageController#save');
Also, the image column in your database should be a string, an integer can't hold a path to a file
$table->string('image');
But you can't insert an array to a string column anyway so you should move the Model create method inside the foreach loop
foreach ($image as $files) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
Image::insert($profileImage);
}

Error while submitting form Laravel 5.6

I have code in router:
/**************Quản lý user*****************/
Route::get('admin/manage-user', 'UserController#getList')->middleware('admin');
Route::get('admin/manage-user/add', 'UserController#indexAdd')->middleware('admin');
Route::post('admin/manage-user/add', 'UserController#getAdd')->middleware('admin');
Code in UserController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests\AddUserRequest;
class UserController extends Controller
{
//
public function getList()
{
$data = User::paginate(10);
return view('admin.manage-user',['data' => $data]);
}
public function indexAdd()
{
return view('admin.add-user');
}
public function getAdd(AddUserRequest $request)
{
if($request->fails())
return view('admin.add-user')->withInput();
}
}
Code in AddUserRequest
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class AddUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'username' => 'required|max:200',
'email' => 'required|email|unique:users',
'pass1' => 'required|min:6',
'pass2' => 'required|same:pass1',
];
}
}
Code view errors:
#extends('layouts.admin')
#section('title','Add User')
#section('content')
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Add User</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
When running the path: http://localhost/LBlog/public/admin/manage-user/add and submit (Do not enter form information), the screen returns error: The page has expired due to inactivity. Please refresh and try again.
I hope someone can help me with this issue
That error appears due to CSRF token.
Add csrf token in your form.
<form role="form" action="{{url('admin/manage-user/add')}}" method="post">
#csrf
<div class="box-body">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>

How to create a laravel 5.5 custom auth?

I created a custom Auth controller in Laravel 5.5 with the action "store" inside it, then I authenticated it using the $auth->attempt() method that returns true. So far so good, the problem starts when I try to use the "auth" middleware for my panel routes, the authentication middleware always redirects to the login action.
Routes:
Route::group(['middleware' => ['auth', 'web']], function () {
Route::get('/painel/', ['as' => 'painel.dashboard', 'uses' => 'DashboardController#index']);
});
Route::get('/login', ['middleware' => 'web', 'as' => 'login', 'uses' => 'AuthController#index']);
Route::group(['middleware' => ['web']], function () {
Route::get('/painel/auth', ['as' => 'painel.auth.index', 'uses' => 'AuthController#index']);
Route::post('/painel/auth/store', ['as' => 'painel.auth.store', 'uses' => 'AuthController#store']);
});
Controller:
namespace App\Applications\Painel\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Auth\AuthManager as Auth;
class AuthController extends BaseController
{
/**
* #var Guard
*/
private $auth;
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
public function index()
{
return view('painel::auth.index');
}
public function store(Request $request)
{
$data = $request->only(['email', 'password']);
// This condition always return true, but after Laravel return to action index...
if ($this->auth->attempt($data)) {
return redirect()->route('painel.dashboard');
}
return redirect()->back();
}
}
auth.index:
<!doctype html>
<html lang="pt_BR">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Admin</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="row">
<div class="col-sm-12 col-md-12">
<h2 class="text-center">Admin</h2>
<hr>
</div>
</div>
<div class="row">
<div class="col-sm-4 col-md-2 col-md-offset-5 col-sm-offset-4">
<form action="{{ route('painel.auth.store') }}" method="post" id="login-form">
{!! csrf_field() !!}
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="password">Senha</label>
<input type="password" class="form-control" name="password" id="password" placeholder="Senha">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-lg btn-block" name="submit" id="submit">Entrar</button>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
The attempt method needs the $request as parameter or you'll need to include the remember token in $data. The guard is missing the remember token, I think.

MethodNotAllowed Exception on form submit

routes.php
use App\Http\Controllers\Task;
use Illuminate\Http\Request;
Route::get('/', function () {
$tasks = Task::orderBy('created_at', 'asc')->get();
return view('tasks', [
'tasks' => $tasks
]);
});
Route::get('Login', 'Login#index');
View: loginform.blade.php
<form method="post" action="http://localhost/blog/public/Login">
<!-- Task Name -->
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
{!! Form::label('usernamelabel','Username', ['class'=>'col-sm-3 control-label']) !!}
{!! Form::text('username', '', ['class'=>'form-control','id'=>'username']) !!}
</div>
<div class="col-sm-6">
{!! Form::label('passwordlabel', 'Password', ['class'=>'form-control control-label']) !!}
{!! Form::text('password', '', ['class'=>'form-control','id'=>'password']) !!}
</div>
</div>
<!-- Add Task Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Login
</button>
</div>
</div>
{!! Form::close() !!}
Controller: Login.php
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Models\userloginModel;
use Illuminate\Http\Request;
class Login extends Controller{
protected $request;
public function index(Request $request)
{
echo view('login.loginform');
$foo = new userloginModel();
echo $foo->username = $request->username;
echo $foo->password = $request->password;
}
}
I have try all solutions from Stackoverflow and laracast but i failed to solve this please some one help me from this i am new with laravel..
Your error is in method, u trying to make a post request and your route are receiving a get request, try this:
Route
<?php
//...
Route::get('Login', 'Login#index');
Route::post('Login', 'Login#login');
?>
Controller
<?php
//...
public function index()
{
return view('login.loginform');
}
public function login(Request $request)
{
$foo = new userloginModel();
echo $foo->username = $request->username;
echo $foo->password = $request->password;
}
?>

Resources