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');
Related
I'm coding a quiz app and I'm trying to add an edit function to it. With a click on the 'Submit' Button I get the error Missing required parameters for [Route: quiz/show] [URI: quiz/{quiz}].
How can I fix that? I'm a beginner in Laravel so it would be nice if you could help me.
My web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\MainController;
use App\Http\Controllers\QuizController;
use App\Http\Controllers\DashboardController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Route::get('dashboard', 'App\Http\Controllers\DashboardController#index')->name('dashboard');
Route::get('quiz/create', 'App\Http\Controllers\QuizController#create');
Route::post('quiz', 'App\Http\Controllers\QuizController#store');
Route::get('quiz/{quiz?}', 'App\Http\Controllers\QuizController#show')->name('quiz/show');
Route::get('quiz/{quiz}/questions/create', 'App\Http\Controllers\QuestionController#create');
Route::post('quiz/{quiz}/questions', 'App\Http\Controllers\QuestionController#store');
Route::delete('quiz/{quiz}/questions/{question}', '\App\Http\Controllers\QuestionController#destroy');
Route::get('question/edit', '\App\Http\Controllers\QuestionController#edit')->name('question/edit');
Route::patch('question/{question}', '\App\Http\Controllers\QuestionController#update')->name('question/update');
Route::get('startquiz/{quiz}-{slug}', 'App\Http\Controllers\StartQuizController#show');
Route::post('startquiz/{quiz}-{slug}', 'App\Http\Controllers\StartQuizController#store');
My QuestionController
<?php
namespace App\Http\Controllers;
use App\Models\Question;
use App\Models\Quiz;
use Illuminate\Http\Request;
class QuestionController extends Controller
{
public function create(Quiz $quiz) {
return view('question.create', compact('quiz'));
}
public function store(Quiz $quiz) {
$data = request()->validate([
'question.question' => 'required',
'answers.*.answer' => 'required',
]);
$question = $quiz->questions()->create($data['question']);
$question->answers()->createMany($data['answers']);
return redirect('/quiz/'.$quiz->id);
}
public function destroy(Quiz $quiz, Question $question) {
$question->answers()->delete();
$question->delete();
return redirect($quiz->path());
}
public function edit(Question $question) {
return view('quiz.edit', compact('question'));
}
public function update(Request $request, Question $question, Quiz $quiz) {
//$request->validate([
//'question' => 'required',
//]);
$question->update($request->all());
//dd($quiz);
return redirect()->route('quiz/show', ['quiz' => $question->quiz])
-> with('success', 'Question updated successfully');
}
}
My edit.blade
<html>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<body>
<h1>Edit Question</h1>
<form action="{{ route('question/update',$question->id) }}" method="POST">
#csrf
#method('PATCH')
<div class="container">
<div class="row justify-content-center">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="question">Question</label>
<input type="text" class="form-control" name="question" value="{{ $question->name }}"placeholder="Enter Question">
<small id="questionHelp" class="form-text text-muted">Type in your edited question.</small>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
</form>
</body>
</html>
Your route for "update" does not take any parameters. Your update method of the Controller looks like it wants to use Route Model Binding but there are no parameters so you are getting a non existing instance of Quiz which doesn't have an id so its trying to use null which you can not do for route parameters when generating URLs.
You need to adjust your route URI definition to take a parameter for question and quiz. Maybe:
Route::patch('quiz/{quiz}/question/{question}', ...)
If you don't want to use route parameters for quiz or question you will have to make adjustments to the controller to get the information from the request inputs.
Other quick option:
You should be able to derive the quiz from the question so you don't need to pass the quiz along:
Route::patch('question/{question}', ...)
public function update(Request $request, Question $question)
{
$question->update($request->all());
return redirect()->route('quiz/show', ['quiz' => $question->quiz])
->with('success', 'Question updated successfully');
}
I have created a view to create new courses 'create.blade.php'. And I am trying to store this data in the DB however I am getting the following error:
BadMethodCallException Method Illuminate\Http\Request::request does
not exist.
I am not sure what is causing the error as I have referred to the the request namespace in my controller. See below;
CoursesController.php;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$courses = Course::all()->pluck('title');
$instructors = User::all()->pluck('name', 'id'); //defining instructor variable
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->courses()->sync($request->request('courses', [])); //
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
}
Create.blade.php
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control {{ $errors->has('title') ? 'is-invalid' : '' }}" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
#if (Auth::user()->isAdmin())
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $instructors, Input::get('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
#if($errors->has('Instructor'))
{{ $errors->first('Instructor') }}
</p>
#endif
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
#endif
</form>
</div>
</div>
#endsection
I am new to laravel so i would appreciate any help. Thanks.
The error message
BadMethodCallException Method Illuminate\Http\Request::request does
not exist
speaks to an attempt to call a method/function named request on the Illuminate\Http\Request class, and that function not existing.
it looks like you are indeed trying to use a request() method here:
$course->courses()->sync($request->request('courses', []));
You most likely want the input() method instead, which would get data posted as 'courses'.
$course->courses()->sync($request->input('courses', []));
as described at https://laravel.com/docs/master/requests#input-trimming-and-normalization
I hope this helps!
change
$course->courses()->sync($request->input('courses', []));
Basically i have this form on userblog/create.blade.php
<form action="{{route('userblog.store')}}" method="POST">
{{csrf_field()}}
<div class="form-group">
<div class="row">
<div class="col-md-12">
<label style="font-family: SansBold">تیتر وبلاگ:</label>
<input type="text" name="blog_title"
class="form-control">
</div>
</div>
</div>
<div class="text-right">
<button type="submit" class="btn btn-primary">
Save
<i class="icon-arrow-left13 position-right"></i></button>
</div>
<br/>
</form>
with this route on web.php
Route::group(['middleware' => ['auth:web'], 'prefix' => 'page'], function () {
$this->resource('userBlog', 'UserBlogController');
});
now I'm trying to check posted form on Controller with this code and store them on database:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'blog_title' => 'required|min:10',
'blog_content' => 'required|min:10',
]);
if ($validator->failed()) {
return back();
} else {
dd('store on database');
}
}
in this my code i get
Route [userblog.store] not defined
error and when i change form action to /page/userBlog i get [] on $validator
The routes name should be like resource name. Replace your resource name or Route name like:
$this->resource('userblog', 'UserBlogController');
or
.. action="{{route('userBlog.store')}}"
BTW, It's not a validation error. Just fix your route.
i use the validated method for validate request, but the var errors is empty in the view :/.
in the controller, i have:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function(){
return view('home');
})->name('home');
Route::group(['prefix' => 'do'], function($name = null){
Route::get('/{action}/{name?}', ['uses' => 'controllers#get', 'as' => 'get']);
Route::post('/', ['uses' => 'controllers#post', 'as' => 'post' ]);
});
});
for the controller, i have:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class controllers extends Controller
{
public function get($action, $name=null)
{
return view('actions.' . $action, ['name' => $name]);
}
public function post(Request $request)
{
$this->validate($request, [
'action' => 'required',
'name' => 'alpha|required'
]);
return view('actions.'.$request['action'] , ['action' => $request['action'], 'name'=>$this->transformName($request['name'])]);
}
private function transformName($name)
{
$add = "king ";
return $add.strtoupper($name);
}
}
and for the view, i have:
#extends('layouts.master')
#section('content')
<div class="centered">
greet
hug
kiss
<br >
<br >
#if (isset($errors) && count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
{!! $errors->first() !!}
#endforeach
</ul>
</div>
#endif
<form action="{{ route('post')}}" method="post">
<label for="select-action">I want to...</label>
<select id="select-action" name="action">
<option value="greet">greet</option>
<option value="hug">hug</option>
<option value="kiss">kiss</option>
</select>
<input type="text" name="name">
<button type="submit">action</button>
<input type="hidden" name="_token" value="{{Session::token()}}">
</form>
</div>
#endsection
if i delete the middleware of the route, the var errors work correctly.
how i can fix this?
thanks.
If you're using latest Laravel 5.2 build, you should remove web middleware from routes. Now it applies automatically to all routes and if you're trying to add it manually, it causes different errors.
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.