I'm having a hard time on this error when I encounter this error, My solution is to create new project. I know this question is alway ask here. I followed all tutorial line by line and is always error.
Sign Up:
#extends('layouts.master')
#section('content')
<div class="col-md-6">
<form method="POST" action="{{ route('signup') }}">
<div class="form-group">
<input type="text" name="username" placeholder="Username" class="form-control"></input>
</div>
<div class="form-group">
<input type="password" name="password" placeholder="Password" class="form-control"></input>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary pull-right"></input>
<input type="hidden" name="_token" value="{{ Session::token() }}"></input>
</div>
</form>
</div>
#endsection
routes.php
<?php
Route::get('/', function () {
return view('welcome');
});
Route::post('/signup', [
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
UserController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class UserController extends Controller
{
public function postSignUp(Request $request){
$username = $request['username'];
$password = bcrypt($request['password']);
$user = new User();
$user->username = $username;
$user->password = $password;
$user->save();
return redirect()->back();
}
}
I don't see a get route for your form. Your post route will work only if you submit the form.
So, in your routes.php, there should something like
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('/signup', [
'uses' => 'UserController#getSignUp',
'as' => 'signup'
]);
Route::post('/signup', [
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
And, in UserController#getSignUp you just load the view of the form.
//your blade file is OK ,you can use same
//you route
Route::get('/signup', function () { //route1 to view form
return view('signUp');
});
Route::post('/signup', [ // route2 to handle form request
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
to view your form you have to use get method which is route1 ,after submitting the form your postSignUp method will redirect to get route which is route1.
//your controller
public function postSignUp(Request $request){
$username = $request->username; //to access username
$password = bcrypt($request->password); //to access password
$user = new User();
$user->name = $username;
$user->password = $password;
$user->save();
return redirect()->back();
}
in your blade file you use name filed as username and password for user's username and password respectively.so In user Usercontroller you can directly access them as $request->username and $request->password for User's username and password respectively.
Related
I want to use input from a form in one view and print results into another view. I get the following error: Undefined variable: users Thanks in advance!
The form (in a view called 'dashboard') that I am using to get email address:
...
<div class="search">
<header><h3>Search Friend</h3></header>
<form action="{{ route('search.friend') }}" method="post">
<div class="form-group">
<input class="form-control" type="text" name="email" id="email" placeholder="Friend's email">
</div>
<button type="submit" class="btn btn-primary">Post</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
</div>
...
The route to send data from 'dashboard' to Controller:
Route::post('/searchfriend',[
'uses' => 'FriendController#getSearchFriend',
'as' => 'search.friend',
'middleware' => 'auth'
]);
The controller where I use the email to find user:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
The route to send the result to a 'userlist' view:
Route::get('/userlist',[
'uses' => 'FriendController#getSearchFriend',
'as' => 'userlist',
'middleware' => 'auth'
]);
Finally, the 'userlist' view:
#extends('layouts.master')
#section('title')
Users
#endsection
#section('content')
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Users</h3></header>
<div class="userlist">
<header><h2>Click to Add Friend</h2></header>
#foreach($users as $user)
Name: {{ $user->username }}
#endforeach
</div>
</div>
</section>
#endsection
Change:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['$users' => $users]);
}
}
to:
class FriendController extends Controller
{
public function getSearchFriend(Request $request)
{
$this->validate($request,[
'email' => 'required | email'
]);
$email = $request['email'];
$users = User::where('email',$email)->get();
return view('userlist',['users' => $users]);
}
}
You don't need the $ when passing the name of the variable to the view.
#Ryan J Field is correct. Also, you can pass the variable in many different ways. Such as -
return view('userlist')->with('users', $users);
Or,
return view('userlist', compact(users));
I'm trying to insert my data to database from form.
My URL to create the data is web.com/siswa/create
But when I click submit system show error MethodNotAllowedHttpException.
How I can fix it? Is there anything wrong with my code?
Here is my form:
<form action="{{ url('siswa') }}" method="POST">
<div class="form-group">
<label for="exampleInputEmail1">NISN</label>
<input type="text" class="form-control" name="nisn" id="nisn" placeholder="NISN"></div>
<div class="form-group">
<label for="exampleInputEmail1">Nama Siswa</label>
<input type="text" class="form-control" name="nama_siswa" id="nama_siswa" placeholder="Nama Siswa"> </div>
<button type="submit" class="btn btn-success btn-sm font-weight-bold">Submit</button></form>
Controller:
public function tambah()
{
return view('siswa.create');
}
public function store(Request $request)
{
$siswa = new \App\Siswa;
$siswa->nisn = $request->nisn;
$siswa->nama_siswa = $request->nama_siswa;
$siswa->tanggal_lahir = $request->tanggal_lahir;
$siswa->jenis_kelamin = $request->jenis_kelamin;
$siswa->save();
return redirect('siswa');
}
Route:
Route::get('/siswa/create', [
'uses' => 'SiswaController#tambah',
'as' => 'tambah_siswa'
]);
Route::get('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
change your store function route from get to post
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
Use Csrf protection field in your form for the session timeout error
{{ csrf_field() }}
OR
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
OR if you are using Form builder
{!! Form::token() !!}
In Route please use post instead of get
Route::post('/siswa','SiswaController#store');
and also include {{ csrf_field() }} in form
you are using method="POST" on your form but in on your route you are using Route::get
Use Route::post for your route
In your form you've given POST method, but your router doesn't have any POST handler. So all you have to do is , when you are trying to store data from form to DB you have to post the data, and the router should handle it.
Try this
Route::post('/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
]);
You are using POST method in your form and using GET in route.
try this
Route::post( '/siswa', [
'uses' => 'SiswaController#store',
'as' => 'simpan_siswa'
] );
I would like to start by apologizing for the newbish question.
I'm in the process of making a simple CRUD controller on Laravel.
My create method is as follows:
public function create(Request $request)
{
$dummy = new Dummy();
$dummy->title = $request->title;
$dummy->content = $request->dummy_content;
$dummy->created_at = new \DateTime();
$dummy->updated_at = new \DateTime();
$dummy->save();
return redirect()
->route('index/view/', ['id' => $dummy->id])
->with('message', 'Dummy created successfully');
}
my view method:
public function view($id)
{
$dummy = Dummy::find($id);
return view('index/view', [
'dummy' => $dummy
]);
}
my corresponding routes:
Route::get('index/view/{id}', 'IndexController#view');
Route::post('index/create', 'IndexController#create');
and my form:
<form action="create" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="content">Content</label>
<textarea name="dummy_content" cols="80" rows="5" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-default btn-sm">Submit</button>
</form>
When I submit my form I get the following exception:
InvalidArgumentException in UrlGenerator.php line 314:
Route [index/view/] not defined.
I've been stuck here for quite some time and I still can't figure out why I'm not generating my route properly.
What am I missing?
You are trying to call a route when instead you should call the controller. This will do the trick
return redirect()->action('IndexController#view', ['id' => $id])->with($stuff);
Also, i suggest you to define aliases to routes, so you could do something like
In your controller:
return Redirect::route('route_alias', ['id' => $id])->with($stuff);
In your routes:
Route::get('/index/view/{id}', [
'as' => 'route_alias',
'uses' => 'IndexController#view'
]);
I have created a new Laravel 5.2 installation. And I have run the following command to install the default Laravel authentication;
php artisan make:auth
The registration form works but the login just redirects home without logging in. And displays no errors when when I enter the wrong credentials.
This is my routes file:
Route::get('/', 'BaseController#index');
Route::get('/tutors', 'TutorsController#Index');
Route::get('/tutors/myrequest', 'TutorsController#RequestTutor');
Route::get('/tutors/{id}', 'TutorsController#show')->where(['id' => '[0-9]+']);
Route::get('/tutors/{GUID}', 'TutorsController#TutorByGUID')->where(['id' => '[A-Za-z]+[0-9]+']);
/********************Authentication routes**********************************/
Route::group(['middleware' => ['web']], function () {
Route::auth();
});
This is code from the AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/';
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
This is the BaseController which contains the home method;
<?php namespace App\Http\Controllers;
use App\Services\InterfaceService;
use App\Repositories\TutorRepository;
use App\Http\Requests;
use Illuminate\Http\Request;
class BaseController extends Controller {
protected $TutorRepository;
protected $InterfaceService;
public function __construct(InterfaceService $InterfaceService, TutorRepository $TutorRepository)
{
//$this->middleware('guest');
$this->InterfaceService = $InterfaceService;
$this->TutorRepository = $TutorRepository;
}
public function index()
{
$tutors = $this->TutorRepository->all();
$page_info = \Config::get('constants.App.Pages.home');
$this->InterfaceService->SetPageInfo($page_info);
return view('home', ['TopTutors'=>$tutors]);
}
} ?>
This is code from the login view.
<form role="form" method="POST" action="{{ url('/login') }}" id="login_form">
{!! csrf_field() !!}
<div class="mj_login_form">
<div class="form-group">
<input type="text" placeholder="Email" id="email" name="email" class="form-control" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block"><strong>{{ $errors->first('email') }}</strong></span>
#endif
</div>
<div class="form-group">
<input type="password" placeholder="Your Password" id="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block"><strong>{{ $errors->first('password') }}</strong></span>
#endif
</div>
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 mj_toppadder20">
<div class="form-group pull-left">
<div class="mj_checkbox">
<input type="checkbox" value="1" id="check2" name="remember">
<label for="check2"></label>
</div>
<span> remember me</span>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 mj_toppadder20">
<div class="form-group pull-right">
<span>forget password ?</span>
</div>
</div>
</div>
</div>
<div class="mj_pricing_footer">
login Now
</div>
</form>
That happens because your '/' route is not under the web middleware group and you're not using the auth middleware for the routes you want to be authenticated
This means that when accessing that route, session is not available, and the auth middleware doesn't fire, so authentication doesn't work.
Try to put all the routes in which you want to use session under the web middleware group, and for the routes in which you want authentication use the auth middleware:
Route::group( ['middleware' => ['web'] ], function () {
/* these routes use 'auth' middleware, so only an authenticated user will access*/
Route::group( ['middleware' => 'auth' ], function () {
Route::get('/', 'BaseController#index');
});
Route::auth();
});
A Note on Laravel version:
Keep in mind that if you're using Laravel version >= 5.2.27 the middleware web is used by default on every route defined in routes.php as you can see in app/Providers/RouteServiceProvider.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web'
], function ($router) {
require app_path('Http/routes.php');
});
}
In that case you can remove you statement for using the web middleware group, but you'll only need to use auth middleware for the authenticated routes
i use the validated method for validate request, but the var errors is empty in the view :/.
in the controller, i have:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function(){
return view('home');
})->name('home');
Route::group(['prefix' => 'do'], function($name = null){
Route::get('/{action}/{name?}', ['uses' => 'controllers#get', 'as' => 'get']);
Route::post('/', ['uses' => 'controllers#post', 'as' => 'post' ]);
});
});
for the controller, i have:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class controllers extends Controller
{
public function get($action, $name=null)
{
return view('actions.' . $action, ['name' => $name]);
}
public function post(Request $request)
{
$this->validate($request, [
'action' => 'required',
'name' => 'alpha|required'
]);
return view('actions.'.$request['action'] , ['action' => $request['action'], 'name'=>$this->transformName($request['name'])]);
}
private function transformName($name)
{
$add = "king ";
return $add.strtoupper($name);
}
}
and for the view, i have:
#extends('layouts.master')
#section('content')
<div class="centered">
greet
hug
kiss
<br >
<br >
#if (isset($errors) && count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
{!! $errors->first() !!}
#endforeach
</ul>
</div>
#endif
<form action="{{ route('post')}}" method="post">
<label for="select-action">I want to...</label>
<select id="select-action" name="action">
<option value="greet">greet</option>
<option value="hug">hug</option>
<option value="kiss">kiss</option>
</select>
<input type="text" name="name">
<button type="submit">action</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</div>
#endsection
if i delete the middleware of the route, the var errors work correctly.
how i can fix this?
thanks.
If you're using latest Laravel 5.2 build, you should remove web middleware from routes. Now it applies automatically to all routes and if you're trying to add it manually, it causes different errors.