I just downloaded and started a new project with the latest Laravel 4.2. When trying to submit a form I get the following error : BadMethodCallException Method [store] does not exist
Here are my files : controller - admin/AdminController
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index() {
if (Input::has('Login')) {
$rules = array(
'email' => 'required',
'password' => 'required|min:3',
'email' => 'required|email|unique:users'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('admin\AdminController')->withErrors($validator);
} else {
// redirect
Session::flash('message', 'Successfully created user!');
return Redirect::to('admin\AdminController');
}
}
$data['title'] = ADMIN;
return View::make('admin.index', $data);
}
}
View page - admin/index.blade.php
<div class="container">
{{ Form::open(array('url' => ADMIN,'id' => 'login')) }}
<div id="icdev-login-wrap">
<div class="raw align-center logoadmin">{{ HTML::image('images/logo.png') }}</div>
<div id="icdev-login">
<h3>Welcome, Please Login</h3>
<div class="mar2_bttm input-group-lg"><input type="text" class="form-control loginput" placeholder="Email" name="email"></div>
<div class="mar2_bttm input-group-lg"><input type="password" class="form-control loginput" placeholder="Password" name="password"></div>
<div ><input type="submit" class="btn btn-default btn-lg btn-block cus-log-in" value="Login" /></div>
<div class="row align-center forgotfix">
<input type="hidden" name="Login" value="1">
</div>
</div>
<div>
</div>
</div>
{{ Form::close() }}
</div>
The error message tells you what the problem is: the method called store() doesn’t exist. Add it to your controller:
<?php
namespace admin;
use Illuminate\Support\Facades\View;
use App\Services\Validators\ArticleValidator;
use Input, Notification, Redirect, Sentry, Str;
class AdminController extends \BaseController {
public function index()
{
// leave code as is
}
public function store()
{
// this is your NEW store method
// put logic here to save the record to the database
}
}
A couple of points:
Use camel-casing for name spaces (i.e. namespace admin should be namespace Admin)
Read the Laravel documentation on resource controllers: http://laravel.com/docs/controllers#resource-controllers
You can also automatically generate resource controllers with an Artisan command. Run $ php artisan make:controller ItemController, replacing ItemController with the name of the controller, i.e. ArticleController or UserController.
Related
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
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 am making a todo list with validation using laravel 5.4.
When I click on the submit button, only the required validation is working but not the unique.
What am I doing wrong and how do I fix it so as to get it working as desired?
Below is my form (located at home.blade.php):
<div class="panel-body">
<form class="form form-control" action="/todo" method="post">
{{csrf_field()}}
<fieldset class="form-group">
<textarea class="form-control" name="textbox" id="textArea"></textarea>
<button type="submit" class="btn btn-primary">Submit</button>
</fieldset>
</form>
{{-- for dispaying the error --}}
#if (count($errors) >0)
{{-- expr --}}
#foreach ($errors->all() as $error)
<h3 class="text-danger">{{$error}}</h3>
#endforeach
#endif
</div>
Here, the content of my Todo controller (in my todocontroller.php file):
use Illuminate\Http\Request;
use App\todo;
public function store(Request $request)
{
$todo = new todo;
$todo->body = $request->textbox;
$this->validate($request,[
"body" => "required|unique:todos"
]);
$todo->save();
return redirect('/todo');
}
You should simply use the name of the field; you don't need to stress yourself.
Take a look at the snippet below:
<?php
namespace App\Http\Controllers;
use App\Todo;// following Laravel's standards, your model name should be Todo; not todo
use Illuminate\Http\Request;
class NameOfYourTodoController extends Controller
{
public function store(Request $request)
{
$todo = new Todo();
// use the name of the field directly (here, textbox)
$this->validate($request, [
'textbox' => 'required|unique:todos'
]);
// other code logics here.
}
}
I'm newbie to Laravel and got stuck with login mechanism I'm using my custom login mechanism here (not using Laravel Authentication) and there I'm not able to login with authenticate credentials.
I want to login with credentials and after login the log should be maintain in login_master and redirected to home. but it is not maintaining plus if the credentials are wrong then it should redirect back to signin.blade.php but it's redirecting to home.
Here is the code
create_login_table.php (My Login Table Structure)
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLoginTable extends Migration
{
public function up()
{
Schema::create ('login_master',function($table)
{
$table->increments('login_id',true);
$table->integer('user_id')->unsigned();
$table->date('login_date');
$table->date('login_time');
});
// to create foreign key :)
Schema::table('login_master', function($table) {
$table->foreign('user_id')->references('user_id')->on('registration_master');
});
}
public function down()
{
Schema::dropIfExists('login_master');
}
}
LoginController (Controller for working with table)
namespace App\Http\Controllers;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Validator;
class LoginController extends Controller
{
public function loginform()
{
return view('signin');
}
public function authenticate(Request $request)
{
$userdata= Input::all();
$rules= array(
'email' => 'required|email',
'password' => 'required| min:6',
);
$validator = Validator::make($userdata,$rules);
if($validator->fails())
{
redirect('/signin')->withInput(Input::except('password'))->withErrors($validator);
}
else
{
$userdata= array(
'email' => Input::get('email'),
'password' => Input::get('pwd')
);
if(Auth::validate($userdata))
{
if(Auth::attempt($userdata))
{
$email= $userdata['email'];
$password= $userdata['password'];
$live_date=Carbon::now();
$log_date=$live_date->toDateString();
$log_time=$live_date->toTimeString();
$user_id= DB::select('select user_id from registration_master where email= ? and password = ?',[$email, $password]);
$record= DB::insert('insert into login_master
(user_id, login_date, login_time) values(?, ?, ?)',[$user_id, $log_date, $log_time]);
echo $email;
echo $password;
return Redirect::intended('/');
}
}
else
{
Session::flash('error', 'Something went wrong');
return Redirect::to('signin');
}
}
}
public function logout()
{
Auth::logout();
return Redirect::to('signin');
}
}
signin.blade.php (view for login)
<html>
<head>
<title>App Name - #yield('title')</title>
#include('library')
</head>
<body>
#include('header')
<div class="form-content">
<div class="headingstyle form-title">
<h1 class="heading1">Log in!</h1>
</div>
<form method="post" action="/home">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="formgroup">
<input class="input" type="text" name="uemail"required>
<label class="label">Email</label>
</div>
<div class="formgroup">
<input class="input" type="password" name="pwd"required>
<label class="label">Password</label>
</div>
<div class="formgroup bottomstyle">
<div id="check-awesome" class="form-group checkbox">
<input type="checkbox" id="RememberMeUser" mame="RememberMeUser">
<label for="RememberMeUser">
<span></span>
<span class="check"></span>
<span class="box"></span>
Remember Me
</label>
</div><!--Login-->
<input type="submit" value="Login"><br>
<a data-dismiss="modal" class="button cancelbtn">Cancel</a><br>
<span class="links"> <a class="bottomlink" href="#">Forgot Password?</a></span><br>
<span class="links">New User
<!--<a class="bottomlink" href="#" data-dismiss="modal" data-toggle="modal" data-target="#id02">Sign Up?</a> -->
{{ Html::linkAction('SignUpController#signupform','Sign Up', array(), array('class' => 'bottomlink')) }}
</span>
</div>
</form>
</div>
<div>
#include('footer')
</div>
</body>
</html>
You will need to configure app/auth.php or dotenv to use your own custom model with the Auth Guard helper in Laravel. There you can set the model and table you want to use.
Else you could implement your own Auth helper/facade to save logged_in_user_id in session. Your custom authentication will basically confirm the passed user credentials and store the logged_in_user_id in session. Your logout method will likewise clear this id from session when called.
I want to save one form data through my task controller. But when i go to url to access my form. it's showing the following Error:
MethodNotAllowedHttpException in RouteCollection.php line 219:
Here is my Routes.php
<?php
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
return view('welcome');
});
Route::get('/all_item','TestController#index');
Route::post('/create_item','TestController#create');
Route::get('/home', 'HomeController#index');
});
Here is my TaskController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Test;
use App\Http\Requests;
use Redirect;
class TestController extends Controller
{
public function index()
{
$alldata=Test::all();
// return $alldata;
return view('test.itemlist',compact('alldata'));
}
public function create()
{
return view('test.create_item');
}
public function store(Request $request)
{
$input = $request->all();
Test::create($input);
return redirect('test');
}
}
Here is the create_item page( post form / view page)
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Create Item</div>
{!! Form::open(array('route' => 'Test.store','class'=>'form-horizontal','method' => 'patch')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label>Item Code</label>
<input type="text" name="item_code" class="form-control" placeholder="Code">
</div>
<div class="form-group">
<label>Item Name</label>
<input type="text" name="item_name" class="form-control" placeholder="Name">
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endsection
You're using PATCH method in form, but route with POST method
try
'method' => 'patch'
change to
'method' => 'post'
LaravelCollective's HTML only supports methods POST, GET, PUT DELETE
so you might want to change that to POST or PUT
'method' => 'POST'
You haven't declared a Test.store route in your Routes.php, so try adding a resource or a named route:
Route::post('/store_item', [
'as' => 'Test.store', 'uses' => 'TestController#store'
]);
As i can see TestController#create is a post method.But it behaves like a get method.Try passing Request $request parameter to the create method.Or else if you really need a get method for the create method, change the method as get in Routes.php as like this,
Route::get('/create_item','TestController#create');