MethodNotAllowedHttpException in RouteCollection.php Laravel - php

I have problem to save name and email from user1 in table user1s that I have made .
When I enter them in textareas using html form in Laravel with route::post and function store it is not working. When I enter text and hit the button Register it outputs the following error:
MethodNotAllowedHttpException in RouteCollection.php line
You will see that I use the HTML form and that I have tried to add <input ....> into my form.
Here are my files:
route.php
<?php
Route::get('/','PageController#home');
Route::post('/','User1Controller#store');
Route::get('about','PageController#about');
welcome.blade.php
I'm not sure about the action.
After putting user1 inf into table, it should be redirected to a "Thank you" page (I have a thankyou.blade.php ) , maybe that is the problem
<form method="POST" action="">
<input name="_token" type="hidden" value="{{ csrf_token() }}"/>
<ul class="list-group" >
<li >
NAme
<div class="form-group" title="email" >
<textarea name="name" class="form-control" >
</textarea>
</div>
</li >
<li>Email
<div class="form-group" >
<textarea name="email" class="form-control" >
</textarea>
</div>
</li>
<li >
<div class="form-group" >
<button class="btn btn-primary">Register</button>
</div>
</li>
</ul>
</form>
migration for user1
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotesTable extends Migration
{
public function up()
{
Schema::create('notes', function (Blueprint $table) {
$table->increments('id');
$table->integer('card_id')->unsigned();
$table->text('body');
$table->timestamps();
});
}
public function down()
{
Schema::drop('notes');
}
}
user1controller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class User1Controller extends Controller
{
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return view('thankyou');
}
}
pagecontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User1;
class PageController extends Controller
{
public function home()
{
$user1s= User1::all();
return view('welcome',compact('user1s'));
}
public function about()
{
return view('pages.about');
}
}

Your form is basically a registration form. I would recommend using a more meaningful name for the end point. The post route can be something like,
Route::post('/register','User1Controller#store');
Now the form action can be,
action="/register"

I corrected the typo.Thanks!
I have also changed this
Route::post('/','User1Controller#store');
and action=" " .
It works ,the only thing right now that is not good is that I should redirect to a page "Thank you" not go to anther view on the exact same page.
Because It makes a mess in the database when I reload the home page.
I'll try that and tell if it works.
Thank you people for the help! :)

Things solved,this works. I will add the code that i have added so the other can find it!
Firs of all : I haven't figured why ,but action="dir1/dir3" for me didn't work!
Here are the added things!
routes.php
Route::get('thankyou','PageController#thankyou');
***PageController.php***
public function thankyou()
{
return view('thankyou');
}
*****User1Controller.php*****
public function store(Request $request)
{
$user= new User1;
$user->name = $request->name;
$user->email = $request->email;
$user->save();
return redirect('/thankyou');
}

Related

Inserting data to database laravel

At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you

Can't get input data from form LARAVEL

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());
}

Laravel: Error trying to get unique users to create posts

Right so im trying to make a website where a registered user can create a post. The issue i am having rigt now is getting the post to be added to the the database. It should work but im getting an error.
The error:
Call to a member function posts() on null
The error points to my post controller class
<?php
use App\Post;
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class postController extends Controller
{
public function postCreatePost(Request $request){
$post = new Post();
$post->body = $request['body'];
$request->user()->posts($post); //points here
return redirect()->route('dashboard');
}
}
This is my post migration up method:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->text('body');
$table->integer('user_id');
});
}
Post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user(){
return $this->belongsTo['App\User'];
}
}
User model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function posts(){
return $this->hasMany('App\Post');
}
}
The section the user types in:
<section class="row new-post">
<div class="col-md-6 col-md-offset-3">
<form action="{{ route('postcreate') }}" method="post">
<div class="form-group">
<textarea class="form-control" name="body" rows="5" placeholder="your post"></textarea>
</div>
<button type="submit" class="btn btn-primary">Create post</button>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
</div>
</section>
The problem is that on your controller you do:
$request->user()->posts($post); //points here
You are considering that user() will always return something.
If your route isn't guarded by the auth middleware, $request->user() may return null if there's no authenticated user.
So you have two options: Or you add the auth middleware, or you put an if on your code:
if ($request->user()) {
$request->user()->posts($post);
}
However, this will fix the error but it won't create a post
public function postCreatePost(Request $request){
$post = new Post();
$post->body = $request['body'];
$request->user()->posts($post); // This call isn't valid.
return redirect()->route('dashboard');
}
The right way to do is:
public function postCreatePost(Request $request){
$request->user()->posts()->create([
'body' => $request->body
// Here I'm assumming that the only field is the `body`,
// but you may need other fields if they exists.
// the `user_id` field will be automatically filled.
];
return redirect()->route('dashboard');
}

How to store values from Form in Database using Laravel?

This is my code for SubscriptionController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SubscribersController extends Controller
{
//
//This method is to process the form
public function postSubmit() {
//we check if it's really an AJAX request
if(Request::ajax()) {
$validation = Validator::make(Input::all(), array(
//email field should be required, should be in an email//format, and should be unique
'email' => 'required|email|unique:subscribers,email'
)
);
if($validation->fails()) {
return $validation->errors()->first();
} else {
$create = Subscribers::create(array(
'email' => Input::get('email')
));
if($create){
return Redirect::to('/')
->with('success','You have been successfully subscribe to us.');
}else{
echo 'We could not save your address to oursystem, please try again later';
}
}
} else {
return Redirect::to('subscribers');
}
}
}
This is my code for Eloquent
class CreateSubscribersTable extends Migration
{
public function up()
{
Schema::table('subscribers', function (Blueprint $table) {
$table->increments('id');
$table->string('email,100)->default('');
$table->timestamps();
});
}.....
In the Route/web :
Route::post('/subscribers', 'SubscribersController');
This is the code for welcome.blade.php
<form action="/subscribers" method="post">
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</div>
</form>
The code dont insert in database and dont show any error in the console. I put in the postsubmit function echos if error appears and nothing.
I already search one tutorial and dont find.
I´m a noob in Laravel.
Routes should be Route::post('/subscribers','SubscribersController#postSubmit');
and add csrf_field() to form.
<form action="/subscribers" method="post">
{{csrf_field()}}
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</div>
</form>`
In your routes file, your route need to send to an action, not just the controller.
Route::post('/subscribers', 'SubscribersController');
should be this
Route::post('/subscribers', 'SubscribersController#postSubmit');
And add the csrf field to your html form:
<form action="/subscribers" method="post">
{{ csrf_field() }}
<input type="email" name="email" placeholder="Email Address" required>
<button type="button" class="btn btn-danger">Subscribe</button>
</form>
First of all, did you run :
php artisan migrate
Second, as Hollings stated above, your route :
Route::post('/subscribers', 'SubscribersController#postSubmit');
Third, top of your SubscribersController, add :
use Subscribers;
Aside of having CreateSubscribersTable extends Migration, you need to have another model class named Subscribers which extends Model. All class you might need to have :
SubscribersController extends Controller (you have it)
CreateSubscribersTable extends Migration (you have this too)
Subscribers extends Model/Eloquent (Do you have this?)
Sorry, that are all i can figure. Will try to check more to help.
Or if you really dying to figure out where the problem is, try to put echo something maybe "Test", within each of your if else.
1) Your migration content is wrong
public function up()
{
Schema::create('subscribers', function (Blueprint $table) { //** 'create', not 'table'
$table->increments('id');
$table->string('email,100)->default('');
$table->timestamps();
});
}
Delete your db contents and php artisan migrate
2) Your form is
<form action="/subscribers" method="post">
{{ csrf_field() }} //** add token
<input type="email" name="email" placeholder="Email Address" required>
<button type="submit" class="btn btn-danger">Subscribe</button> //** Button type : submit
</div>
</form>
Your route:
Route::post('/subscribers', 'SubscribersController#postSubmit');
Your controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Subscribers; //********* change this
class SubscribersController extends Controller
{
//This method is to process the form
public function postSubmit(Request $request) {
$validation = Validator::make($request->all(), [
//email field should be required, should be in an email format, and should be unique
'email' => 'required|email|unique:subscribers,email',
]);
if($validation->fails()) {
return $validation->errors()->first();
}
$create = Subscribers::create(array(
'email' => $request->email,
));
return Redirect::to('/')->with('success','You have been successfully subscribe to us.');
}
}
Add protected $table = 'subscribers'; to your Subscribers Model.
Why are you using if (Request::ajax()) ? You are not submitting form via AJAX.

Laravel 5.3 throw MethodNotAllowedHttpException on Store using restfull controller

I am trying to add a record to a database utilizing a resource controller, however, I'm getting MethodNotAllowedHttpException error. I'm using a pivot table. I have gone through several similar questions like a link! but none seem to answer me. This is my code:
Routes.php
Route::group(['prefix' => 'user'], function () {
Route::resource('categories', 'User\CategoriesController');
});
CategoriesController.php
<?php
namespace App\Http\Controllers\User;
use Session;
use Sentinel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Sections;
use App\Models\Categories;
use App\Models\Users;
use App\Models\CategorieUser;
class CategoriesController extends Controller
{
public function __construct()
{
$this->middleware('sentinel.auth');
}
public function index()
{
$categories = Categories::all();
return view('user.categories.index', ['categories' => $categories]);
}
public function create()
{
$sections = sections::all();
return view('user.categories.create', ['sections' => $sections]);
}
public function store(Request $request)
{
// records in table categories
$categories = new Categories();
$categories->name = $request->name;
$categories->sections_id = $request->sections_id;
$categories->save();
// records in pivot table users_categories
$user = Sentinel::getUser()->id;
$users_categories = new CategorieUser();
$users_categories->user_id = $user;
$users_categories->categorie_id = $categories->id;
$users_categories->save();
return redirect()->route('categories.index');
}
}
This is the form:
<form action="store" method="POST">
<div class="form-group">
<label for="section">Choose section:</label>
<select class="form-control" name="sections_id">
#foreach($sections as $section)
<option value="{{ $section->id }}">{{ $section->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="name">Category name:</label>
<input type="text" class="form-control" name="name" required>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-default">Submit</button>
</form>
This is model Categories.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Categories extends Model
{
public function sections()
{
return $this->belongsTo('App\Models\Sections');
}
public function users()
{
return $this->belongsToMany('App\Models\Users', 'categorie_user');
}
}
And this is model Users.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
public function categories()
{
return $this->belongsToMany('App\Models\Categories', 'categorie_user');
}
}
When I add this route under routes as above
Route::group(['prefix' => 'user'], function () {
Route::resource('categories', 'User\CategoriesController');
Route::post('categories/store', ['uses' => 'User\CategoriesController#store']);
});
then everything works like a charm. I'm newbie in Laravel but I think that everything must work with out that route because I use restfull controller. Any sugestions I will appriciated. Thank you.
Finally, I find the answer. According to RESTfull resource controller the URL for form action must be the main route, not /store or /create. So in form action I wrote:
<form action="/user/categories" method="POST">
And that worked for me. Anyway, thanks for help. I hope this will help someone.
change the form action to "/user/categories" like
<form action="/user/categories" method="POST">

Categories