I'm trying to store multiple emails in a prospect system. I'm building the system with Laravel 5.8. I'm trying to put the emails using the AJAX request. And not return in a page using redirect, but keep in the same modal.
This is for a system that in the past, can only store one email. But a user says that need to store more than one email to the client. Now i'm trying to create a functionality that in a prospect, you can add multiple emails and when the user will send a proposal, will show all emails stored in that prospect.
I'm need to use the AJAX request to do it. Now I try to use the method "POST" to proceed with my functionality, i put it in my route, my view and my AJAX request.
This is my route
Route::POST('prospect/emails/save','ProspectEmailsController#store')->name('prospectEmails.store');
This is my view
<form id="emailModalProspect" method="POST">
#csrf
<input hidden name="prospect_id" id="prospect_id" type="text">
<div class="form-group mb-3">
<label class="form-control-label" for="prospect-email-name">{{ __('Nome') }}</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-email-83"></i></span>
</div>
<input class="form-control" id="prospect-email-name" name="name" placeholder="Put the email owner" type="text">
</div>
</div>
<div class="form-group mb-3">
<label class="form-control-label" for="prospect-email-email">{{ __('Email') }}</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-email-83"></i></span>
</div>
<input class="form-control" id="prospect-email-email" name="email" placeholder="Put the email" type="email">
</div>
</div>
<div class="text-center">
<button type="submit" id="save-email" class="btn btn-primary my-4 store-email">Store</button>
</div>
</form>
This is my controller
public function store(Request $request){
$prospect_emails = ProspectEmails::where(['prospect_id'=>$request->prospect_id])->get();
ProspectEmails::create(array_merge($request->all(), ['company_id' => Auth::User()->company_id], ['prospect_id'=>$request->prospect_id], ['tag'=>false]));
$p_email = ProspectEmails::where('prospect_id',$request->prospect_id)->get()->count();
$update_at = Carbon\Carbon::now();
Prospect::where('id', $request->prospect_id)->update(['updated_at' => $update_at, 'prospect_emails'=> $p_email]);
return response()->json();
}
And this is my Ajax request
$('.open-email-modal').on('click', function(e) {
e.preventDefault();
let p = JSON.parse($(this).attr('data-entity')); //the id of the prospect that i want to insert the emails
let modal = $('#emailModal');
let form = $('#emailModalProspect');
$('#prospect-email-name').val(p.name);
$('#prospect_id').val(p.id).change();
form.submit(function(e){
if(p.id) {
$.ajax({
url: "{{route('prospectEmails.store')}}",
type: "POST",
data : form.serialize() ,
dataType: "json",
success:function(data) {
if(data){
console.log(data); // here, in console, show a empty array like it "[]".
}
}
});
}
});
modal.modal({show : true});
});
Now always I'm trying to register a new email, show this message:
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
In console show this error.
POST http://127.0.0.1:8000/prospect 405 (Method Not Allowed)
The strange that store the data in my database, but show it. What happens to show this message?
I change to PUT method. At first it works, but show the token and the things that i store in URL. It's not what i want.
Your route is defined as prospect/emails/save, but you're POSTing to prospect, which apparently doesn't exist as a POST route.
Post to the correct route and it should work fine. Adding an action to your <form> should do the trick:
<form action="{{ route('prospectEmails.store') }}" ...>
please use
Route::any('prospect/emails/save','ProspectEmailsController#store')->name('prospectEmails.store');
or
Route::post('prospect/emails/save','ProspectEmailsController#store')->name('prospectEmails.store');
instead of
Route::POST('prospect/emails/save','ProspectEmailsController#store')->name('prospectEmails.store')
please use routes like this
Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);
Related
I'm new to Laravel 6, and I'm trying to make a edit profile feature but I'm stuck with the error:
The GET method is not supported for this route. Supported methods: POST
To be honest, I am not sure why i get this error. I have cross checked everything.
ProfileController
update function
public function update(Request $request, $id)
{
$profile->nickname = $request->input('nickname');
$profile->name = $request->input('name');
$profile->birthday = $request->input('birthday');
$profile->save(); //persist the data
return redirect()->route('profile.index')->with('info','Profile got saved');
}
My route file:
Route::get('/profile', 'ProfileController#index')->name('profile');
Route::put('/profile/edit/{profile}','ProfileController#update')->name('profile.update');
edit.blade.php
<form action="{{route('profile.update')}}" method="POST">
#csrf
#method('PUT')
<div class="form-group row">
<label for="nickname" class="col-md-4 col-form-label text-md-right">{{ __('Brugernavn') }}</label>
<div class="col-md-6">
<input id="nickname" type="text" class="form-control #error('nickname') is-invalid #enderror" name="nickname" value="{{ Auth::user()->nickname }}">
</div>
</div>
<!-- Submit -->
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-secondary">
Gem
</button>
</div>
</div>
</form>
As a usal Laravel offers using 5 methods.
GET/contacts, mapped to the index() method and shows contacts list,
GET /contacts/create, mapped to the create() method and shows create form,
POST /contacts, mapped to the store() method and handle create form request,
GET /contacts/{contact}, mapped to the show() method and shows single item,
GET /contacts/{contact}/edit, mapped to the edit() method and shows update form,
PUT/PATCH /contacts/{contact}, mapped to the update() method and handle update form request,
DELETE /contacts/{contact}, mapped to the destroy() method and handle delete form request.
You have to change your route.php file
Route::put('/profile/edit/{profile}','ProfileController#update')->name('profile.update');
And in your form, change action
<form action="{{ route('profile.update', Auth::user()->id) }}" method="POST">
...
</form>
For more: https://www.techiediaries.com/php-laravel-crud-mysql-tutorial/
You are getting the error because your route expects post and you are using get method
Route::get('/profile/edit','ProfileController#edit')->name('profile.edit');
Route::put('/profile/','ProfileController#update')->name('profile.update');
public function edit() {
return view (edit);
}
public function update() {
//things to update
}
in your edit.blade.php file remove
#method('PUT')
then your method will be post only
You can set route method any
Change Route::post('/profile/edit','ProfileController#update')->name('profile.update');
to
Route::any('/profile/edit','ProfileController#update')->name('profile.update'); change
Thanks
When the user accesses a certain brand page, I pull the information associated with that brand. Then the user has the chance to submit an application for this brand.
When the user submits the form, I want the form to post to /apply/brand/{brand_id} because I want to store this application in my application table with the brand_id as one of the fields (the other fields in this table comes from the fields in my form, but the brand_id will be an URL parameter)
The problem is that when I submit the form, the form posts to /apply/brand/undefined and the submission does not work correctly. I do not reach the ApplicationController#apply_store method.
EDIT:
To debug my problem, I printed out the {{$brand -> id }} right before the element and it printed out fine. However, when the form submits, it goes to /apply/brand/undefined instead of /apply/brand/{{$brand -> id }}. The $brand variable somehow becomes undefined inside of my form.
EDIT:
I hardcoded the from to submit to /apply/brand/43. When I press submit, the url shows up as /apply/brand/43 at first but then quickly changes to /apply/brand/undefined before redirecting me to my default page.
Controller Method for Accessing a Brand Page
public function brandProfile(){
$brand = Brand::where('user_id', Auth::user()->id)->first();
$industry = Industry::where('status', 1)->get();
return view('new-design.pages.profile_brand')
->withData($brand)
->withIndustry($industry);
}
Brand Application Form
<form id="application_form" method="post" action="/apply/brand/{{ $data -> id }}" enctype="multipart/form-data">
{{ csrf_field() }}
<ul>
<div class="col-md-6">
<li>
<label>First Name</label>
<input type="text" class="form-control" name="firstname" placeholder="First Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Last Name</label>
<input type="text" class="form-control" name="lastname" placeholder="Last Name"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Email</label>
<input type="email" class="form-control" name="email" placeholder="Email"/>
</li>
</div>
<div class="col-md-6">
<li>
<label>Instagram Handle</label>
<input type="text" class="form-control" name="instagram" placeholder="Instagram Handle"/>
</li>
</div>
<li>
<label>Cover Letter</label>
<p>Please write your message in the space below, or attach a file (-list of file types accepted-)</p>
<textarea cols="30" rows="50" name="message" class="textarea"></textarea>
</li>
<li>
<div class="upload-cover-letter">
<i class="fa fa-paperclip" style="cursor:pointer;font-size:20px;"></i>
<input type="file" name="file" id="myFileDocument" class="inputfile inputfile-1"/>
<label for="myFileDocument" id="myFileDoc"><span>Choose File</span></label>
<span style="font-size: 12px">No File Chosen</span>
<span class='hidden_text' style="font-size: 12px">Upload File (Max 2MB)</span>
</div>
<input type="hidden" id="myFileName" name="file_name" />
</li>
</ul>
<div class="btn-center">
<button type="button" class="btn btn-gradient waves-effect" id="create_campaign">Apply Now</button>
</div>
</form>
Route in web.php
Route::post('/apply/brand/{brand_id}', 'ApplicationController#apply_store');
Store application in database
public function apply_store(Request $request)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $request->get('brand_id'),
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// TODO: add helper message to confirm application did return
return redirect('/apply');
}
In your controoler metohd apply_store, you need to put the variable that will receive the variable sended by url parameter.
public function apply_store(Request $request, $brand_id){}
I typically work with compact or with to send the param to the blade view. So:
return view('new-design.pages.profile_brand', compact('brand'));
or without compact:
return view('new-design.pages.profile_brand')->with('brand', $brand)
I haven't seen the withVar that you are attempting above (doesn't mean it doesn't exist though). Try with compact and dump $brand on the view to make sure its coming through with data (not undefined). If that dumps successfully, but still fails, you may want to try adding the variable outside the quotes or totally within the blade {{}} in the form like:
<form id="application_form" method="post" action={{ "/apply/brand/".$brand-> id }} enctype="multipart/form-data">
Not sure about how the action is getting though like you have in your code above, though - you might wish to use the url() method:
<form id="application_form" method="post" action={{ url("/apply/brand/".$brand-> id) }} enctype="multipart/form-data">
change your method like this
public function apply_store(Request $request,$brand_id)
{
$application = new Application([
'influencer_id' => Auth::id(),
'brand_id' => $rbrand_id,
'message' => $request->get('message'),
'status' => 'applied'
]);
$application->save();
// Ngentod lah kalian semua, anjeng
return redirect('/apply');
}
I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.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="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.
I create form in Laravel:
<form action="/redeem" method="get" class="sidebar-form">
<div class="input-group">
<input type="text" name="key" class="form-control" placeholder="ENTER VOUCHER CODE">
<span class="input-group-btn">
<button type="submit" name="search" id="search-btn" class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</form>
and now when I try to submit that I get:
http://localhost:8888/redeem?key=NBtGJ5pZls&search=
but I need to get just:
http://localhost:8888/redeem/NBtGJ5pZls
also in route I have:
Route::get('/redeem/{key}', 'OrdersController#redeem');
How to get redirected to redeem/NBtGJ5pZls with my form?
Change your route to:
Route::post('/redeem', 'OrdersController#redeem');
And then get key in controller:
public function redeem(Request $request)
{
$key = $request->key;
And finally, change your form:
<form action="/redeem" method="post" class="sidebar-form">
{{ csrf_field() }}
You've got 2 options:
The first is let your frontend code be the way it is, update the route, and work with the GET parameter.
The second one is using some javascript to rewrite the URL you want to access.
For example this (it's using jQuery):
$('#search-btn').click(function() {
var key = $('input[name=key]').val();
window.location.href = '/redeem/' + key;
});
I prefer the first one, because javascript can be modified by the end-user.
I'm currently developing a system with Laravel framework. Though, I'm not very familiar with MVC architecture yet.
When I'm developing the system, I come across a problem which relates with this bootstrap modal that has a form in it. I'd like to put functions in it so that it could be submitted to the database.
I have followed several tutorials, but didn't come up with a solution because they're all using pages instead of modals.
So, here is the HTML of the modal:
<div class="modal hide fade" id="linkSettings">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Add New Link</h3>
</div>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
Save changes
</div>
</div>
Here is the Javascript of the above modal:
$('.btn-settingLink').click(function(e){
e.preventDefault();
$('#linkSettings').modal('show');
});
Now, how do I put the function in the Controller so that whenever a user presses Save Changes button, it will store the value in <textarea> into the database? Is there anything to do with the Javascript code? and Do I need to use {{Form::open('main/addLink','POST')}} at the form to pass its values to the controller and model?
Basically, all I ever wanted was to have the CRUD functions by using modal.
First you need to create a form with a route....
<form method="post" action="{{URL::to('Link/addlink')}}>
Or like you showed above, with your Blade {{Form}} ...either way
Then your textarea needs an id and name
<textarea id="mytext" name="mytext"></textarea>
So your HTML becomes...
<form method="post" action="{{URL::to('Link/addlink')}}>
<div class="modal-body">
<div class="control-group">
<label class="control-label" for="focusedInput">Add A Link:</label>
<div class="controls">
<textarea id="mytext" name="mytext" class="autogrow"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
Close
<input type="submit" id="submit" name="submit" class="btn btn-primary">Save changes</input>
</div>
</form>
Then in your Link controller...or wherever you're actually sending this form..no idea what your controllers are named :)
public function addlink(){
$input = Input::all();
//whatever validation you wanna do, with error handling etc...not gonna provide that, thats up to you
$yourmodel = New Model;
$yourmodel->text = $input['mytext'];
$yourmodel->save();
Return Redirect::back();
}
EDIT (for Ajax)
Add this script at the bottom of your page...
<script>
$(document).ready(function(){
$('input#submit').click(function(e){
e.preventDefault();
var text = $('#mytext').val();
var url = 'your url' //we were using Link/addlink in the other example
$.ajax({
type: "POST",
url: url,
data: { mytext: text },
success: function(){
//Probably add the code to close your modal box here if successful
$('#linkSettings').hide();
},
});
});
});
</script>
PS Completely untested....you will need some tweaking, plus the fact that your controller has the Redirect will probably make it not work since this will just be expecting an echoed Json string
But these are the nuts and bolts, and the foundation is there for you to continue on your own I would think...