I've created a form in Laravel to submit registration data to database. I've done this identically as other form in other view that works. Checked for typo's but still when I press submit button, nothing happens.
HTML of form in 'registrations/create.blade.php'
<form method="POST" action="{{route('registrations.store')}}"></form>
<div class="container">
<p>Prašome užpildyti visus laukus.</p>
<hr>
#csrf
<label for="vardas"><b>Vardas</b></label>
<input type="text" placeholder="Įveskite savo vardą" name="vardas" required>
<label for="pavarde"><b>Pavardė</b></label>
<input type="text" placeholder="Įveskite savo pavardę" name="pavarde" required>
<label for="el_pastas"><b>El. paštas</b></label>
<input type="text" placeholder="Įveskite savo el. paštą" name="el_pastas" required>
<label for="tel_nr"><b>Telefono nr.</b></label>
<input type="text" placeholder="Įveskite savo telefono nr." name="tel_nr" required>
<b>Pasirinkite norimą gitaros mokytoją</b><br><br>
<input type="radio" name="mokytojas_id" value="1"> Petras Petrauskas<br>
<input type="radio" name="mokytojas_id" value="2"> Andrius Rimiškis<br>
<input type="radio" name="mokytojas_id" value="3"> Virgis Stakėnas<br>
<hr>
<button type="submit" class="registerbtn"><b>Registruotis</b></button>
</div>
</form>
'routes.web.php'
Route::get('/', 'PagesController#index');
Route::get('/contacts', 'PagesController#contacts');
Route::get('/form', 'PagesController#form');
Route::get('/guitarists', 'PagesController#guitarists');
Route::get('/news', 'PagesController#news');
Route::resource('questions', 'QuestionsController');
Route::resource('registrations', 'RegistrationsController');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#dashboard');
Route::resource('guitarists', 'MokytojaiController');
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Registration extends Model
{
protected $fillable = ['vardas', 'pavarde', 'el_pastas', 'tel_nr', 'mokytojas_id'];
}
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Registration;
class RegistrationsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//$questions = DB::select('SELECT * FROM questions');
//$questions = Question::orderBy('id','desc')->take(1)->get();
//$questions = Question::orderBy('id','desc')->get();
$registrations = Registration::orderBy('id','desc')->paginate(10);
return view ('registrations.index')->with('registrations', $registrations);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('registrations.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'vardas' => 'required',
'pavarde' => 'required',
'el_pastas' => 'required',
'tel_nr' => 'required',
'mokytojas_id' => 'required'
]);
$post = $request->all();
Registration::create($post);
return redirect('/registrations/create')->with('status', 'Registracija atlikta!');
}
Your form tag is closed immediately.
<form method="POST" action="{{route('registrations.store')}}"></form>
Is this a type when you posted here or most probably this is the issue. Button is doing nothing since its not inside the form tag.
Related
I have made a simple form when I am calling the form from api route it is showing an error that "errors" is an undefined variable when I am calling using web route it just works fine and shows no error. Why is this happening? Since error is a pre defined variable but why is it showing error.
Layout file:
#extends('layout')
#section('content')
<h1 class="title">Simple Form</h1>
<form method="POST" action="/website/atg/public/projects">
#csrf
<div class="field">
<label class="label" for="name">Name</label>
<div class="control">
<input type="text" class="input" name="name" placeholder="Enter Name" value="{{old('name')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="email">E-mail</label>
<div class="control">
<input type="text" class="input" name="email" placeholder="Enter E-mail Address" value="{{old('email')}}" required>
</div>
</div>
<div class="field">
<label class="label" for="pincode">Pincode</label>
<div class="control">
<input type="text" class="input" name="pincode" placeholder="Enter Pincode" value="{{old('pincode')}}" required>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button">Submit</button>
</div>
</div>
#if($errors->any())
<div class="notification">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
#endsection
Routes file:
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
*/
Route::apiResource('projects','ATGController');
Controller file:
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Mail\ProjectCreated;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class ATGController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('projects.index');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects')
->withErrors($validator)
->withInput();
}
else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}
/**
* Display the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function show(Project $project)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function edit(Project $project)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Project $project)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Project $project
* #return \Illuminate\Http\Response
*/
public function destroy(Project $project)
{
//
}
}
you have to return validator fails like this, to be able to get $errors in your blade. Check below example for reference and change the code to your parameters
don't forget to import use Illuminate\Support\Facades\Validator;
public function store(Request $request){
$validator = Validator::make($request->all(), [
'name'=>'required|unique:projects,name',
'email'=>'required|email|unique:projects,email',
'pincode'=>'required|digits:6'
]);
if ($validator->fails()) {
return redirect('/projects/create')
->withErrors($validator)
->withInput();
}else{
$project=Project::create(request(['name','email','pincode']));
\Mail::to('sbansal1809#gmail.com')->send(
new ProjectCreated($project)
);
//echo '<script>alert("User added sucessfully!")</script>';
return response()->json($project);
}
}
I'm trying to make a website where you can upload games and see them on the home page, but because I need a two-step form I can't directly send them to the database.
my controller:
public function createstep1(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.game',compact('naam', $naam))->with('games', game::all());
}
public function postcreatestep1(Request $request)
{
$validatedData = $request->validate([
'naam' => 'required',
'geslacht' => 'required',
]);
if(empty($request->session()->get('naam'))){
return redirect('/game');
}else{
$naam = $request->session()->get('naam');
$naam->fill($validatedData);
$request->session()->put('naam', $naam);
}
return redirect('/newgame');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$naam = $request->session()->get('naam');
return view('games.newgame',compact('naam',$naam));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$game= new Game();
$game->game= $request['game'];
$game->naam= $request['naam'];
$game->geslacht= $request['geslacht'];
$game->save();
return redirect('/game');
}
<div id="newgame" style="height: 500px; width: 250px; float: left;">
<form method="post" name="naam">
#csrf
<input id="naam" name="naam" placeholder="naam">
<select name="geslacht" type="text">
<option name="man">man</option>
<option name="vrouw">vrouw</option>
</select>
<a type="submit"><button>volgende</button></a>
</form>
</div>
<div id="games" style="float: right">
#foreach($games as $game)
{{$game->game}} <br><br>
#endforeach
</div>
<h1>welkom {{$naam}}</h1>
<form method="post">
#csrf
<h3>game invoeren</h3>
<input type="text" id="gamenaam" name="gamenaam" placeholder="game">
<a id="submit" type="post" name="game" href="/newgame/store">
<button>verstuur</button></a>
</form>
Route::get('/', function () {
return view('welcome');
});
Route::get('/newgame', function () {
return view('games.newgame');
});
//Route::post('/newgames', ['as' => '/newgames', 'uses' => 'GameController#create']);
Route::get('/game', 'GameController#createstep1');
Route::post('/game', 'GameController#postcreatestep1');
Route::get('/newgame', 'GameController#create');
Route::post('/newgame/store', 'GameController#store');
I expect it will drop the game + name and gender in the database but the actual code gives an error message.
This work is for school but they can't help me if you have suggestions or can help me fix the problem that would be great.
When registering a new route you need to specify which HTTP method the route is for. Usually Route::get() is alright but since you're sending a POST request with your form to the controller method postcreatestep1, this one needs to be registered as a POST route with Route::post().
You may also declare a route available for multiple HTTP methods with the Route::match() method.
To get an overview of all available router methods the official documentation of Laravel is a good starting point.
I am using PHP Laravel framework. I am trying to save a form after submission. Strangely first time it is not saving, but subsequently, it is saving. On the first post request, the flow isn't even entering function save_application
Code below.
My controller:
class ApplicationController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['store_application']]);
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function save_application(Request $request){
$user = Auth::user();
if(isset($request->application)){
$application = Application::where("user_id",$user->id)->first();
if($application){
$application->update($request->application);
}else{
$application = new Application;
$application = Application::create($request->application);
$application->user_id = $user->id;
$application->save();
}
}
return $this->store_application($request);
}
public function store_application(Request $request){
if(isset($request->application)){
if($request->session()->has('application')){
$request->session()->forget('application');
}
$application_data = [];
$application = new Application;
$application->attributes = $request->application;
$application_data["application"] = $application;
$request->session()->put("application" , $application_data);
}
//
return Redirect::to("/application")->withErrors(array("success"=>"Thank you for submitting the application"));
}
}
My routers
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('application');
My html
<form method="POST" action="/application" enctype="multipart/form-data" id='application_form'>
<input type="hidden" name="_token" value="xtQapusSjgf5XVUxjCOudedeH93a8hEqyfaNh8ChEaKt">
<input type='checkbox'>
<label>I've read and accept the terms and conditions</label>
<p class='font-size-16 font-bold text-uppercase text-black'>
Your information
</p>
<hr class='hr1'>
<div class='row form-group'>
<div class='col-lg-6'>
<label class='control-label'>First name*</label>
<input type='text' class='form-control' name='application[first_name]' value="">
</div>
<div class='col-lg-6'>
<label class='control-label' >Last name*</label>
<input type='text' class='form-control' name='application[last_name]' value="">
</div>
</div>
<div class='form-group'>
<label class='control-label' >Middle name</label>
<input type='text' class='form-control' name='application[middle_name]' value="">
</div>
<div class='form-group'>
<label class='control-label'>ID*</label>
<input type='text' class='form-control' name='application[]' value="">
</div>
<button class="btn btn-primary text-uppercase">Submit <i class='fa fa-check text-white'></i></button>
</form>
your routes have the same name, give them differents.
Route::post('/application', 'ApplicationController#save_application')->name('application');
Route::post('/application_store', 'ApplicationController#store_application')->name('other');
and in your form, you can:
<form method="POST" action="{{ route('application') }}" enctype="multipart/form-data" id='application_form'>
and as senty say:
<button type="submit">
</form>
I think you overcomplicate things, you can simply use updateOrCreate() to make it cleaner.
First of all, make sure $fillable or $guarded is utilized in your Application model. (Application.php)
protected $fillable = ['each', 'field', 'as', 'string'];
// or
protected $guarded = [];
Some improvements for your method:
public function save_application(Request $request){
// 1. Do a proper check
$request->validate([
'application.first_name' => 'required',
'application.middle_name' => 'required',
'application.last_name' => 'required'
]);
// 2. Update or Create
$application->updateOrCreate(
[ 'user_id' => $user->id ],
$request->application // I suppose this is an array that you want
);
// 3. Handle the redirect the right way so you can eliminate the other `store_applcation()` method entirely
return redirect()->back()->with([
'application' => $application
'success' => "Your Message"
]);
}
Also you don't need store_application() method in your controller or its route because your html form is POST'ing to /application route.
This is what you want, right?
I have a resource controller TruckController generated via php artisan make:controller TruckController --resource.
When I go go to localhost/trucks/1/edit, the edit form shows up successfully.
When I click submit, I am redirected to the resource show page (localhost/trucks/1); however, the truck information is not updated and no errors were thrown.
It seems the update function is not firing at all, which I think means there is something wrong with the action attribute in my form, but I am still unsure. There shouldn't be an issue with the routes because the routes should already be defined because it's a resource controller.
edit.blade.php
<form method="PUT" action="{{ action('TruckController#update', ['id' => $truck->id]) }}" class="validate form-horizontal form-groups-bordered" novalidate="novalidate">
#csrf
<input type="hidden" name="state" data-geo="administrative_area_level_1" value="{{ $truck->state }}">
<input type="hidden" name="city" data-geo="locality" value="{{ $truck->city }}">
<input type="hidden" name="zipcode" data-geo="postal_code" value="{{ $truck->zipcode }}">
[ ... ]
</form>
TruckController#update
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(TruckCreateRequest $request, Truck $truck)
{
$validated = $request->validated();
$truck->name = $request->name;
$truck->description = $request->description;
$truck->save();
}
TruckCreateRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class TruckCreateRequest 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 [
'name' => 'required',
'description' => 'required',
'city' => 'required',
'state' => 'required',
'zipcode' => 'required',
'address' => 'required'
];
}
}
And just in case this may be of more help ...
Web.php
<?php
Auth::routes();
// ajax
Route::post('ajax/notifications/clear', 'DashboardController#mark_notifications_read');
Route::get('/', 'DashboardController#index')->name('dash');
Route::resource('events', 'EventController');
Route::resource('venues', 'VenueController');
Route::resource('trucks', 'TruckController');
Route::resource('admin', 'AdminController');
App/Models/Truck.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Truck extends Model
{
//
}
From the Laravel Documentation:
Since HTML forms can't make PUT, PATCH, or DELETE requests, you will
need to add a hidden _method field to spoof these HTTP verbs.
Try to add a hidden method field to the form:
#method('PUT')
Read more here: https://laravel.com/docs/5.7/blade#method-field
You should try this:
<form method="POST" action="{{ action('TruckController#update', [$truck->id]) }}" class="validate form-horizontal form-groups-bordered" novalidate="novalidate">
#csrf
<input type="hidden" name="state" data-geo="administrative_area_level_1" value="{{ $truck->state }}">
<input type="hidden" name="city" data-geo="locality" value="{{ $truck->city }}">
<input type="hidden" name="zipcode" data-geo="postal_code" value="{{ $truck->zipcode }}">
[ ... ]
</form>
Im doing a university project which is a foodlog, where the user is able to log in and then log their food items. Ideally this will post to the database, then the user will be able to view all their logged foods displayed in a table.
at the minute im trying to post the form information to the database and it doesnt seem to work. I also want the user's id to be logged in the database which is a foreign key in the food log table (from users table).
This is my PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
class PostsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store()
{
Post::create([
'id'->request('id');
'user_id'->Auth::user()->id;
'name'->request('name');
'servings'->request('servings');
'servingsize'->request('servingsize');
'calories'->request('calories');
'fat'->request('fat');
]);
return redirect('/foodlog');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
This is my add.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="POST" action="/posts">
{{ csrf_field() }}
<h1>Add to Foodlog</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="name" name="name" class="form-control">
</div>
<div class="form-group">
<label for="noOfServings">Number of Servings:</label>
<input type="number" id="servings" name="servings" class="form-control">
</div>
<div class="form-group">
<label for="servingSize">Serving Size (g):</label>
<input type="number" id="servingsize" name="servingsize" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
</div>
</div>
#endsection
And my web.php
<?php
Route::get('/', 'FoodlogController#index');
Route::get('/add', 'FoodlogController#add');
Route::get('/account', 'FoodlogController#account');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/foodlog', function() {
return view('/foodlog');
});
Route::get('/logout', function(){
Auth::logout();
return Redirect::to('welcome');
});
Route::post('/posts', 'PostsController#store');
I have also included a screenshot of my create foodlog migrations file so that you can see the fields in my table
Also my Post model is empty as you can see
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//
}
Your store function should looks like:
public function store(Request $request)
{
Post::create([
'id' => $request->id, //<--- if this is autoincrement then just delete this line
'user_id' => Auth::user()->id,
'name' => $request->name,
'servings' => $request->servings,
'servingsize' => $request->servingsize,
'calories' => $request->calories,
'fat' => $request->fat
]);
return redirect('/foodlog');
}
For relationship between tables please follow this link
Add to Post model fillable fields:
protected $fillable = [
//if id is not autoincrement then add 'id'
'user_id',
'name',
'servings',
'servingsize',
'calories',
'fat'
];