I want to Edit my Database through Laravel Form. Edit do works but when i want to update the database it's showing the following Error.
MethodNotAllowedHttpException in RouteCollection.php line 219:
here is my Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
return view('course.create');
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
public function show($id)
{
//
}
public function edit($id)
{
$course=Course::findOrFail($id);
return view('course.edit',compact('course'));
}
public function update(Request $request, $id)
{
$input = $request->all();
$data=Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
public function destroy($id)
{
$data=Course::findOrFail($id);
$data->delete($input);
return redirect('course');
}
}
Here is my Edit Page:
<html>
<head>
<title> Update Course </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" >
<h3> Update course </h3>
{!! Form::open(array('route' =>['course.update',$course->course_id],'class'=>'form-horizontal')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label >Course Code</label>
<input type="text" name="course_code" class="form-control" value="{{$course->course_code}}">
</div>
<div class="form-group">
<label >Course Title</label>
<input type="text" name="course_title" class="form-control" value="{{$course->course_title}}">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" value="{{$course->course_credit}}">
</div>
<button type="submit" class="btn btn-default">Update</button>
{!! Form::close() !!}
</div>
</body>
</html>
Here is the route:
<?php
Route::resource('course','courseController');
Route::group(['middleware' => ['web']], function () {
});
If anyone can solve the problem.please help.
When you try to edit you need to add method type according this link.
Specifying different methods
You can use methods other than POST with your forms. Pass the 'method'
you want in the array argument. Valid methods are 'get', 'put',
'patch', 'post', or 'delete'.
So in your case you need to add 'method' => 'patch' to your Form::open..
So your final code in blade will look like this:
{!! Form::open([
'method' => 'PATCH',
'route' => ['course.update',$course->course_id],
'class'=>'form-horizontal'
]) !!}
Extra
I can see you are using php tags like <?php echo csrf_field(); ?>, I assume you know in Laravel you can use {{ csrf_field() }} which is equal, but since I do not have in depth knowledge about your code, so it is left to you.
Related
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', []));
I am trying to allow a user to update their information after they have submitted a form, but did not check a certain box. Everything is within the same page and I am controlling the different modals by returning a message, which triggers a script to open the different modals.
For some reason, I can't seem to pass the ID or email through to the next step. Can anyone help with this?
Whenever, I try, I get the following error:
Undefined variable: leads
Any idea?
Thanks!!!
Files:
web.php
index.blade.php
LeadsController.php
Leads.php
Web.php
Route::post('/', [
'uses' => 'LeadsController#store',
'as' => 'leads.store'
]);
Route::patch('/{email}', [
'uses' => 'LeadsController#update',
'as' => 'leads.update'
]);
Index.blade.php
<html>
<div id="contact" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form id="form" class="form" action="/" method="post" accept-charset="utf-8">
{{ csrf_field() }}
<input type="email" name="email" value="{{ old('email') }}">
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#if(session()->has('message'))
<div id="sign_up" class="modal fade">
<div class="modal-dialog modal-content modal-lg">
<div class="modal-body">
<form method="post" action="{{ route('leads.update', $leads->email) }}">
{{ csrf_field() }}
{{ method_field('PATCH') }}
<input type="checkbox" name="newsletter">
<button type="submit">Submit</button>
</form>
</div>
</div>
</div>
#endif
</body>
</html>
LeadsController.php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator)->withInput($request->all);
} else {
try {
$leads = new Leads;
$leads->email = $request->email;
$leads->newsletter = $request->newsletter;
$leads->save();
if($request->newsletter == ''){
return redirect()->back()->with('message','sign up')->withInput($request->all)->with($leads->email, $request->get('email'));
}
if($request->newsletter == 'true'){
return redirect()->back()->with('success','success');
}
} catch (Exception $e) {
return response()->json(
[
'status' => false,
'error' => base64_encode($e->getMessage()),
],
Status::HTTP_INTERNAL_SERVER_ERROR
);
}
}
}
public function update($email)
{
$leads = Leads::find($email);
$leads->newsletter = $input('newsletter');
$leads->save();
return redirect()->back()->with('success','success');
}
Leads.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Leads extends Model
{
protected $table = 'my_renamed_table';
public $timestamps = false;
protected $fillable = ['email', 'newsletter'];
}
Thanks for all of your help and your questions! You helped push me in the right direction.
Here is how I solved it:
I had to correct myself in how I pushed the $email through to the view:
LeadsController
return redirect()
->back()
->with('message','sign up')
->withInput($request->all)
->with('email', $request->get('email'));
Notice how I'm sending the email through as 'email' here.
Then, I pushed the email through the view in the 2nd form like this:
index
<form method="post" action="{{ route('leads.update', session('email')) }}">
Then, finally, in order to capture the email again, use it to find the lead that I wanted, I had to drastically change the update:
public function update($email)
{
DB::table('my_renamed_table')
->where('email', $email)
->update(['newsletter' => Input::get('newsletter')]);
return redirect()->back()->with('success','success');
}
Thanks again!
//this is the view.blade.php file. it is showing the above error can any one please give ideas whats going wrong . the Route. php file and the blog controller.php is given below. ,maybe the the problem is in controller or route file , i dont know.
///view.blade.php
#section ('content')
#include('blog.partials.post', array('post'=> $post))
<hr/>
<section id="comments">
#foreach($post->comments as $comment)
<div class="comment">
<p>{{$comment->name }} says...</p>
<blockquote>
{{$comment->comment}}
</blockquote>
</div>
#endforeach
</section>
<section>
<h3 class="title">Add a Comment..</h3>
<form action="{{ URL::route('createComment'), array('id'=>$post->id)}}" method="POST">
<div class="form-group" >
<input type="text" name="name" placeholder="your name" class="form-control">
</div>
<div class="form-group" >
<textarea class="form-control" name="content" placeholder="your comment">
</textarea>
</div>
<input type="submit" class="btn btn-primary" value="Add Comment">
</section>
#stop
///route.php
Route::get('/', 'BlogController#index');
Route::get('post/new', array(
'uses'=>'BlogController#newPost',
'as' =>'newPost',
));
Route::post('/post/new' ,array(
'uses' =>'BlogController#createPost',
'as' =>'createPost',
));
Route::get('post/{id}',array(
'uses' =>'BlogController#viewPost',
'as' =>'viewPost',
));
Route::post('/post/{id}/comment',array(
'uses'=>'BlogController#createComment',
'as' =>'createComment'
));
////BlogController
class BlogController extends BaseController {
// set this controller's layout
protected $layout = 'layouts.master';
public function index()
{
$this->layout->content = View::make('blog.index',array(
'posts'=>Post::all()
));
}
// TODO: implement all the function we need in this controller
public function newPost()
{
$this->layout->content = View::make('blog.new');
}
public function createPost()
{
$post= new Post();
$post->title=Input::get('title');
$post->content=nl2br(Input::get('content'));
$post->save();
return Redirect::route('viewPost', array('id'=>$post->id));
}
public function viewPost($id)
{
$post = Post::findOrFail($id);
$this->layout->content = View::make('blog.view',array(
'post' =>$post
));
}
public function createComment($id)
{ $post = Post::findOrFail($id);
$Comment= new Comment();
$Comment->name=Input::get('name');
$Comment->content=nl2br(Input::get('content'));
$post->Comments()->save();
return Redirect::route('viewPost',array('id'=>$post->id));
}
}
Your parameter should be like this
<form action="{{ URL::route('createComment', array('id'=>$post->id))}}" method="POST">
Note : laravel blade template {{}} is equivalent to echo so now your passing parameter outside . so it's trying to echo the array . so here echo can't echo the array variable . that's why it's gave this error.
Array to string Conversion
I want to save some data through dropdownlist .. after loading the page, database also fetched with the dropdown but it doesn't save after I clicked the save button. I think there is problem with Course migration table but I couldn't get it.
[Scenery is while taking courses student can take a class from the dropdown list.]
Here is my contoller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Course;
use App\TheClass;
use Redirect;
class courseController extends Controller
{
public function index()
{
$alldata=Course::all();
return view('course.index',compact('alldata'));
}
public function create()
{
$input=\App\TheClass::all();
return view('course.create',compact('input'));
}
public function store(Request $request)
{
$input = $request->all();
Course::create($input);
return redirect('course');
}
}
Here is my view page:
<html>
<head>
<title> Create Course </title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" >
<h3> Create course </h3>
{!! Form::open(array('route' => 'course.store','class'=>'form-horizontal')) !!}
{!! Form::token(); !!}
<?php echo csrf_field(); ?>
<div class="form-group">
<label>Course Code</label>
<input type="text" name="course_code" class="form-control" placeholder="Code">
</div>
<div class="form-group">
<label>Course Title</label>
<input type="text" name="course_title" class="form-control" placeholder="Title">
</div>
<div class="form-group">
<label>Course Credit</label>
<input type="text" name="course_credit" class="form-control" placeholder="Credit">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="class_id" >
#foreach($input as $row)
<option value="{{$row->class_id}}">{{$row->class_name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
</body>
</html>
Course Table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCourseTable extends Migration
{
public function up()
{
Schema::create('courses', function (Blueprint $table) {
$table->increments('course_id');
$table->string('course_code',10);
$table->string('course_title',50);
$table->string('course_credit');
$table->integer('class_id')->unsigned();
$table->timestamps();
$table->foreign('class_id')->references('id')->on('classes');
});
}
public function down()
{
Schema::drop('courses');
}
}
The Class table Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClassTable extends Migration
{
public function up()
{
Schema::create('classes', function (Blueprint $table) {
$table->increments('id');
$table->string('class_name',10);
$table->timestamps();
});
}
public function down()
{
//
}
}
Change {{$row->class_id}} to {{$row->id}}
Because your classes table does not have class_id column.
First of all you need to add $fillable to your model as create
method uses Mass Assignment.
Secondly I dont see any category field in migrations. Your select
has name category so in database also should be category field.
Basically here you need to use One To Many
P.S. Don't have enough points for comments so answered.
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');