POST method is not supported for this route - laravel

First, I've checked other question topic, but couldn't find the solution.
when I try to post my form. I am getting this error.
The POST method is not supported for this route. Supported methods:
GET, HEAD.
Form:
<div class="card-body">
<form action="{{route('profile.update', ['id' => $id])}}" method="post">
#csrf
#put
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location" value="{{$info->location}}">
</div>
<div class="form-group">
<label for="about">About</label>
<textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
</div>
<div class="form-control">
<p class="text-center">
<button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
</p>
</div>
</form>
</div>
Routes:
Route::group(["middleware" => "auth"], function(){
route::get("/profile/edit", [
"uses" => "ProfilesController#edit",
"as" => "profile.edit"
]);
route::get("/profile/{slug}", [
"uses" => "ProfilesController#index",
"as" => "profile"
]);
route::put("/profile/update/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
});
in controller:
public function update(Request $request, $id)
{
dd($request->all());
}

From your question, i can understand that you're trying to update a profile using POST method or may be PUT method earlier. Since, the resource you are editing is unique, you're not passing any parameters for the controller to find that single resource so as to update it.
therefore modify your your route like
route::put("/profile/update/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
And your form like
<form action="{{route('profile.update', ['id' => $id])}}" method="post">
#csrf
#method('put')
You'll need to pass the ID of the profile you want to update as parameter
then at the controller
public function update(Request $request, $id){
//edit the profile with id = $id
}

You have an error in your form definition
<form class="{{route('profile.update', ['id' => $id])}}" method="post">
should be
<form action="{{route('profile.update', ['id' => $id])}}" method="post">

Since you made a form for PUT request, you have to change
route::post("/profile/update/profile", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
to this
route::put("/profile/update/profile", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);

Here is the correction in your provided example.
In form route('profile.update', ['id' => {here you have to place id of record which you want to update}]).
View File
$info->id])}}" method="post">
<div class="form-group">
<label for="location">Location</label>
<input class="form-control" type="text" name="location" value="{{$info->location}}">
</div>
<div class="form-group">
<label for="about">About</label>
<textarea name="about" id="about" rows="10" cols="50" class="form-control">{{$info->about}}</textarea>
</div>
<div class="form-control">
<p class="text-center">
<button class="btn btn-primary btn-md" type="submit">Update Your Info</button>
</p>
</div>
</form>
</div>
In Route
Route::group(["middleware" => "auth"], function(){
route::get("/profile/{slug}", [
"uses" => "ProfilesController#index",
"as" => "profile"
]);
route::get("/profile/edit/profile", [
"uses" => "ProfilesController#edit",
"as" => "profile.edit"
]);
route::post("/profile/update/profile/{id}", [
"uses" => "ProfilesController#update",
"as" => "profile.update"
]);
});
In Controller
public function update(Request $request, $id)
{
dd($id, $request->all());
}

Related

How can I solve 404 errors in Laravel 7?

I'm making a registration form using Laravel 7, my form has a "preview" step where users first check the details and either submit the details as they are or edit. The actual submission of the details happens in the blade file named preview.blade.php and this is where I have placed the form action for posting the data. This part works well, the edit part is the one with the problem as it gives 404 error. Please help.
In my register.blade.php:
<form method="post" action="{{ url('/preview-details') }}" id="regForm">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my preview.blade.php:
<div>
<a href="{{route('edit_preview')}}">
<button type="button" class="btn btn-primary btn-sm"
style="float:right;"><i class="fas fa-edit"> </i>Edit</button>
</a>
</div>
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my edit_preview.php (this one shows 404 error):
<form method="post" action="{{ url('/client-registration') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="region">Your Region</label><span class="text-danger">*</span>
<input type="text" class="form-control" name="region" id="region" placeholder="e.g Westlands" required>
</div>
<label for="start_date">Date</label><span class="required">*</span>
<input type="date" class="form-control" id="start_date" name="start_date"
value="{{ old('start_date') }}" required>
<!--Other fields here-->
</form>
In my Routes file:
Route::get('/client-registration', 'Auth\Client\RegisterController#create')->name('client-registration');
Route::post('/client-registration', 'Auth\Client\RegisterController#store');
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Route::post('/preview-details-existing', 'Auth\Client\PreviewDetailsExistingClientController#confirmation')->name('preview-existing');
Route::post('/edit_preview', 'Auth\Client\EditRegisterDetailsController#editDetails')->name('edit_preview');
In my Preview Controller (It works well):
class PreviewRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
}
In my edit details controller:
class EditRegisterDetailsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
// Validating the User
public function editDetails(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data = $request->all();
return view('auth.client.edit_preview', compact('categories', 'data'));
}
}

Change image name and save to DB Laravel

Hi i can not store image name to database in Laravel project.
How to solve this?
Here is codes of controller
class TarifController extends Controller
{
public function store(Request $request)
{
$request->validate([
'title_uz' => 'required',
'desc_uz' => 'required',
'full_desc_uz' => 'required',
'company_id' => 'required',
'order' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,svg|max:2048',
]);
$image1 = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image1);
Tarif::create($request->all());
return redirect()->route('tarifs.index')
->with('success','Yangi tarif muvoffaqiyatli qo`shildi.');
}
}
and here is codes from view
<form role="form" action="{{ route('tarifs.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div> .. another fields .. </div>
<div class="col-5">
<label for="image">Surat</label>
<input type="file" class="form-control" name="image" id="image" required>
</div>
<div> .. another fields .. </div>
<div class="card-footer">
<a class="btn btn-info" href="{{ route('tarifs.index') }}">Qaytish</a>
<button type="submit" class="btn btn-success">Saqlash</button>
</div>
</form>
It saves image to public/images folder but didn't saves filename or path to DB. The field name is 'image' on database.
If you need to merge new values into a request object, the following code would have done the trick :
$request->merge(['image' => 'avatar.png']);
Or, you can change your code like this :
$image1 = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image1);
$input = $request->all();
$input['image'] = $image1;
Tarif::create($input);

How to get session mobile in laravel

I want to after registered a user name, age, mobile and ... get the session of mobile because in next page, I want to get mobile in input hidden.
Attention: I did not do session at all.
I think it's like this:
RegisterController.php
public function register(Request $request, User $user)
{
$code = rand(10000,99999);
session->get('mobile')
$user = \App\User::create([
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'gender' => $request->gender,
'mobile' => $request->mobile,
'code' => $code,
.
.
.
return redirect()->route('code')->with('mobile', $request->mobile);
}
It redirect to this page.
Code
code.blade.php
<form action="{{ route('send') }}" method="post">
{{ csrf_field() }}
<input type="hidden" class="form-control" value="{{ session->mobile }}" name="mobile" id="mobile">
<div class="form-group">
<label for="code">کد</label>
<input type="text" class="form-control" name="code" id="code">
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger" id="btn-ok">OK</button>
</div>
</form>
use Illuminate\Support\Facades\Session;
For saving in session use
Session::put('mobile', $request->mobile);
then retrieve it using
Session::get('mobile');

Laravel Form validation redirects back to home page upon form errors instead of staying on same page

I have a contact form that when submitted, is successfully going to the DB. The issue is, when I check for validation on my webpage, the errors appear properly using Larvael $error validation, the problem is that my webpage always redirects back to home when errors show up instead of the page remaining still and showing the errors. I have to keep scrolling down to where my contact form is to see the errors; this will be annoying for my future users. How do I get the page to remain where it is if there are errors? NOTE: My page redirects correctly when the form is valid and submitted, this is not an issue. NOTE-2: I have created a single page webpage that the nav-links take you to, there are no redirects. Instead, it is one HTML page.
Web.php
Route::get('/', 'HomeController#index')->name('home');
Route::post('/contact/submit', 'MessagesController#submit');
MessagesController.php
namespace App\Http\Controllers;
use App\Message;
use Illuminate\Http\Request;
class MessagesController extends Controller
{
public function submit(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
Message::create($validatedData);
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
contact.blade.php
{{--CONTACT FORM--}}
<section id="contact">
<div class="container-fluid padding">
<div class="row text-center padding">
<div class="col-12">
<h2 class="lead display-3">Contact Us</h2>
<hr class="my-4">
<form action="/contact/submit" method="POST">
#csrf
<div class="field">
<label for="name" class="label">Name</label>
<div class="control">
<input type="text" class="input {{$errors->has('name') ? 'is-danger' : 'is-success'}}"
name="name" placeholder="Project Title" value="{{old('name')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Email</label>
<div class="control">
<input type="text" class="input {{$errors->has('email') ? 'is-danger' : 'is-success'}}"
name="email" placeholder="Project Title" value="{{old('email')}}">
</div>
</div>
<div class="field">
<label for="name" class="label">Phone Number</label>
<div class="control">
<input type="text"
class="input {{$errors->has('phonenumber') ? 'is-danger' : 'is-success'}}"
name="phonenumber" placeholder="Project Title" value="{{old('phonenumber')}}">
</div>
</div>
<div class="field">
<label for="message" class="label">Message</label>
<div class="control">
<textarea name="message"
class="textarea {{$errors->has('message') ? 'is-danger' : 'is-success'}}"
placeholder="Project description">{{old('message')}}</textarea>
</div>
</div>
<div class="field">
<div class="control">
<button type="submit" class="button is-link">Create Project</button>
</div>
</div>
<!--Errors variable used from form validation -->
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
</form>
</div>
</div>
</div>
</section>
You need to create a manual validator so that you have control over the redirect if the validation fails (which I assume is what you are having issues with).
public function submit(Request $request)
{
$validator = Validator::make($request->all(),[
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return redirect(url()->previous() .'#contact')
->withErrors($validator)
->withInput();
}
Message::create($request->all());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
First, move the errors to the top of the form so you can see them.
<form action="/contact/submit" method="POST">
#csrf
#if($errors->any())
<div class="notification is-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
A better way of handling validation is to separate it using a form request.
php artisan make:request SendMessageRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SendMessageRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
];
}
}
If validation fails, a redirect response will be automatically generated to send the user back to their previous location.
Now update your controller.
use App\Http\Requests\SendMessageRequest;
use App\Message;
class MessagesController extends Controller
{
public function submit(SendMessageRequest $request)
{
Message::create($request->validated());
return redirect('/')->with('success', 'Your message has been
successfully sent. We will reach out to you soon');
}
}
You can leave the validation in your controller using the Validator and back() redirection, but the first is the better way.
public function submit(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|max:255',
'phonenumber' => 'required|min:10|max:10',
'message' => 'required|min:5',
]);
if ($validator->fails()) {
return back()->withInput()->withErrors($validator);
}
Message::create($request->all());
return redirect('/')->with('success,' 'Your message has been
successfully sent. We will reach out to you soon');
}

Submitting form input after logging in with laravel

I have the view:
<form class="text-center" action="{{route('PostComment')}}" method="POST">
<div class="form-group">
<textarea class="form-control" name="Comment" id="exampleTextarea" placeholder="Write down your thought here..." rows="4"></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<input type="hidden" value="{{ Session::token() }}" name="_token">
</form>
And also the route:
Route::post('/Comment', [
'uses' => 'CommentController#Comment',
'as' => 'PostComment',
'middleware' => 'auth'
]);
And the controller(not so important):
public function Comment(Request $request)
{
$this->validate($request, [
'Comment' => 'required|min:10|max:100',
]); // validation of comment
$NewComment = new Comment();
$NewComment->user_id = Auth::user()->id;
$NewComment->text = $request['Comment'];
$NewComment->save();
return redirect()->route('Debate');
}
My question is that when you submit the form data and you are not logged in, you have to log in but the form isn't submitted?(edited:using laravel auth)
How to make this thing work, you fill the textarea, you forgot to log in, you log in and the form is submited?

Resources