MethodNotAllowedHttpException in RouteCollection.php line 218: - laravel

I'm tryng to built a controller for a newsletter, her is my code:
Controller
public function postNews(Request $request, $user) {
$this->validate($request, [ 'email' => 'required | email' ]);
$user = User::findOrFail($id);
$data = array(
'email' => $request->email);
$token = $request->input('g-recaptcha-response');
if (strlen($token) > 0 ) {
Mail::send('emails.newsletter', $data, function( $message ) use ($data) {
$message->from($data['email']);
$message->to($user->email, $user->name)->subject('A-Studio News Letter');
//$message->subject($data['subject']);
});
Session::flash('success', 'Grazie per esserti iscritto alla nostra news letter!');
return view('blog.posts')->withPosts($posts);
}else {
return view('pages.nobot');
}
}
Route
Route::post('posts/{user}', ['uses' => 'BlogController#postNews', 'as' => 'blog.posts']);
Response
MethodNotAllowedHttpException in RouteCollection.php line 218:
Any idea?
Thank you.

<form method="post" action="/posts">
<input name="email" type="email">
<button type="submit">subscribe</button>
</form>
Route::post('/posts', 'YourController#userSubscribe');
public function userSubscribe(Request $request){
$data = $request->input('email');
//Validate $data if necessary and save in the DB
}
This should work.

You should remove the,
Route::post('posts/{user}', '....');
use as,
Route::post('posts', '....');
And also use the controller function with $user variable in the parameters.
I hope this will help you.

You should make POST request
<form action="posts/{{user}}" method="POST">

Related

Laravel - How to pass parameter from controller to route and use it in another controller?

I have configured a resource route as below
Route::resource('users', UserController::class);
When a user posts data, it will call the store method in the controller where it will add the data and set a message for success/failure.
public function store(Request $request)
{
// return $request;
$request->validate(
[
"firstName" => 'required',
"lastName" => 'required',
"phoneNo" => 'required',
"email" => 'email:rfc,dns'
]
);
$date = date(now());
$data = [
'firstName' => $request->firstName,
'lastName' => $request->lastName,
'phoneNo' => $request->phoneNo,
'email' => $request->email,
'designation' => $request->designation,
'status' => $request->status,
'createdAt' => $date,
'updatedAt' => $date,
];
$user = Firebase::insertData($data, static::$collection);
if ($user->id() != null) {
$message = "User Created Successfully";
} else {
$message = "Something went wrong. Please contact System Admin with error code USR001";
}
return redirect()->route('users.index', ['message' => $message]);
}
This will redirect to the index method of the same controller. How can I use the $message parameter in the index method and send it to the view? My index method is below
public function index()
{
$userCollection = app('firebase.firestore')->database()->collection('users');
$userData = $userCollection->documents();
$response = [];
$app = app();
foreach ($userData as $data) {
$user = $app->make('stdClass');
$user->firstName = $data["firstName"];
$user->lastName = $data["lastName"];
$user->phoneNo = $data["phoneNo"];
$user->email = $data["email"];
$user->designation = $data["designation"];
$user->status = $data["status"];
$user->createdAt = $data["createdAt"];
$user->updatedAt = $data["updatedAt"];
array_push($response, $user);
}
return view('pages.user.list-user', ['response' => $response]);
}
You can directly pass the message as a flash message using the with() method with the redirect method.
Edit your redirect code as:
return redirect()->route('users.index')->with('message', $message]);
and add the below code in your pages.user.list-user blade file:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
Visit https://laravel.com/docs/8.x/redirects#redirecting-with-flashed-session-data for more info on redirects with a flash message.
Replace your redirect code :
return redirect()->route('users.index', ['message' => $message]);
with
return view('pages.user.list-user', ['message' => $message]);
(1) First of all, pass the message in the parameter of index function:
public function index($message)
{
...
}
(2) This is okay, you wrote correctly:
return redirect()->route('users.index', ['message' => $message]);
(3) Now just access the message in the view (blade) and print it:
{{ $message }}
You can also store message in $response array and simply pass the $response to the desired view:
$response['message'] = $message;
You can have the index method like if the parameter used in the controller.
public function index(Request $request)
{
// Your code
$message = $request['message'];
}
If you want to access the message in view use
return redirect()->route('users.index')->with('message', $message]);
and access from the view using session('message') like in OMi Shah's answer

When I clicked add button, MethodNotAllowedHttpException is appeared

When I clicked on the add button, a MethodNotAllowedHttpException error appeared. What is wrong in my code?
I have read all of the version of correction but nothing helped me.
This is my getdata() function inside AjaxdataController:
function getdata()
{
$users=User::select('id','name','lastname','email','created_at');
return DataTables::of($users)
->addColumn('action', function ($user) {
return '<i class="glyphicon glyphicon-edit"></i> Edit';
})
->make(true);
}
function postdata (Request $request)
{
$validation=Validator::make($request-> all(),[
'name' =>'required',
'lastname' => 'required',
'email' =>'required',
'password' =>'required'
]);
$error_array= array();
$success_output='';
if ($validation->fails())
{
foreach ($validation->messages()->getMessages as $field_name => $messages) {
$error_array[]=$messages;
}
}
else
{
if ($request->get('button_action')=="insert")
{
$user =new User([
'name' =>$request->get('name'),
'lastname'=>$request->get('lastname'),
'email'=>$request->get('email'),
'password'=>$request->get('password')
]);
$user->save();
$success_output= '<div class="alert alert-success"> Data Inserted </div>';
}
}
$output=array(
'error' =>$error_array,
'success'=>$success_output
);
echo json_encode($output);
}
I assume that you defined the route as a GET request but the form is probably sending a POST request. Change your route definition.
// Change this
Route::get('/foo', 'FooController#bar')
// To this
Route::post('/foo', 'FooController#bar')

ErrorException in helpers.php line 533:

I'm making a contact form with laravel 5.4 and I want to get an email when someone sends the contact form. I'm using Mailtrap to receive emails.
The problem I'm getting is that I get this error when I submit the form.
ErrorException in helpers.php line 533:
htmlspecialchars() expects parameter 1 to be string, object given (View: C:\xampp\htdocs\website\app\Modules\Templates\Resources\Views\emails\contact.blade.php)
My contact function
public function contact()
{
$data = Input::all();
$rules = array(
'name' => '',
'email' => '',
'message' => '',
);
$validator = Validator::make($data, $rules);
if($validator->passes())
{
Mail::send('templates::emails.contact', $data, function($message){
$message->from(Input::get('email'), Input::get('name'));
$message->to('info#site.com', 'Info')->subject('Testing contact form');
});
Session::flash('success', 'Your message has been sent successfully.');
return back();
}else{
return back()->withErrors($validator);
}
}
and my contact.blade.php that is the information that gets sent to me
<h1>We been contacted by.... </h1>
{{ $name }}<br />
{{ $email }}<br />
{{ $subject }}<br />
{{ $message }}<br />
You're passing the $data which holds the array of input. You need to access them like shown below.
Change the data being passed to
Mail::send('templates::emails.contact', compact('data'), function($message)
Change your view code to
{{ $data['name'] }}<br/>
{{ $data['email'] }}<br/>
{{ $data['message'] }}<br/>
You're also trying to access subject in the view when isn't available in the input.
you need to Add $subject in ur cantact function or remove it from cantact.blade.php, try this code :
public function contact()
{
$cdata = Input::all();
$crules = array(
'name' => '',
'email' => '',
'subject' => '',
'message' => '',
);
$validator = Validator::make($cdata, $crules);
if($validator->passes())
{
Mail::send('templates::emails.contact', $cdata, function($message){
$message->from(Input::get('email'), Input::get('name'));
$message->to('info#site.com', 'Info')->subject('Testing contact form');
});
Session::flash('success', 'Your message has been sent successfully.');
return back();
}else{
return back()->withErrors($validator);
}
}
and some times u got an error because ur variables have the same name of stored variables ( like data,timer,for ... etc)

Controller didn't get more arguments laravel

I'm trying to send two arguments and one request to controller with post request. This is the code where I send the arguments:
<form class="form-horizontal" name="form1" method="post" action="{{ route('shipment_view', $uniqueid, $category_name) }}" role="form" enctype="multipart/form-data">
And this is the controller where I'm sending the arguments:
public function storeShipment(Request $request, $number, $category_name){
$category = Category::where('category_name', $category_name)->first();
$user = Auth::user();
$item = new Item([
'id' => $user->id,
'category_id' => $category->id,
'unq' => $number,
'fullname' => $request->input('name'),
]);
$item->save();
}
But when I open the view it gives me error
ErrorException in NewShipmentController.php line 53:
Missing argument 3 for App\Http\Controllers\NewShipmentController::storeShipment()
Update:
My route function:
Route::post('/ship/preview/{number}',[
'uses' => 'Controllerr#storeShipment',
'as' => 'shipment_view'
]);
Any ideas?
replace your route function with the below one
Route::post('/ship/preview/{number}/{category_name}',[
'uses' => 'Controllerr#storeShipment',
'as' => 'shipment_view'
]);
Hope this solves your problem.
You can get the all the parameters through request it self But before this how you are defining the route
public function storeShipment(Request $request){
$number = $request->number;
$category_name = $request->number
}

Failed to save information to database

I'm quite new to laravel, created all that is needed but i can't edit or add new entries into the database. However i can successfully delete. what could be the problem not making the application write to the database?
This is my store function
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
// redirect
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
return Redirect::to('user');
}
Route
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('auth.login');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::resource('user', 'UserController');
Route::resource('role', 'RoleController');
User Controller
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
// redirect
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
return Redirect::to('user');
}
Your routes
<?php
Route::get('/', function () {
return view('auth.login');
});
Route::auth();
Route::get('/home', 'HomeController#index');
Route::post('/user/store', 'UserController#store');
Your form
<form id="form-add-user" role="form" method="POST" action="{{ url('/user/store') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
...
</form>
Change your store method with below given and let me know which message will print?
public function store(Request $request)
{
//validate data
$validation=$this->validate($request, [
'username' => 'required|max:50',
'role_id' => 'required|max:50',
'email' => 'required|email|max:50',
]);
$user = new User;
$user->username = $request->username;
$user->role_id = $request->role_id;
$user->email = $request->email;
$user->save();
//Success redirect
if($user){
Session::flash('message', 'Successfully added the record!');
Session::flash('alert-type', 'success');
}
//Failed redirect
else {
Session::flash('message', 'Something went wrong!');
Session::flash('alert-type', 'success');
}
return Redirect::to('user');
}
For get the ride of basic CRUD with laravel example.

Resources