Can't get input data from form LARAVEL - php

I'm learning Laravel and I got stuck trying to get data from a form.
I already am able to get data back with GET, but with POST I've been having a ton of trouble. Here's what I'm working with:
Form:
<form id="forms" method="POST" action="sugestoes" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<hr>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
#php
if (isset($_POST["obs"])) {
echo "IN";
}
#endphp
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('sugestoes');
//
}
}
Route:
Route::post('sugestoes', 'PostController#store');
The intended behaviour that I'm trying to reach is for the post to be submitted, and then returning to the same page with an empty form. Later on I'll be sending the input data into a database, but for now I just want to get the post to work.
I guess I'm missing something really basic, but I've been following guides and looking online, I've done some progress but I'm really stuck here.
(some more info, this is Laravel 5.4, and I'm using XAMPP)

First, you need to call the model, use App/Your_model_name; then you have to save the data.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Suggest; //Suggest model, let's hope you have suggest table
class PostController extends Controller
{
public function store(Request $request)
{
$suggest = new Suggest; //model
$suggest->name = $request->obs; //name is DB name, obs is request name
$suggest->save(); //save the post to DB
return redirect()->back()->with('success', 'Saved successfully'); //return back with message
}
}
Then if you want to flash the message on the HTML page
#if(session('success'))
<div class="alert alert-warning alert-dismissible" id="error-alert">
<strong style="color: white;">{{session('success')}}</strong>
</div>
#endif

<form id="forms" method="POST" action="{{ route('sugestoes') }}" novalidate>
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-12">
<label for="obs">Observações:</label>
<textarea type="text" class="form-control" name="obs" placeholder="Observações" required></textarea>
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
Remove the #php tag below the form, then in router.php
Route::post('/sugestoes', 'PostController#store')->name('sugestoes');
Then in Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$name = $request->input('obs');
return redirect('/sugestoes'); // you should have GET in Route.php
//
}
}

Add the following code in your action attribute on the form. It will capture the post URL. When you submit the form it will send the form data to the URL end-point.
action="{{ url('sugestoes')}}"
Then die and dump in your controller store function
public function store(Request $request)
{
dd($request->all());
}

Related

Search user from their Id# after search button is pressed Laravel 8

I want to show registered user data after his/her id# is entered in the input field and on hit enter or when search button is pressed bring his/her data in the fields. I just want to show user data when the search button is pressed. I think the problem is in my controller. This is my controller:
use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
class Helpercontroller extends Controller
{
function search(Request $request){
$patientid = $request->input('patientid');
$data = DB::table('patients')->where(['patientid'=>$patientid])->first();
return $data;
}
}
}
this is my route file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\login;
use App\Http\Controllers\MainController;
use App\Http\Controllers\add1;
use Illuminate\Http\Request;
use App\Http\Controllers\Helpercontroller;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/registration', function () {
return view('registration');
});
Route::post('/registration/search',[Helpercontroller::class,'search'])->name("search-registration");
this is my blade file:
#extends('layouts.theme')
#section('content')
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="col-md-3 col-md-offset-3 d4 " style="margin-top: 50px">
<h4>Patient Registration</h4>
</div><br>
#if(Session::get('success'))
<div class="alert alert-success">
{{Session::get('success')}}
</div>
#endif
#if(Session::get('fail'))
<div class="alert alert-danger">
{{Session::get('fail')}}
</div>
#endif
<form action="{{ route("search-registration") }}" method="POST" autocomplete="off">
#csrf
<label>Search Patient :</label>
<input placeholder="Enter Patient ID" type="number" name="patientid" class="form-control form-control-sm d2" >
</div>
</div>
<div class="col-lg-2">
<button type="submit" class="btn-block col-lg-12 ">Search</button>
</div>
</form>
[![THIS IS MY BLADE FILE OUTPUT][1]][1]
change your route for search, a good practice is name the routes for better organization:
Route::post('/registration/search',[Helpercontroller::class,'search'])->name("search-registration");
In the form:
<form action="{{ route("search-registration") }}" method="POST" autocomplete="off">
Problem is in your route file.
Route::get('/registration', function () {
return view('registration');
});
Route::get('registration',[Helpercontroller::class,'search']);
Both the route are same. So Laravel will return the first matching route. You need to change the route or at least change the route method.
see below for more details.
Router-Methods

Laravel Error: The POST method is not supported for this route. Supported methods: GET, HEAD

Good evening , for school i am trying to create a simple CRUD app, using laravel 6 and mongoDB.
I can get read, update and delete working but creat fails with The POST method is not supported for this route. Supported methods: GET, HEAD.. I have searched the answers here and other sites but im stuck for 2 days now (could be something very silly but im not seeing it)
my routes are:
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/post/{_id?}', 'PostController#form')->name('post.form');
Route::post('/post/save/', 'PostController#save')->name('post.save');
Route::put('/post/update/{_id}', 'PostController#update')->name('post.update');
Route::get('/post/delete/{_id}', 'PostController#delete')->name('post.delete');
form.blade is:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Post Form</div>
<div class="card-body">
#if($data)
<form action = "{{Route ('post.update', $data->_id)}}" method="post">
#csrf
#method('PUT')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content">{{$data->content}}</textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#else
<form action = "{{Route ('post.form')}}" method="post">
#csrf
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content"></textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
#endif
</div>
</div>
</div>
</div>
#endsection
and my PostController is:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function form($_id = false){
if($_id){
$data = Post::findOrFail($_id);
}
$data = false;
return view ('post.form', compact('data'));
}
public function save (Request $request){
$data = new Post($request->all());
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function update (Request $request, $_id){
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->save();
/* return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]); */
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function delete($_id){
$data = post::destroy($_id);
if($data) {
return redirect()->route('home');
}
else {
dd('error cannot delete this post');
}
}
}
Anybody any idea what i am missing?
Thanks in advance
You have to replace this line <form action = "{{Route ('post.form')}}" method="post"> with <form action = "{{Route ('post.save')}}" method="post">
You are using wrong route. Please change to Route ('post.save')
EDIT: I found that one myself, the PostControler didnt return a view if there was an $_id
Thanks for the help everyone!
Thanks for pointing that out, it did bring my from back to life :) However it breaks the update function :S.
When i now click on the edit button, the form does no longer get filled with the data for the post, and "save" creates a new post in stead of updating it.

The PUT method is not supported for this route. Supported methods: GET, HEAD, POST, DELETE. (note I am using model biding)

I am using model biding, but I am basically trying to create a form that can edit and update comments. It runs perfectly and even prompts me to edit the form. However, every time I try to update it the POST method is not supported for the root. which is bogus as I did the spoofing correctly, someone help me please.
Here us my CommentsController methods
public function edit($id)
{
$comment = Commenting::find($id);
return view('comments.edit', compact('comment'));
}
public function update(Request $request, $id, $posts)
{
$comment = Commenting::find($id);
$comment->update($request->all());
$comment->posts_id = $posts;
return view('post.show', compact('comment'));
}
Here is the routing in my web.php
Route::get('/posts/comment/{comment}', 'CommentsController#edit')->name('comments.edit')->middleware('auth');
Route::put('/posts/comment/{comment}', 'CommentsController#update')->name('comments.update')->middleware('auth');
Here's what I call the link to edit the form in my show.blade
Edit
lastly this is my edit.blade file
#extends ('layouts.home')
#section ('content')
<div class="card">
<h1> Edit Comment </h1>
<div class="card-block">
<form method="POST" action="{{route('comments.update', ['comments' => $comment])}}">
#csrf
#method('PUT')
<div class="form-group">
<textarea name="body" placeholder="Enter you comment here..." class="form-control"> {{$comment->body}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Update</button>
</div>
</form>
#include ('layouts.errors')
</div>
</div>
#endsection
Take a look your update method
public function update(Request $request, $id, $posts)
Try to delete the $posts variable on update function
Try
{{method_field('put')}}
or
<input type="hidden" name="_method" value="PUT">
add patch method in blade file:
#extends ('layouts.home')
#section ('content')
<div class="card">
<h1> Edit Comment </h1>
<div class="card-block">
<form method="POST" action="{{route('comments.update', ['comments' => $comment])}}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH">
<div class="form-group">
<textarea name="body" placeholder="Enter you comment here..." class="form-control"> {{$comment->body}}</textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Update</button>
</div>
</form>
#include ('layouts.errors')
</div>
</div>
#endsection
write post method in route file :
Route::post('/posts/comment/{comment}', 'CommentsController#update')->name('comments.update')->middleware('auth');
Your route binding is named comment not comments. This will not generate a URL to your comments.update route:
route('comments.update', ['comments' => $comment])
This will generate a URL to /posts/comment?comments=3 not /posts/comment/3. You want to use the same name as the route parameter so it knows to replace that route parameter:
route('comments.update', ['comment' => $comment])
Which would generate a URL to /posts/comment/3.
Also your controller method
public function update(Request $request, $id, $posts)
has a $posts variable but there is no parameter for that defined for the route, so where does that come from?
If you actually want to use Model Binding, which it would appear you are not, you could use Implicit Bindings by type-hinting a $comment argument on that controller method:
public function update(Request $request, Comment $comment)
as the route pararemeter is named comment not id.
Laravel 5.8 - Routing - Route Model Binding - Implicit Binding

unique validation is in not working in laravel 5.4

I am making a todo list with validation using laravel 5.4.
When I click on the submit button, only the required validation is working but not the unique.
What am I doing wrong and how do I fix it so as to get it working as desired?
Below is my form (located at home.blade.php):
<div class="panel-body">
<form class="form form-control" action="/todo" method="post">
{{csrf_field()}}
<fieldset class="form-group">
<textarea class="form-control" name="textbox" id="textArea"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</form>
{{-- for dispaying the error --}}
#if (count($errors) >0)
{{-- expr --}}
#foreach ($errors->all() as $error)
<h3 class="text-danger">{{$error}}</h3>
#endforeach
#endif
</div>
Here, the content of my Todo controller (in my todocontroller.php file):
use Illuminate\Http\Request;
use App\todo;
public function store(Request $request)
{
$todo = new todo;
$todo->body = $request->textbox;
$this->validate($request,[
"body" => "required|unique:todos"
]);
$todo->save();
return redirect('/todo');
}
You should simply use the name of the field; you don't need to stress yourself.
Take a look at the snippet below:
<?php
namespace App\Http\Controllers;
use App\Todo;// following Laravel's standards, your model name should be Todo; not todo
use Illuminate\Http\Request;
class NameOfYourTodoController extends Controller
{
public function store(Request $request)
{
$todo = new Todo();
// use the name of the field directly (here, textbox)
$this->validate($request, [
'textbox' => 'required|unique:todos'
]);
// other code logics here.
}
}

Laravel- Form post going to wrong URL

I am learning Laravel from scratch.
I am doing simple form "POST" but something is missing and I am not able to find out what is missing.
So here is my "routes.php":
Route::get('cards','CardsController#all');
Route::get('cards/{card}','CardsController#show');
Route::post('cards/{card}/notes','NotesController#new');
and view:
<div>
<form method="POST" action="cards/{{ $card->id }}/notes">
<div class="form-group">
<label>Note body:</label>
<textarea name="body" class="form-control"></textarea>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
</div>
and here is controller:
`
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class NotesController extends Controller
{
public function new(Request $request){
return $request->all();
}
}
`
Now when I submit the form it gives me following error:
NotFoundHttpException in RouteCollection.php line 161
and the URL in browser becomes:
http://localhost:88/learning/cards/cards/1/notes
which is definitely wrong.
I think I am missing something very basic.
Please guide me.
Thank you.
Change the form action to,
<form method="POST" action="{{ url('cards/'.$card->id.'/notes') }}" >
Your action starts with "cards/". Change the action to start with '/cards/' so that it's path is not calculated relative to the current route.
<form method="POST" action="/cards/{{ $card->id }}/notes">

Categories