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
}
Related
Previously, I was trying for a few hours to get my "destroy()" function working. Which would sound ridiculous to most of you but simply putting "method("DELETE")" in the form made it work, which I still don't why.
Now, I'm stuck with the update() function. Once I click update, the page just reloads and does nothing. It doesn't update the info in the database nor does it redirect me back to the index. Here's the code:
Route (web.php):
Route::resource('books', BookController::class);
Form (Edit.blade.php):
#section('content')
<div class="row">
<div class="col-lg-12">
<form action="{{ route('books.update', $book->id) }}" method="POST">
#csrf
#method('PUT')
<div class="mb-3 mt-3">
<label for="exampleFormControlInput1" class="form-label">Book Title</label>
<input type="text" name="title" class="form-control" value="{{ $book->title }}">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Book Author</label>
<input type="text" name="author" class="form-control" value="{{ $book->author }}" placeholder="Author Name..">
</div>
<div class="btn-group" role="group">
<button type="submit" class="btn btn-block btn-danger">Update</button>
<button type="button" class="btn btn-success">Go Back</button>
</div>
</form>
</div>
</div>
#endsection
Controller (BookController):
public function update(Request $request, Book $book)
{
$validated = $request->validate([
'title' => 'required|max:255|unique:books',
'author' => 'required|max:255'
]);
Book::where('id',$book->id)->update($validated);
return redirect()->route('books.index')->with('message','Book Updated!');
}
What am I doing wrong here? Some help would be appreciated.
I think the problem is in your unique validation. When you don't change the title in the form and hit updated, the unique validation fails. It fails because the title already exists in the database. We have to skip unique validation for the resource that is being updated.
$validated = $request->validate([
'title' => 'required|max:255|unique:books,title,'.$book->id, // <-- change this
'author' => 'required|max:255'
]);
$book->update( $request->only(['title', 'author']) );
I need some advice. I make a view for editing a database that contains textarea form. Unfortunately, when I hit the save button it doesn't give any change to the database. What should I do?
Here's the form in infoupdate.blade.view:
<form action="{{ route('updateinfo') }}" method="POST">
#method('PUT')
#csrf
<div class="intro-y box p-5">
<div>
<div class="mt-3"> <label for="by" class="form-label">Oleh</label> <input name="by" id="by" type="text" class="form-control" value="{{ auth()->user()->username }}" readonly></div>
</div>
<div>
<div class="mt-3"> <label for="selectedTime" class="form-label">Waktu Pengumuman</label> <input name="selectedTime" id="selectedTime" type="text" class="form-control" value="{{ $infos->selectedTime }}" readonly></div>
</div>
<div class="mt-3">
<label class="pb-8" for="contentInfo">Isi Pengumuman</label>
<textarea name="contentInfo" id="contentInfo" class="w-full border-2" rows="10" cols="100">{{ $infos->contentInfo }}</textarea>
</div>
<div class="text-right mt-5">
<button type="submit" class="btn btn-primary w-24">Simpan</button>
</div>
</div>
</form>
Also the update function in DBIController.php:
public function update(Request $request){
$request->validate([
'contentInfo' => 'required|min:16'
]);
DB::table('infos')->where('id', $request->id)->update([
'contentInfo' => $request->contentInfo
]);
return redirect()->route('DBI')->with('message','Data Pengumuman Berhasil di Update');
}
and the route for displaying the form and the route for updating database in web.php :
Route::get('/infoeditor/{id}',[DBIController::class, 'edit'])->middleware('admin')->name('infoeditor');
Route::put('/updateinfo',[DBIController::class, 'update'])->middleware('admin')->name('updateinfo');
on your update route, you need to add /{id}
Route::put('/updateinfo/{id}',[DBIController::class, 'update'])->middleware('admin')->name('updateinfo');
Then, in your controller method, you will add $id as parameter
public function update(Request $request, int $id)
{
$request->validate([
'contentInfo' => 'required|min:16'
]);
DB::table('infos')->where('id', $id)->update([
'contentInfo' => $request->contentInfo
]);
return redirect()->route('DBI')->with('message','Data Pengumuman Berhasil di Update');
}
And in your view, you update the action url with $id
<form action="{{ route('updateinfo', ['id' => $infos->id]) }}" method="POST">
I have just got this error all the tries while updating my table data.
ErrorException: Creating default object from empty value
AdminController.php
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
My Resource Route
Route::resource('post', AdminController::class);
Blade File
<div class="edit-post-content">
<form action="{{ route('post.update',$list->post_id) }}" method="POST">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{$list->id}}">
<input type="hidden" name="post_rating" value="{{$list->post_rating}}">
<div class="mb-3">
Edit Title: <input class="form-control" name="post_title" type="text" id="exampleFormControlInput1" value="{{$list->post_title}}" aria-label="default input example">
</div>
<div class="mb-3">
Edit Description:
<textarea class="form-control" id="exampleFormControlTextarea1" name="post_details" rows="3">
{{ $list->post_details }}
</textarea>
</div>
<div>
<img src="{{asset('images/'.trim($list->post_image))}}" alt="" width="120px;">
Edit Photos:
<input id="formFileMultiple" class="form-control form-control-lg" name="post_image" type="file" value="{{ $list->post_image }}" multiple>
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
Could someone help me, please?
There is a chance that the model doesn't exist. You can add a check for this in your controller as follows:
public function update(Request $r, $post_id) {
$post = Post::find($post_id);
if (!$post) {
// You can add code to handle the case when the model isn't found like displaying an error message
return back();
}
$post->post_title = $r->post_title;
$post->post_image = $r->post_image;
$post->post_details = $r->post_details;
$post->post_rating = $r->post_rating;
$post->id = $r->id;
$post->save();
return back();
}
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());
}
}
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.