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', []));
Related
How to show an old value / query field from database in mysql, and edit value in Laravel. I'm using Laravel 9x and PHP 8x
Controller.php :
public function edit(Business $business)
{
return view('dashboard.bisnis.edit', [
'item' => $business
]);
}
public function update(Request $request, Business $business)
{
$rules = [
'deskripsi' => 'required|max:255',
'pemilik' => 'required|max:255'
];
$validateData = $request->validate($rules);
Business::where('id', $business->id)->update($validateData);
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
}
Blade.php:
#extends('dashboard.index')
#section('container')
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Edit Data Bisnis</h1>
</div>
<div class="col-lg-8">
<form method="post" action="/dashboard/bisnis/{{ $item->id }}" class="mb-5" enctype="multipart/form-data">
#method('put')
#csrf
<div class="mb-3">
<label for="deskripsi" class="form-label">Deskripsi</label>
<input type="text" class="form-control #error('deskripsi') is-invalid #enderror" id="deskripsi" name="deskripsi" required autofocus
value="{{ old('deskripsi', $item->deskripsi) }}">
#error('deskripsi')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="pemilik" class="form-label">Pemilik</label>
<input type="text" class="form-control #error('pemilik') is-invalid #enderror" id="pemilik" name="pemilik" required autofocus
value="{{ old('pemilik', $item->pemilik) }}">
#error('pemilik')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Simpan Perubahan</button>
</form>
</div>
<script>
const deskripsi = document.querySelector('#deskripsi');
const pemilik = document.querySelector('#pemilik');
</script>
#endsection
Also when navigating through my menu such as Business, the sidebar seems cant to be clicked, nor use. Thank you so much
Please try like this:
{{ old('deskripsi') ? old('deskripsi') :$item->deskripsi }}
Please replace this:
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
to
return redirect()->back()->with('success', 'Item has been updated !');
I assume you use Laravel 9
Referring to Repopulating Forms - Validation
Controller.php:
you should use
$deskripsi = $request->old('deskripsi');
$pemilik = $request->old('pemilik');
before
$validateData = $request->validate($rules);
Blade.php:
you should use this on input
value="{{ old('deskripsi') }}"
value="{{ old('pemilik') }}"
By default old will return null if no input exists so we don't need to use nullcheck like
{{old('deskripsi') ?? ''}}
To repopulate value using old() in Laravel you need to return a response withInput(). Not just response.
The return code should
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !');
change to this
return redirect('/dashboard/bisnis')->with('success', 'Item has been updated !')->withInput();
The solution is i forgot to pass my $id on my controller and route (web.php). Here's my route
Route::controller(GroupServiceController::class)->middleware('auth')->group(function () {
Route::get('/dashboard/gruplayanan', 'index');
Route::get('/dashboard/gruplayanan/create', 'create')->name('gruplayanan.create');
Route::post('/dashboard/gruplayanan', 'store')->name('gruplayanan.store');
Route::get('/dashboard/gruplayanan/edit/{id}', 'edit')->name('gruplayanan.edit');
Route::post('/dashboard/gruplayanan/update/{id}', 'update')->name('gruplayanan.update');
Route::post('/dashboard/gruplayanan/delete/{id}', 'destroy')->name('gruplayanan.delete');
});
and my controller :
public function edit(GroupService $groupService, $id)
{
$groupService = $groupService->findOrFail($id);
return view('dashboard.gruplayanan.edit', [
'item' => $groupService
]);
}
I started creating an e-commerce platform and I'm stuck with a problem I can't solve for 2 days.. It's probably something obvious but I just can't find the solution for this. Could you help me with this, please? I get this error:
Missing required parameters for [Route: images.update] [URI: dashboard/images/{image}]. (View: C:\xampp\htdocs\ecommerce\ecommerce\resources\views\website\admin\product_image\update.blade.php)
update.blade.php
#extends('website.admin.layouts.main')
#section('content')
<div class="col-md-12 col-sm-12 ">
<div class="x_panel">
<div class="x_title">
<h2>Zaktualizuj obraz</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
<form id="updateimage-form" data-parsley-validate="" class="form-horizontal form-label-left" novalidate="" enctype="multipart/form-data" method="POST" action="{{route('images.update', $productImage->id)}}">
#csrf
#method('PUT')
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Produkt<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<select class="form-control" name="product_id">
#foreach ($product as $prodcat)
<option value="{{$prodcat -> id}}" name="product_id">{{ $prodcat -> product_name }}</option>
#endforeach
</div>
</div>
<div class="ln_solid"></div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Nazwa obrazu<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="text" id="img_title" name="img_title" placeholder="Image Title" value="{{ $productImage -> image_name }}" required="required" class="form-control ">
</div>
</div>
<div class="item form-group">
<label class="col-form-label col-md-3 col-sm-3 label-align" for="first-name">Wgraj obraz<span class="required">*</span></label>
<div class="col-md-6 col-sm-6 ">
<input type="file" name="img" id="img" onchange="fileSelected();"/>
</div>
</div>
<div class="item form-group">
<div class="col-md-6 col-sm-6 offset-md-3">
<button class="btn btn-primary" type="reset">Wyczyść</button>
<button type="submit" class="btn btn-success">Zaktualizuj obraz</button>
</div>
</div>
</form>
</div>
</div>
</div>
#endsection
models\ProductImage.php
<?php
namespace App\Models\models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ProductImage extends Model
{
protected $fillable = [
'product_id',
'image_name',
'image',
'slug',
'status'
];
public function product()
{
return $this -> belongsTo('App\Models\models\Product');
}
}
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\Product;
use App\Models\models\ProductImage;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
class ProductImageController extends Controller
{
public function index()
{
$productImage = ProductImage::all();
return view('website.admin.product_image.index', compact('productImage'));
}
public function create()
{
$product = Product::all();
return view('website.admin.product_image.create', compact('product'));
}
public function store(Request $request)
{
$slug = Str::slug($request->image_name, '-');
$image = time().'.'.$request->image->extension();
$request->image->move(public_path('images'), $image);
ProductImage::create([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function show(ProductImage $ProductImage)
{
//
}
public function edit(ProductImage $productImage)
{
$product = Product::all();
return view('website.admin.product_image.update',compact('productImage','product'));
}
public function update(Request $request, ProductImage $productImage)
{
$slug=Str::slug($request->image_name,'-');
if($request->image)
{
$image = time() .'.'. $request -> image -> extension();
$request->image->move(public_path('images'), $image);
}
else
{
$image=$productImage->image;
}
$productImage->update([
'image_name'=>$request->image_name,
'image'=>$image,
'product_id'=>$request->product_id,
'slug'=>$slug,
]);
return redirect()->route('images.index');
}
public function destroy(productImage $productImage)
{
$productImage->delete();
return redirect()->route('images.index');
}
}
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('website.shop.layouts.main');
});
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard.index');
Route::resource('/dashboard/categories', 'App\Http\Controllers\ProductCategoryController');
Route::resource('/dashboard/product', 'App\Http\Controllers\ProductController');
Route::resource('/dashboard/images', 'App\Http\Controllers\ProductImageController');
update.blade.php
<form method="post" action="{{route('images.update', $productImage->id)}}" enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group">
<label for="filename">Select your Image</label>
<input type="file" name="image" class="form-control">
<button type="submit" class="btn btn-primary btn-lg">Update</button>
</div>
</form>
ProductImageController.php
<?php
namespace App\Http\Controllers;
use App\Models\models\ProductImage;;
use Illuminate\Http\Request;
class DocumentController extends Controller
{
public function update(Request $request, $productId){
$product = ProductImage::findOrFail($productId);
if($request->hasfile('image'))
{
$file = $request->file('image');
$name=$file->getClientOriginalName();
$file->move(public_path().'/uploads/ProductImages/', $name);
$file = $name;
$product->image = $file;
}
$product->save();
return redirect()->back();
}
}
I solved this, the problem was with "images" name in route. I changed it to something else everywhere and it works now.
action="{{route('images.update', $productImage->id)}}" is incorrect way of calling route() helper function. Consider the following snippet;
action="{{route('images.update', [
'image' => $productImage->id
])}}"
For more details about route() helper, see this link; https://laravel.com/docs/8.x/helpers#method-route
You don't have Model Binding happening here you have Dependency Injection happening instead. For Implicit Route Model Binding to take place you have to match the type hinted parameter of your method to the name of the route parameter. In your case the route parameter is named image, not productImage. So you are getting an empty new instance of ProductImage instead of the replacement for the Route Model Binding.
Change your controller's parameter to match the route parameter:
vvvvv
public function edit(ProductImage $image)
You would need to change this in all the methods you want the Implicit Binding for, unless you want to override the parameter used in the route.
vvvvv
public function update(Request $request, ProductImage $image)
At the moment you are passing an empty model to your view which is then trying to use it's "id" to generate a route, but "id" is null and route parameters can no to null.
I'm start learning laravel and want to create sample login authorization system on my html template. I watched a tutorial and when i do everything that was in video i get error Undefined variable: erros.
I'm new and I don't know good PHP but i want to learn while creating a website I know a little.
my rout code is my route code :
this is route for my login code
Route::get ('/main', 'MainController#index');
Route::get ('/main/checklogin', 'MainController#checklogin');
Route::get ('/main/successlogin', 'MainController#successlogin');
Route::get ('/main/logout', 'MainController#logout');
1.my login code
<div class="login slide-up">
<div class="center">
<h2 class="form-title" id="login"><span>sign</span>in</h2>
#if (isset(Auth::user()->email))
<script>window.location="/main/successlogin"</script>
#endif
#if ($message = Session::get('error'))
<div class ="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">X</button>
<strong>{{$message}}</strong>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
#if(count($errors) >0 )
<div class="alert alert-danger">
<ul>
#foreach($erros->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="get" action="{{ url('/main/checklogin')
}}">
{{ csrf_field()}}
<div class="form-holder">
<input type="email" class="input" placeholder="email" />
<input type="password" class="input" placeholder="password" />
</div>
<button class="submit-btn">Sign in</button>
</div>
2.my successlogin code
<html>
<body>
#if (issets(auth::user()->email))
<p>gamarjoba {{Auth::user()->email}}}</p>
<a href="{{ url('/main/logout') }}" > logout </a>
else
<script>windows.location = "/main"; </script>
#endif
</body>
</html>
my main controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Auth;
class MainController extends Controller
{
function index()
{
return view('front/login');
}
function checklogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|alphaNum|min:4'
]);
$user_data = array(
'email' => $request -> get('email'),
'password' => $request -> get('password')
);
if (Auth::attempt($user_data))
{
return redirect('main/successlogin');
}
else
{
return back()->with('error', 'wrong Login Details');
}
}
function successlogin()
{
return view('successlogin');
}
function logout()
{
Auth::logout();
return redirect('main');
}
}
Laravel made this easy:
Run php artisan make:auth
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 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');