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

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?

Related

How to display the last inserted id in db using Laravel after creating

Patient Controller:
public function store(Request $request)
{
$input = request()->all();
Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
}
This is my medical.create view
{!! Form::model($input, [
'method' => 'POST',
'action' => ['MedicalController#store', $input->id]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id', null, array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}
I want to get my last inserted id after storing, and display the last id in the next form, but this is the error appear in my screen:
Trying to get property 'id' of non-object
This is my Patient table:
You can do that by saving the Patient object in a variable when creating it:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input); // Save it in variable
dd($patient->id); //Now you can access patient id here
// return redirect()->route('medical.create',compact('patient')); //Also you can pass it to your view
}
you can use id like Code below with least Changes in your code
$input = request()->all();
$input = Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
you can retrive id after saving data by mass assignments :
public function store(Request $request)
{
$input = request()->all();
$patient = new Patient($input); // fill model with mass assignments
$patient->save() // save instant
$id = $patient->id; //retrive id
}
You can't use compact while redirecting. Try this:
Patient Controller:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input);
$patient = DB::table('patients')->get()->last();
return redirect()->route('medical.create')->with('patient_id', $patient->id);
}
This is my medical.create view
{!! Form::model($input, [
'method' => 'POST',
'action' => ['MedicalController#store', session('patient_id')]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id', null, array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}

Despite using 'fillable' and checking all variables, my create method in the controller is not saving input to model

I'm trying to save some data to my model using a form and my controller.
The form looks like this:
<body>
<div class="container">
<h1>Assign days to event</h1>
{{ Form::open(array('url' => 'days')) }}
<div class="form-group">
{{ Form::label('event_name', 'Event Name') }}
{{ Form::select('event_name', $events, null) }}
</div>
<div class="form-group">
{{ Form::label('day_number', 'Number of Days') }}
{{ Form::text('day_number', Input::old('day_number'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Assign!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
</div>
</body>
My Create/Store functions in my Controller looks like this:
namespace StrawDogBuilder\Http\Controllers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use View;
use Session;
use Redirect;
use StrawDogBuilder\Day;
use StrawDogBuilder\Event;
use Illuminate\Http\Request;
public function create()
{
$events = Event::pluck('id');
return View::make('days.create')
->with('events', $events);
}
public function store()
{
$rules = array(
'event_id' => 'required',
'day_number' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('days/create')
->withErrors($validator)
->withInput(Input::except('password'));
}
else {
$day = new day;
$day->event_id = Input::get('event_name');
$day->day_number = Input::get('day_number');
$day->save();
Session::flash('message', 'You have assigned this event a number of days');
return Redirect::to('days');
}
}
And my Model looks like this
class Day extends Model
{
protected $fillable = ['id','event_name','day_number'];
public function mods()
{
return $this->hasMany('App\Mod');
}
// Get the Event this day is attributed to
public function event()
{
return $this->belongsTo('App\Event');
}
}
The form is created without errors, however when I add values to the fields and hit 'Assign!' it will stay on the same page and will not indicate if it has done anything. Checking the table shows that it hasn't saved the data.
Am I missing something that causes the form to save the data via the controller, and if so what could it be?
First of all revised your form as
{!! Form::open(['route'=>'days.store']) !!}
Then in your controller
public function store(Request $request)
{
$this->validate($request,
array(
'event_id' => 'required',
'day_number' => 'required',
)
);
$day = new Day;
$day->event_id = $request->event_name;
$day->day_number = $request->day_number;
$day->save();
Session::flash('message', 'You have assigned this event a number of days');
return redirect()->route('days');
}

Laravel Form-Model Binding multi select default values

I'm trying to bind a default value to a select tag. (in a "edit view").
I know this should be easy, but I think I'm missing something.
I have:
User.php (my user model)
...
public function groups()
{
return $this->belongsToMany('App\Group');
}
public function getGroupListAttribute()
{
return $this->groups->lists('id');
}
...
UserController.php (my controller)
...
public function edit(User $user)
{
$groups = Group::lists('name', 'id');
return view('users.admin.edit', compact('user', 'groups'));
}
...
edit.blade.php (the view)
...
{!! Form::model($user, ['method' => 'PATCH', 'action' => ['UserController#update', $user->id]]) !!}
...
...
// the form should be binded by the attribute 'group_list' created
// at the second block of 'User.php'
// performing a $user->group_list gets me the correct values
{!! Form::select('group_list[]', $groups, null, [
'class' => 'form-control',
'id' => 'grouplist',
'multiple' => true
]) !!}
...
I did a dummy test in my blade, and have gotten the correct results:
#foreach ($user->group_list as $item)
{{ $item }}
#endforeach
This lists the values that should be selected by default..
I also tried to put $user->group_list as third parameter from the Form::select, but this didnt work ether...
I have no clue what i'm doing wrong.. any hints on this one?
edit
when I do:
public function getGroupListAttribute()
{
//return $this->groups->lists('id');
return [1,5];
}
The item are correctly selected,
now i know i have to grab an array from the collection..
digging deeper.. :)
found it
User.php:
...
public function getGroupListAttribute()
{
return $this->groups->lists('id')->toArray();
}
...
could it be easier?
Nice regards,
Kristof
You shouldn't put null in the selected defaults (3rd) argument.
{!! Form::model($user, ['route' => ['user.update', $user->id]]) !!}
{!! Form::select(
'group_list[]',
$groups,
$user->group_list,
['multiple' => true]
)
!!}

Laravel update method passing through model name instead of ID

I am having an issue with my resource route when calling the update method.
I get this error:
Creating default object from empty value
The 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)
{
$vehicle = Vehicle::find($id);
$vehicle->VRM = $input['VRM'];
$vehicle->make = $input['make'];
$vehicle->model = $input['model'];
$vehicle->description = $input['description'];
$vehicle->save();
}
Route:
Route::resource('/admin/vehicles', 'VehiclesController');
If I print the ID then it shows {vehicle}.
My form is this:
{{ Form::open(['route' => 'admin.vehicles.update', 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}
// input fields etc
{{ Form::close() }}
I think there is something wrong with the form possibly? Since when the error is thrown the URL is:
http://localhost/admin/vehicles/%7Bvehicles%7D
Never had any issues before with using resource routes with CRUD applications and cant see where this is going wrong?
You need the id in update route...
{{ Form::open(['route' => array('admin.vehicles.update', $vehicle->id), 'class' => 'form-horizontal edit-vehicle-form', 'method' => 'PATCH']) }}

Laravel 4 - Username not being passed on in URL

I am trying to get into Laravel 4 and am having a problem with editing users I have created. So far I have controllers, views, and routes to show a user and then edit the user by clicking the "Edit" button but when I click the submit button I keep getting a NotFoundHttpException and the "Crash/Error" orange and white Laravel screen. I did, however, notice that the URL changes from showing the username (ex - public/users/av1/edit - with av1 being the username) to only saying {username} (ex -public/users/{username}/edit). I am still new to Laravel but my thought is that I'm not passing the username along properly but I know that it could also be the Controller or route as well. I have tried removing and changing sections of code and have found that if I remove the code from the Controller I still get a URL with {username} but I at least don't get the "Crash/Errors" screen. If anyone could help explain where I am going wrong it would be very much appreciated!
Here is my view:
#extends('layout.main')
#section('content')
{{ Form::model($user, array('route'=>'user-edit-post')) }}
<div>
{{ Form::label('username', 'Username:')}}
{{ Form::text('username') }}
#if($errors->has('username'))
{{ $errors->first('username') }}
#endif
</div>
<div>
{{ Form::label('password', 'Password:')}}
{{ Form::password('password') }}
#if($errors->has('password'))
{{ $errors->first('password') }}
#endif
</div>
<div>
{{ Form::label('password_confirmation', 'Confirm Password:')}}
{{ Form::password('password_confirmation') }}
#if($errors->has('password_confirmation'))
{{ $errors->first('password_confirmation') }}
#endif
</div>
<div>
{{ Form::submit('Edit User') }}
</div>
#stop
My User Controller functions that relates to editing:
public function getEdit($username){
$user = User::where('username', '=', $username);
if($user->count()) {
$user = $user->first();
return View::make('users.edit')
->with('user', $user);
} else {
return App::abort(404);
}
}
public function postEdit($username){
$validator = Validator::make(Input::all(),
array(
'first_name' => 'required|max:20',
'last_name' => 'required|max:20',
'email' => 'required|max:50|email',
'username' => 'required|max:20|min:3',
'password' => 'required|min:6',
'password_confirmation' => 'required|same:password'
)
);
if($validator->fails()){
return Redirect::route('user-edit')
->withErrors($validator);
} else {
/*Edit User*/
$user = User::whereUsername($username)->first();
$password = Input::get('password');
$user->password = Hash::make($password);
$user->first_name = Input::get('first_name');
$user->last_name = Input::get('last_name');
$user->email = Input::get('email');
$user->username = Input::get('username');
/*password is the field $password is the variable that will be used in the password field*/
if($user->save()){
return Redirect::route('home')
->with('global', 'The password has been changed.');
}
return Redirect::route('home')
->with('global', 'The password could not be changed.');
}
}
And lastly my Routes:
/*Edit users (GET)*/
Route::get('users/{username}/edit', array(
'as' => 'user-edit',
'uses' => 'UserController#getEdit'
));
/*Edit Order (POST)*/
Route::post('/orders/{orders}/edit', array(
'as' => 'order-edit-post',
'uses' => 'OrderController#postEdit'
));
Change
{{ Form::model($user, array('route'=>'user-edit-post')) }}
To
{{ Form::model($user, array('route'=>array('user-edit-post', $user->username))) }}
Your route need additional parameters, so you need supply your parameters with your route name when binding model to form.
Yep, after reading the comment. I found the reason of your trouble here is the redirect in the postEdit function:
Change:
if($validator->fails()){
return Redirect::route('user-edit')
->withErrors($validator);
}
Into
if($validator->fails()){
return Redirect::route('user-edit', $username)
->withErrors($validator);
}
Again, your route need parameters. When the validation fails, you have been redirected to a wrong URL.

Categories