Getting MethodNotAllowedHttpException error in Laravel - php

I'm learning Laravel. I'm trying to create a form that list the cars in a cars table and if clicked, sends into another form which is based on a DB query that returns the data of the chosen car (identified by $modelesc).
This form sends the data to a "orders" table. With the code that I have now, I'm not able to post the order on the order table. it gets the message: "MethodNotAllowedHttpException in RouteCollection.php line 233:"
This is the code
Web.php
Route::get('catalog', 'carController#catalog');
Route::get('orders/', 'CarController#orders')->name('orders');
CarController
function catalog() {
$cars = DB::table('cars')->get();
return view('catalog', compact('cars'));
}
function orders(Request $request) {
$modelesc = $request->modelesc;
$cars = DB::table('cars')->where('Model', $modelesc)->get();
$colours = DB::table('colours')->get()->pluck('Colour');
return view('orders', compact('cars', 'colours'));
}
Catalog.blade.php
#foreach($cars as $car)
{!! Form::open(array('action' => 'CarController#orders', 'method' => 'GET')) !!}
{!! Form::hidden('$modelesc', $car->Model) !!}
{!! Form::submit($car->Model) !!}
{!! Form::close() !!}
#endforeach
Orders.blade.php
#foreach($cars as $car)
{!! Form::open(['method' => 'POST']) !!}
{{ $car->Model }}
{!! Form::hidden('users_id', Auth::user()->id) !!}
{!! Form::hidden('Fabrication_date', date('Y-m-d')) !!}
{!! Form::select('Colour_id', $colours) !!}
{!! Form::hidden('Order_status_id', '1') !!}
{!! Form::submit('Ok') !!}
{!! Form::close() !!}
#endforeach
The table orders has following structure:
$table->increments('id');
$table->integer('users_id')->unsigned();
$table->foreign('users_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('Model');
$table->date('Fabrication_date');
$table->integer('Colour_id')->unsigned();
$table->foreign('Colour_id')->references('id')->on('colours')->onDelete('cascade')->onUpdate('cascade');
$table->integer('Order_status_id')->unsigned();
$table->foreign('Order_status_id')->references('id')->on('order_status')->onDelete('cascade')->onUpdate('cascade');
$table->timestamps();

Update your orders function
public function orders(Request $request)
{
$modelesc = $request->modelesc;
$cars = DB::table('cars')->where('Model', $modelesc)->get();
...
}
Catalog.blade.php
Form::hidden('modelesc', $car->Model)
The value of your hidden input will be read by request->modelesc and you will endup with a URL that looks like this http://mysite.dev/orders?modelesc=toyota.
Some advice
You using a form to only submit a hidden input. No user input. It seems to me it would be a easier to use simple anchors <a></a>.
#foreach($cars as $car)
{{ $car->Model }}
#endforeach
Same result.
Make it nice with pretty URLs. Change your route definition
Route::get('orders/{modelesc}', 'CarController#orders')->name('orders');
And the anchor
{{ $car->Model }}
With named route
{{ $car->Model }}
And the function
public function orders($modelesc)
{
$cars = DB::table('cars')->where('Model', $modelesc)->get();
...
}

change your route to:
Route::get('orders/{model}', 'CarController#orders')->name('orders');
after this change your Controller to:
public function orders($model) {
$cars = DB::table('cars')->where('Model', $model)->get();
if(!count($cars)){
abort(404);
}
$colours = DB::table('colours')->get()->pluck('Colour');
//$status = DB::select('select * from order_status where id = ?', [1])->get(); //this variable is never used
return view('orders', compact('cars', 'colours'));
}
and now change your Catalog.blade.php
in your case you don't need a form for go in your order page
#foreach($cars as $car)
{{ $car->Model }}
#endforeach

Related

How to store multi select values in Laravel

I have many to many relationship between categories and movies. When I check multiple values for categories and insert movie the result on home page selects only one category not all. I tried many things but I wasn't able to resolve this. Here is my code.
upload.blade.php:
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>
Controller:
public function index(Request $request)
{
$categories = Category::pluck('category_name', 'id')->all();
return view('movies.upload', compact('categories'));
}
public function upload(MovieUploadRequest $request)
{
DB::beginTransaction();
try {
$movie = Movie::create($request->all());
$movie->categories()->attach($request->get('category_id'));
DB::commit();
} catch (\Exception $e) {
DB::rollBack();
}
return redirect('home');
}
To enable multiple selects, you first of need to change the name of the select input from category_id to category_id[]. This enables posting of multiple variables as an array.
The code should then look like:
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id[]', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>
In your controller, you will then need to loop through the posted id's:
public function upload(...){
foreach( $request->input('category_id') AS $category_id ){
$movie = Movie::create($request->all());
$movie->categories()->attach($category_id);
...
}
}
Edit:
The method attach() also accepts an array of ids as an argument. Thereby, you don't need to loop through the input as above, but can simply use:
public function upload(...){
$movie = Movie::create($request->all());
$movie->categories()->attach($request->input('category_id'));
...
}
In your view, use a name like :
<select name="yourfiled[]"></select>.
In controller, to store it in database, just write
$movies->categories = json_encode(yourfield);
Done.
You can write this. hopefully this will solve your problem
<div class="form-group">
{!! Form::label('category_id', 'Category:') !!}
{!! Form::select('category_id[]', $categories, null, ['class'=>'form-control', 'multiple' => true]) !!}
</div>

Trying to get property of non-object laravel when accessing database

I am trying to code the edit route for laravel and for some reason keep getting the error "Trying to get property of non-object laravel". The Create controller works fine, however when I use the controller#update route I keep getting this error
My Controller for adding an event: (update)
public function update(Request $request, $id)
{
//create event
$my_user = my::find($id);
$my_user->programme = $request->input('programme');
$my_user->goal1 = $request->input('goal1');
$my_user->goal2 = $request->input('goal2');
$my_user->goal3 = $request->input('goal3');
$my_user->goal4 = $request->input('goal4');
$my_user->goal5 = $request->input('goal5');
$my_user->user_id = auth()->user()->id;
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
edit page
#extends('layouts.app')
#section('content')
<div class="container">
<h1>Edit Post</h1>
{!! Form::open(['action' => ['myUserController#update', $my_user], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('title', 'Event Name')}}
{{Form::text('goal1', $my_user->goal1, ['class' => 'form-control', 'placeholder' => 'Goal One'])}}
</div>
{{Form::hidden('_method','PUT')}}
{{Form::submit('Submit', ['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Given that you are using a Route::resource you can type-hint your parameters by writing something like
public function update(Request $request, MyUser $myuser){
// The $myuser parameter comes from the Route::resource and can be verified using php artisan route:list in your terminal
// edit $my_user
$my_user->save();
return redirect('/home')->with('success','Event Created');
}
Update after reviewing LaravelCollective documentation for Form
Thank you Sohel0415 for mentioning that you do not need to call $my_user->id for providing the route parameter with the Form facade.
You can use this method on your code:
{{ Form::open(array('url'=>'admin/users/store' , 'method' =>'POST')) }}
and your route define by this method in web.php file:
Route::post('users/store', 'admin\UserController#store');

How to customize a field of the model before storing in database

I have a model like this :
class Article extends Model {
protected $fillable = [
'title',
'body',
'img_profile', // store name of image
];
}
And a controller like this:
public function store(ArticleRequest $request){
$article = Auth::user()->articles()->create($request->all());
return redirect('articles');
}
And a form like this:
{!! Form::model($article = new \App\Article,['url' => 'articles','files' => true ]) !!}
{!! Form::text('title', null ) !!}
{!! Form::textarea('body', null) !!}
{!! Form::file ('img_profile', '') !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}
When I submit the form, the img_profile field is stored default cached file which is /private/var/tmp/phpceBMP2.But I just want to update file_name in img_profile.
How can I change the value of the img_profile request before storing it in database?
You should use mutator for Article model this way:
public function setImgProfileAttribute($value)
{
$this->attributes['img_profile'] = '/private/var/tmp/phpceBMP2/'. $value;
}
However you should think if you really want to store the path in DB this way. What if you will want to change it in future? You will have to update all the records?

Laravel - Resource route passing in wrong parametre (not the id)

I have an issue with my the update method in my controller.
Normally everything works and it takes care of itself, but this time its not working.
My controller:
public function update($id)
{
$input = Input::all();
$validation = Validator::make($input, Vehicle::$rules, Vehicle::$messages);
if ($validation->passes())
{
$this->vehicle->update($id, $input);
return Redirect::route('admin.vehicles.index')->with('success', 'Car Updated');
}
return Redirect::back()
->withInput()
->withErrors($validation);
}
Repository:
public function update($id, $input)
{
print_r($id);
die();
}
This prints out:
{vehicle}
from the URI:
http://localhost/admin/vehicles/1/edit
My form:
{{ Form::open(['route' => 'admin.vehicles.update', 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
// inputs
<div class="form-group">
{{ Form::submit('Update Vehicle', ['class' => 'btn btn-success']) }}
</div>
{{ Form::close() }}
Route:
Route::resource('/admin/vehicles', 'VehiclesController');
Where is this going wrong? How can I get this form to send the ID not the word vehicle?

Laravel 3 search function controller

I am still new in Laravel. I'm trying to create search box for searching users by their username.
What is the best way to create controller for Laravel search box?
The view that I have look as follows:
{{ Form::search_open('/users/search') }}
{{ Form::search_box('search','admin', array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
I have the controller as below:
class Users_Controller extends Base_Controller {
public function action_search() {
$userdetail = Input::get("username");
$details = User::where('username', '=', Input::get('username')) - > first();
return Redirect::to_route("users");
}
}
You may try something like this :
Route :
Route::get('/search', array('as' => 'user.search', 'uses' => 'user#search'));
View : (search/index.blade.php)
{{ Form::open(URL::to_route('user.search')) }}
{{ $errors->has('username') ? $errors->first('username','<span class="error">:message</span>') : '' }}
{{ Form::text('username', Input::old('username', $username), array('class' => 'input-medium')) }}
{{ Form::submit('Search'); }}
{{ Form::close() }}
#if ( isset($user) )
#foreach ($user->results as $user)
{{ $user->first_name }}
{{ $user->last_name }}
#endforeach
#endif
Controller : (controllers/user.php)
class User_Controller extends Base_Controller
{
public function action_search()
{
$data['username'] = Input::get('username');
if(Input::get())
{
$rules=array( 'username' => 'required' );
$validation = Validator::make(Input::all(), $rules);
if($validation->fails())
{
return Redirect::back()->with_errors($validation)->with_input();
}
else {
data['user'] = User::where('username', '=', Input::get('username'));
}
}
return View::make('search.index', $data);
}
}
Model : (models/user.php)
class User extends Eloquent
{
// ...
}

Categories