laravel post does not get picked up? - php

I am trying to pass a form through. I am using request method to get variables. here is my blade of a form:
<div class="add_photo">
<h1>Add a photo</h1>
<form action="{{Route('postPhoto')}}">
<span>Name: </span>
<input type="text" name="title">
<span>File: </span>
<input type="text" name="file">
<input type="submit" value="Add">
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
</div>
Routes involved:
Route::get('/admin/gallery', 'GalleryController#manageGallery')->name('manageGallery');
Route::post('/admin/gallery', 'GalleryController#postPhoto')->name('postPhoto');
And this is my controller for it:
class GalleryController extends Controller
{
public function manageGallery() {
return view('home.manageGallery');
}
public function postPhoto(Request $request) {
die("works");
}
}
It does not throw error at me. It just does nothing. So my question is: am I using this method wrong or do I need something more? Thanks in advance.

Firstly make sure that the form you are using is using the correct method for your route
<div class="add_photo">
<h1>Add a photo</h1>
<form action="{{Route('postPhoto')}}" method="post">
<span>Name: </span>
<input type="text" name="title">
<span>File: </span>
<input type="text" name="file">
<input type="submit" value="Add">
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
</div>
In your controller, put the following in the postPhoto function
public function postPhoto(Request $request)
{
dd($request);
}
You should now get a Request object output to the screen when you submit the form

You may wanna use Blade Forms in order to make Forms in a more natural way for Laravel
{{ Form::open(['route' => '/admin/gallery', 'method' => 'post', 'files' => true]) }}
{{ Form::text('title') }}
{{ Form::label('title', 'Name :') }}
{{ Form::file('file') }}
{{ Form::label('file', 'File :') }}
{{ Form::submit('Add') }}
{{ Form::close() }}
It reduces the overhead of adding the token by yourself as it is automatically added when using the Form facade.
And then, in your controller, you would do something like that to debug when sending the form :
<?php
use Request; /* do not forget this line */
class GalleryController extends Controller
{
public function postPhoto(Request $request)
{
dd($request->toArray());
}
}

Related

single form for insert and update data

I am trying to use single form for both data insertion and data update. But I do not know how can it be done.
In my form I've mentioned the action method action="{{action('BookController#create')}}", but I want to use the same form for data insertion and data update.
//book.blade.php
<form class="form-horizontal" method="POST" action="{{action('BookController#create')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" name="NBookName" class="form-control"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-left: 5%;">
<label>Unit Price</label><span class="required">*</span>
<input type="text" maxlength="5" required="required" autocomplete="off" runat="server" name="NBookUnitPrice"/>
</div>
<div class="form-group" style="padding-left: 5%;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
controller code
public function edit($id)
{
$book = Book::find($id);
return view('pages.book',compact('book','id'));
}
route page
// for books
Route::get('/book','BookController#create');
Route::post('/book','BookController#store');
Route::get('/book/{id}','BookController#edit');
I do not know how to process it further.
I am trying to use single form for both data insertion and data update
No you don't, unless you are ready to get killed by another developer who will need to understand what you did there.
You follow the Restful Resource Controllers since Laravel 5.2
It's a quite repetetive solution template
Routes
Route::resource('book', 'BookController');
Controller
class BookController extends Controller {
// Display list of your books
public function index() {
$books = Book::all();
return view('books.index', ['books' => $books]);
}
// Show a form to create a book
public function create() {
return view('books.create');
}
// Show a form to edit a book
public function edit(Book $book) {
return view('books.edit', ['book' => $book]);
}
// Store a new book
public function store(Request $request) {
$this->validate($request, [
'book_name' => 'required|unique:books'
]);
$book = new Book();
$book->book_name = $request->book_name;
if($book->save()) {
return redirect()->route('books.edit', $book)
->with('success', 'Successfully added a book'); // You may print this success message
} else {
return redirect()->back()
->withInput()
->with('error', 'Could not add a book'); // You may print this error message
}
}
// Update existing book
public function update(Request $request, Book $book) {
$this->validate($request, [
'book_name' => 'required|unique:books,book_name,'.$book->getKey().',id'
]);
$book->book_name = $request->book_name;
$book->save();
if($book->save()) {
return redirect()->route('books.edit', $book)
->with('success', 'Successfully updated a book'); // You may print this success message
} else {
return redirect()->back()
->withInput()
->with('error', 'Could not updated a book'); // You may print this error message
}
}
// Delete existing book
public function destroy(Book $book) {
if($book->delete()) {
return redirect()->back()
->with('success', 'Successfully deleted a book'); // You may print this success message
} else {
return redirect()->back()->with('error', 'Could not delete a book'); // You may print this error message
}
}
}
Blade
// Show all of your books using some foreach look and html table
views/books/index.blade.php
// Create a new book
views/books/index.create.php
// Edit an existing book
views/books/index.edit.php
Forms
<!-- Creating a new book (store method) -->
<form action="{{ route('books.store') }}" method="POST">
{{ csrf_field() }}
<input name="book_name" value="{{ old('book_name') ">
<button type="submit">Create</button>
</form>
<!-- Updating an existing book (update method) -->
<form action="{{ route('books.update', $book) }}" method="POST">
{{ csrf_field() }}
{{ method_field('PUT') }}
<input name="book_name" value="{{ old('book_name', $book->book_name) ">
<button type="submit">Update</button>
</form>
<!-- Deleting an existing book (destroy method) -->
<form action="{{ route('books.destroy', $book) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Delete</button>
</form>
Didn't test the code, but still, the developer that sits next to you will not kill you for using common solution patterns.
I think you need another one route:
Route::put('/book/{id}, 'BookController#update')->name('book.update');
In your three methods you may do something like this:
public function edit($id)
{
$action = route('book.update', ['id' => $id]);
$book = Book::find($id);
return view('pages.book',compact('book','id', 'action'));
}
And edit your form (i edited action and input values)
<form class="form-horizontal" method="POST" action="
{{ $action }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row" style="padding-left: 1%;">
<div class="col-md-4">
<div class="form-group">
<label>Book Name</label><span class="required">*</span>
<input type="text" maxlength="100" minlength="3" autofocus="autofocus" autocomplete="off" required="required" value="{{ $book->name ?? '' }}" name="NBookName" class="form-control"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group" style="padding-left: 5%;">
<label>Unit Price</label><span class="required">*</span>
<input type="text" maxlength="5" required="required" autocomplete="off" runat="server" value="{{ $book->price ?? '' }} name="NBookUnitPrice"/>
</div>
<div class="form-group" style="padding-left: 5%;">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
Do not merge update, create, delete, etc. methods. Another request => another method.
You are free to use one form to create and update. If you are following CRUD rules your form meethod will be POST for create and PUT for update, so place #method('PUT') inside your form body for that.
Then you need to create route Route::put('/book','BookController#update')->name('book.update'); for update and Route::post('/book','BookController#store')->name('book.store'); for store. Or just Route::resource('/book','BookController') instead all this methods. Check laravel resource doc.
Next step within your BookController create update(Request $request) method with update logic inside and store(Request $request) method with store logic.
That's it.
First of all, put these inputs and buttons bellow in your modal:
<input type="hidden" name="id" id="id" value="" />
<input type="hidden" name="button_action" id="button_action value="insert" />
<input type="submit" name="action" id="action" class="btn btn-success" value="submit" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
For update, give an id by jquery to your id input:
$('#id').val(id);
$('#button_action').val('update');
$('#action').val('update');
then in your controller:
if($request->get('button_action') == "insert") {
$success_output = insert
}
if($request->get('button_action') == "update") {
$success_output = update
}

Laravel model form binding not working for edit

I have a controller TourCategoryController.php and has edit method:
public function edit(TCategory $tCategory)
{
return view('admin.manage.tour.category.edit')->withCategory($tCategory);
}
And below is the code from my view edit:
<div class="col-sm-4">
{{Form::model($category,['route' => ['tour-category.update', $category->id ], 'method' => "PUT"]) }}
<input type="text" class="form-control" id="name" name="name">
<label for="name">Name</label>
{{ Form::close() }}
</div>
The trouble I'm having is, the input field is not being filled with form modal binding.
While inspecting the edit form action attribute shows action="http://localhost:8000/manage/tour-category" while it should be like action="http://localhost:8000/manage/tour-category/{id}"
Route for the controller:
Route::prefix('manage')
->middleware('role:superadministrator|administrator|user')
->group(function () {
Route::resource('tour-category','TourCategoryController');
});
Use laravel text field instead of plain form text field.
{{ Form::text('name',null,['class'=>'form-control','id'=>'name']) }}
If you are not using Form Facades
<div class="col-sm-4">
<form method="POST" action="{{ route('tour-category.update', $category->id) }}">
{{ method_field('PUT') }}
{{ csrf_field() }}
<label for="name">Name</label>
<input type="text" id="name" name="name" class="form-control">
</form>
</div>
use
{{ Form::text('name',null,['class'=>'form-control','id'=>'name']) }}
instead of
<input type="text" class="form-control" id="name" name="name">

Laravel 5.2 TokenMismatchException in VerifyCsrfToken.php line 67

I will process the data from the form
then I click the add button and get an error
Whoops, looks like something went wrong.
TokenMismatchException in VerifyCsrfToken.php line 67:
i have view
<form action="{{ url('siswa') }}" method="post">
<div class="form-group">
<label for="nisn" class="control-label">NISN</label>
<input name="nisn" id="nisn" type="text" class="form-control">
</div>
<div class="form-group">
<label for="nama_siswa" class="control-label">Nama Siswa</label>
<input name="nama_siswa" id="nama_siswa" type="text" class="form-control">
</div>
<div class="form-group">
<label for="tanggal_lahir" class="control-label">Tanggal Lahir</label>
<input name="tanggal_lahir" id="tanggal_lahir" type="date" class="form-control">
</div>
<div class="form-group">
<label for="jenis_kelamin" class="control-label">Jenis Kelamin</label>
<div class="radio">
<label><input name="jenis_kelamin" type="radio" value="L" id="jenis_kelamin"> Laki-laki</label>
</div>
<div class="radio">
<label><input name="jenis_kelamin" type="radio" value="P" id="jenis_kelamin"> Perempuan</label>
</div>
</div>
<div class="form-group">
<input class="btn btn-primary form-control" type="submit" value="Tambah Siswa">
</div>
</form>
and then this is my controller
public function create()
{
return view('siswa.create');
}
public function store(Request $request)
{
$siswa = $request -> all();
return $siswa;
}
you need to add {{csrf_field()}} inside the form. it will create a csrf token, which is needed to submit a form
You need to add this {{ csrf_field() }} between your form tags.Read here for more information https://laravel.com/docs/5.4/csrf
There are many options to solve this problem.
1) You can take hidden input field for token inside your form like:
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
2) Add following code before the closing tag of your form:
{{ Form::token() }}
3) Or use laravel form syntax to avoid token mismatch problem like below.
{{ Form::open(array('url' => 'foo/bar')) }}
//
{{ Form::close() }}
4) Or in the html form structure you can also use csrf field like below.
<form method="POST" action="/profile">
{{ csrf_field() }}
...
</form>
5) Or lastly.
<form method="POST" action="/profile">
{!! csrf_field() !!}
...
</form>
This will definately work for you.
Thanks

Laravel form not submitting data to database

For some reason, my form isn't submitting any data to the database, but it looks fine from where I'm standing and the database can call the information to the form fine.
Since there's a lot of information for people to submit, I'm making the profile details not part of the login process. Still unfamiliar with how Laravel does these but I roughly get the process now that I've been fiddling.
One thing I'm wondering, is there a specific syntax for forms to write to the database, should I be naming the database's respective table names in the form? Or is that part of the Controller?
Should I be using Form Model Binding? It's a little hard to find information on that that's for the current version of Laravel though.
What am I missing?
//Route::get('NewUser', 'UserEntryController#create');
Route::post('NewUser', 'UserEntryController#UserForm');
//Route::get('NewUser', 'UserEntryController#create')->name('NewUser');
Route::post('NewUser', 'UserEntryController#UserForm')->name('submit');
Controller:
<?php
namespace App\Http\Controllers;
use App\UserEdit;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
class UserEntryController extends Controller
{
protected function create()
{
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
//return $array;
}
public function UserForm(Request $request) {
$email = $request['email'];
$first_name = $request['first_name'];
$password_hint = $request['password_hint'];
$last_name = $request['last_name'];
$user = UserEdit::find(715)->first();
$user->email = $email;
$user->First_Name = $first_name;
$user->Last_Name = $last_name;
$user->Password_Hint = $password_hint;
$user->save();
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
}
}
Blade:
#extends('layout')
#section('content')
<h1> Add Your Information {{ $id['name'] }}</h1>
<div class="row">
<div class="col-md-6">
<h3>Edit</h3>
<form action="{{ route('submit') }}" method="post">
<div class="form-group">
{{ csrf_field() }}
<label for="email">Your E-Mail</label>
<input class="form-control" type="text" name="email" id="email">
</div>
<div class="form-group">
{{ csrf_field() }}
<label for="first_name">Your First Name</label>
<input class="form-control" type="text" name="first_name" id="first_name">
</div>
<div class="form-group">
{{ csrf_field() }}
<label for="last_name">Your Last Name</label>
<input class="form-control" type="text" name="last_name" id="last_name">
</div>
<div class="form-group">
{{ csrf_field() }}
<label for="password_hint">Your Password Hint</label>
<input class="form-control" type="text" name="password_hint" id="password_hint">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<input type="hidden" name="_token" value="{{ Session::token() }}">
</form>
</div>
</div>
#foreach ($id as $key=>$value)
{{ $value }}<br>
#endforeach
#stop
You should use $request->get('email') instead of $request['email'] and the same for everything else you want from the request, and I don't think you have to use ->first() when using ->find
There could be something wrong with the _token field, since there are five csrf fields in the form.
Try to remove this line
<input type="hidden" name="_token" value="{{ Session::token() }}">
and just leave one {{ csrf_field() }} in the form.

How to use update Resource Controllers laravel 4?

I have Customer Controller with index, edit, update methods
Route::resource('customer', 'CustomerController');
Controller methods update
public function update($id) { echo $id; }
my HTML Form
<form action="/customer/1" method="post">
<input type="text" name="email" value="" />
<input type="submit" value="" />
</form>
I have following a Documentation here
http://four.laravel.com/docs/controllers#resource-controllers
PUT/PATCH /resource/{id} update
It's seems not working for me, how to use it? thank you
To use the PATH, PUT or DELETE HTML methods you need to add a hidden input with _method. Like the following...
<input type="hidden" name="_method" value="PUT" />
You can use the Form Builder. Example using blade:
{{ Form::open(array('method' => 'DELETE')) }}
That will automatically add this for you
<input name="_method" type="hidden" value="DELETE">
This works for me in Laravel 4:
{{ Form::open(array('url' => URL::to('customer/1'), 'method' => 'PUT')) }}
I am using Laravel resource controller. For update a page, I copied it from insert page after then
Just I added an extra field to update view like as
{{ method_field('put') }}
Just use this as for update
<form method="post" action="{{ URL::to('customer',$customer['id'])}}">
{{ csrf_field() }}
{{ method_field('put') }}

Categories