how do i send a form POST method with GET route in laravel?
Route
Route::get('domain_detail/{domain_name}','domain_detailController#index');
View domain_detail folder
<form method="post" action="{{url('domain_detail')}}/{{strtolower($domain_detail->domain_name)}}">
<div class="form-group">
<label for="namefamily">namefamily</label>
<input type="text" class="form-control round shadow-sm bg-white text-dark" name="namefamily">
</div>
<div class="form-group">
<label for="mobile">mobile</label>
<input type="text" class="form-control round shadow-sm bg-white text-dark" name="mobile">
</div>
<div class="form-group">
<label for="myprice">myprice</label>
<input type="number" class="form-control round shadow-sm bg-white text-dark" name="myprice">
</div>
<div class="form-group">
<input type="submit" name="send_price" class="btn btn-success" value="submit">
</div>
</form>
Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class domain_detailController extends Controller
{
public function index($domain_name)
{
$domain_detail_exist = DB::table("domains")->where('domain_name', $domain_name)->exists();
if ($domain_detail_exist) {
$domain_detail = DB::table("domains")->where('domain_name', $domain_name)->first();
return view('domain_detail/index', ['domain_detail' => $domain_detail]);
} else {
return view('404');
}
}
public function create()
{
return view('domain_detail.index');
}
}
At the controller i didn't put any codes in the create function, but when i click on submit button in form i get this error
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The POST method is not supported for this route. Supported methods:
GET, HEAD.
Use the index function in your domain_detailController just so return the view.
like this:
public function index($domain_name)
{
return view('domain_detail.index');
}
create a route to return the view:
Route::get('domain_detail/','domain_detailController#index');
Then use the create function to store the domain detail like this:
public function create($domain_name)
{
$domain_detail_exist = DB::table("domains")->where('domain_name', $domain_name)->exists();
if ($domain_detail_exist) {
$domain_detail = DB::table("domains")->where('domain_name', $domain_name)->first();
return view('domain_detail/index', ['domain_detail' => $domain_detail]);
} else {
return view('404');
}
}
make a POST route like this:
Route::post('domain_detail/','domain_detailController#create');
Also take a look at the laravel best practices when it comes to naming conventions:
https://www.laravelbestpractices.com/
Related
I am having a problem with the routing.
Firstly, I am on the page (rate product)/{$id}
Next, when clicking the button, I want to go to another view (addReview/{$productID}/{$clientID}) But it gives me an error.
-web.php file
Route::get('rateProduct/{id}', 'CatalogController#getProduct')
->name('rateProduct');
Route::post('./addReview/{$productID}/{$clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
add_review.blade.php
<div class="mb-3">
<form method="post" action="{{url('rateProduct.addReview', [$product->id, 10]) }} value="{{ csrf_token() }}"">
{{--{{ csrf_field() }}--}}
<label for="exampleFormControlTextarea1" class="form-label">Share your thoughts!</label>
<textarea class="form-control rounded" id="exampleFormControlTextarea1" rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences" name="comment"></textarea>
</div>
<button type="submit" class="btn btn-primary">Send</button>
</form>
ReviewController.php
class ReviewController extends Controller
{
public function addReview($productID, $clientID)
{
if(isset( $_POST['submit'])) {
$comment = $_POST["comment"];
}
$date = date_create();
$reviewID = DB::table('review')->max('id') + 1;
$data = array(
'id'=>$reviewID,
"comment"=>$comment,
"review_date"=>date_timestamp_get($date),
"rating"=>1,
"client_id"=>$clientID
);
DB::table('review')->insert($data);
$data2 = array('product_id'=>$productID,"review_id"=>$reviewID);
DB::table('product_review')->insert($data2);
return view('pages/product-page');
}
}
Review model
class Review extends Model
{
use HasFactory;
public $timestamps = false;
protected $table = 'Review';
public function owner() {
return $this->belongsTo('App\Models\Product');
}
}
You have error in routing .Remove dot from the beginning(./addReview/{$productID}/{$clientID}) of string in post method.
Route::post('addReview/{$productID}/{$clientID}','ReviewController#addReview')->name('rateProduct.addReview');
Also you are using url method for named routing in form action it should be
<form method="post" action="{{route('rateProduct.addReview', [$product->id, 10]) }}" >
#csrf
Firstly you have a random . at the start of your route and $ symbols in your parameters, they needs to go.
Route::post('/addReview/{productID}/{clientID}','ReviewController#addReview')
->name('rateProduct.addReview');
Next you need to fix the invalid markup of your add_review blade file, you have mismatched opening/closing elements. You are also using a named route but using the url helper which works with paths rather than route names. You also want to add back in the #csrf token back in otherwise you'll get a 419 error.
<div class="mb-3">
<form method="post"
action="{{ route('rateProduct.addReview', [$product->id, 10]) }}">
#csrf
<label for="exampleFormControlTextarea1" class="form-label">
Share your thoughts!
</label>
<textarea class="form-control rounded"
id="exampleFormControlTextarea1"
rows="3"
placeholder="Tell us about your experiecnce in a couple of sentences"
name="comment">
</textarea>
<button type="submit" class="btn btn-primary">Send</button>
</form>
</div>
You can see a working example here.
I started creating an e-commerce platform and I'm stuck with a problem I can't solve for 2 days.. It's probably something obvious but I just can't find the solution for this. Could you help me with this, please? I get this error:
Missing required parameters for [Route: images.update] [URI: dashboard/images/{image}]. (View: C:\xampp\htdocs\ecommerce\ecommerce\resources\views\website\admin\product_image\update.blade.php)
update.blade.php
#extends('website.admin.layouts.main')
#section('content')
<div class="col-md-12 col-sm-12 ">
<div class="x_panel">
<div class="x_title">
<h2>Zaktualizuj obraz</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form id="updateimage-form" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="" enctype="multipart/form-data" method="POST" action="{{route('images.update', $productImage->id)}}">
#csrf
#method('PUT')
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Produkt<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<select class="form-control" name="product_id">
#foreach ($product as $prodcat)
<option value="{{$prodcat -> id}}" name="product_id">{{ $prodcat -> product_name }}</option>
#endforeach
</div>
</div>
<div class="ln_solid"></div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Nazwa obrazu<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="text" id="img_title" name="img_title" placeholder="Image Title" value="{{ $productImage -> image_name }}" required="required" class="form-control ">
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Wgraj obraz<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="file" name="img" id="img" onchange="fileSelected();"/>
</div>
</div>
<div class="item form-group">
<div class="col-md-6 col-sm-6 offset-md-3">
<button class="btn btn-primary" type="reset">Wyczyść</button>
<button type="submit" class="btn btn-success">Zaktualizuj obraz</button>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
models\ProductImage.php
<?php
namespace App\Models\models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductImage extends Model
{
protected $fillable = [
'product_id',
'image_name',
'image',
'slug',
'status'
];
public function product()
{
return $this -> belongsTo('App\Models\models\Product');
}
}
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\Product;
use App\Models\models\ProductImage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ProductImageController extends Controller
{
public function index()
{
$productImage = ProductImage::all();
return view('website.admin.product_image.index', compact('productImage'));
}
public function create()
{
$product = Product::all();
return view('website.admin.product_image.create', compact('product'));
}
public function store(Request $request)
{
$slug = Str::slug($request->image_name, '-');
$image = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image);
ProductImage::create([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function show(ProductImage $ProductImage)
{
//
}
public function edit(ProductImage $productImage)
{
$product = Product::all();
return view('website.admin.product_image.update',compact('productImage','product'));
}
public function update(Request $request, ProductImage $productImage)
{
$slug=Str::slug($request->image_name,'-');
if($request->image)
{
$image = time() .'.'. $request -> image -> extension();
$request->image->move(public_path('images'), $image);
}
else
{
$image=$productImage->image;
}
$productImage->update([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function destroy(productImage $productImage)
{
$productImage->delete();
return redirect()->route('images.index');
}
}
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('website.shop.layouts.main');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard.index');
Route::resource('/dashboard/categories', 'App\Http\Controllers\ProductCategoryController');
Route::resource('/dashboard/product', 'App\Http\Controllers\ProductController');
Route::resource('/dashboard/images', 'App\Http\Controllers\ProductImageController');
update.blade.php
<form method="post" action="{{route('images.update', $productImage->id)}}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<label for="filename">Select your Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary btn-lg">Update</button>
</div>
</form>
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\ProductImage;;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
public function update(Request $request, $productId){
$product = ProductImage::findOrFail($productId);
if($request->hasfile('image'))
{
$file = $request->file('image');
$name=$file->getClientOriginalName();
$file->move(public_path().'/uploads/ProductImages/', $name);
$file = $name;
$product->image = $file;
}
$product->save();
return redirect()->back();
}
}
I solved this, the problem was with "images" name in route. I changed it to something else everywhere and it works now.
action="{{route('images.update', $productImage->id)}}" is incorrect way of calling route() helper function. Consider the following snippet;
action="{{route('images.update', [
'image' => $productImage->id
])}}"
For more details about route() helper, see this link; https://laravel.com/docs/8.x/helpers#method-route
You don't have Model Binding happening here you have Dependency Injection happening instead. For Implicit Route Model Binding to take place you have to match the type hinted parameter of your method to the name of the route parameter. In your case the route parameter is named image, not productImage. So you are getting an empty new instance of ProductImage instead of the replacement for the Route Model Binding.
Change your controller's parameter to match the route parameter:
vvvvv
public function edit(ProductImage $image)
You would need to change this in all the methods you want the Implicit Binding for, unless you want to override the parameter used in the route.
vvvvv
public function update(Request $request, ProductImage $image)
At the moment you are passing an empty model to your view which is then trying to use it's "id" to generate a route, but "id" is null and route parameters can no to null.
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.
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());
}
I'm trying to POST some data using Cjax in CodeIgniter.
My view is:
<?php
require_once(FCPATH . 'ajaxfw.php');
$ajax->click('#subscribesubmit' , $ajax->form('ajax.php?subscriber/add/'));
?>
<div class="col-md-4">
<form class="form-inline subscribe-box" role="form" method="post">
<div class="form-group">
<label class="sr-only" for="subscribemail">Email address</label>
<input type="text" class="form-control" id="subscribemail" name="subscribemail" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="subscribesubmit">Subscribe</button>
</form>
</div>
This view is loaded in controller index().
My subscriber controller:
class Subscriber extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('email');
$this->load->model('subscriber_model');
require_once(FCPATH.'ajaxfw.php');
}
public function add($subscribemail) {
$ajax = ajax();
//$email = $this->input->post('subscribemail');
echo $subscribemail;
$data['status'] = $this->subscriber_model->new_subscriber($subscribemail);
}
}
}
Try this:
in your code block replace to:
require_once(FCPATH . 'ajax.php');
instead of:
require_once(FCPATH . 'ajaxfw.php');
You should include ajax.php instead of ajaxfw.php (ajax.php would include itself ajaxfw.php if it needs to)