I have User Role models defined in a many-to-many relationship. When creating user I have a multiple select box to pick roles for specific user:
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
<label for="roles">Roles</label>
{!! Form::select('roles[]',$roles, null,['class' => 'form-control selectpicker','multiple' => 'true']) !!}
</div>
</div>
This is a form which is shared in both create and edit methods, but for edit it is like this:
{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
#include('patients.partials.form')
{!! Form::close()!!}
When I try to edit user with roles, no roles get selected...this is the controller
public function edit(User $user)
{
$clinics = Clinic::pluck('name', 'id');
$roles = Role::pluck('display_name', 'id');
$states = State::pluck('name', 'id');
$cities = City::pluck('name', 'id');
return view('users.edit', compact('user', 'clinics', 'states', 'cities', 'roles'));
}
EDIT:
I handle update like this:
public function update(Request $request, User $user)
{
if ($request->has('password'))
$user->update($request->except('password_confirmation'));
else
$user->update($request->except('password', 'password_confirmation'));
$user->roles()->sync($request->roles);
return redirect('users')->with('status', 'User Updated!');
}
Part of the request dump:
"roles": [
"1",
"4"
],
"first_name": "xy",
"last_name": "yx",
The third parameter of the form select takes the selected array of item. Make the following changes for your selected roles to show up when you edit.
// Pass the current user roles
public function edit(User $user)
{
$userRoles = $user->roles->pluck('id');
$clinics = Clinic::pluck('name', 'id');
$roles = Role::pluck('display_name', 'id');
$states = State::pluck('name', 'id');
$cities = City::pluck('name', 'id');
return view('users.edit', compact('user', 'userRoles', 'clinics', 'states', 'cities', 'roles'));
}
// Pass the selected list of roles
{!! Form::model($patient, ['route' => ['patients.update', $patient->id], 'method' => 'PUT']) !!}
#include('patients.partials.form', ['selected' => $userRoles])
{!! Form::close()!!}
// Check if a selected value is given and use it. This makes it reusable with create and edit.
{!! Form::select('roles[]', $roles, isset($selected) ? $selected : null, [
'class' => 'form-control selectpicker',
'multiple' => 'true'
]) !!}
Related
I've returned a value from my controller.When I use the value in my view blade,it shows Syntax error
Here is my code,
Controller
public function edit($id)
{
$a = DB::select('select * from users where id = "$pid"', array(1));
return view('sample', ['users' => $a]);
}
And in View blade,
{!! Form::Id('Id', $value = {{$a}}, ['class' => 'form-control1', 'placeholder' => 'Id']) !!}
How 'ld I change my code,Help me
You can do it wit eloquent like this :
public function edit($id)
{
$a = User::find($id);
return view('sample', ['user' => $a]);
}
And on top of your controller add the import :
use App\User;
In the view it's user that will be seen not a so :
<input type="text" name="id" value="{{ $user->id }}" />
{!! Form::email('email', $user->email, ['class' => 'form-control1', 'placeholder' => 'email']) !!}
so how can I make a default checked/unchecked checkbox, with values from the data base? I'm using Form model from laravel collective and my checkbox field is this:
Form::model($role, ['route' => ['the_route', $role->slug], 'method' => 'patch'])
#foreach ($permissions as $permission)
Form::checkbox('permission['.$permission->slug.']', 'true', null, ['class' => 'square'])
#endforeach
Form::close()
The thing is that $role->permissions returns an array like this:
array:3 [
"dashboard.view" => "false"
"user.view" => "true"
"user.edit" => "false"
]
The third parameter is a boolean $checked, so you may write it like this:
Form::model($role, ['route' => ['the_route', $role->slug], 'method' => 'patch'])
#foreach ($permissions as $slug => $value)
Form::checkbox('permission['.$slug.']', 'true', (bool) $value, ['class' => 'square'])
#endforeach
Form::close()
Lavel Collective have one intriguing resource that is not documented, as least I never found it in any site. Name your checkbox with them same name that you gave for relation between your two models, like "permissions", and then Laravel Collective will check all input that are in that relation. In your specific case, $role->permission should return an model, not array, like normally is in any Laravel app.
Check an sample code:
{!! Form::model($role, ['route' => ['roles.update', $user->id], 'method' => 'put']) !!}
<div class="row form-group">
#foreach($permissions as $permission)
<div class="col-sm-3">
{!! Form::checkbox('permissions[]', $permission->id) !!}
{!! Form::label('permissions', $permission->name) !!}
</div>
#endforeach
</div>
{!! Form::close() !!}
// Role model
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany(Permission::class, 'permission_role');
}
}
// Permission model
class Permission extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class, 'permission_role');
}
}
I'm trying to populate the data to edit form. Here's my model
public function EditBatch($id,$request){
$data= DB::table('in_batch')
->where('id', $id)
->update(array(
'id'=>$request->input('id'),
'file_name' => $request->input('file_name'),
'batch_type' => $request->input('batch_type'),
'activity_type' => $request->input('activity_type'),
'schedule_time' => $request->input('schedule_time'),
'predecessor' => $request->input('predecessor'),
'priority' => $request->input('priority'),
'batch_remark'=>$request->input('batch_remark'),
'approved_by' => Auth::user()->id,
'approved_on'=>date("Y-m-d H:i:s"),
));
return $data;
}
here's my controller
public function edit($id){
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$batch = new ManageBatch();
$batch->GetBatchById($id);
return view('batch.edit', array('batch'=>$batch,'batch_type'=>$batch_type));
}
here's my view
{!! Form::open (array('url' => array('batch/update',$batch->id), 'class' => 'form-horizontal', 'method' => 'post','id'=>'editbatch')) !!}
<div class="form-group">
{!! Form::label('batch_id', 'batch_id',array('class'=>'col-md-4 control-label')) !!}
<div class="col-md-6">
{!! Form::text('batch_id',$batch->id,array('class'=>'form-control','id'=>'batch_id')) !!}
</div>
</div>
{!! Form::close() !!}
when i trying to load the data to the view as above error is displaying
Undefined property: App\Models\Batch\ManageBatch::$id (View: C:\wamp\www\hutch-in-portal\resources\views\batch\edit.blade.php)
how to solve this ?
thankyou
well i found a solution and the mistake was in the controller method
public function edit($id)
{
$obatch = new BatchType();
$batch_type = $obatch->GetBatchTypeDropDown();
$ouser = new ManageBatchUser();
$batch_user = $ouser->GetUserDropDown();
$batch = new ManageBatch();
$batch_details=$batch->GetBatchById($id);
return view('batch.edit',array('batch_details'=>$batch_details[0],'batch_type'=>$batch_type,'batch_user'=>$batch_user));
}
since i'm passing a single row to the view . i must add the index [0] in return. finally it worked
UPDATED. I have one form that adds data to two different tables (Articles & Deals). An Article has many deals. A deal has one Article. There are multiple deals with different dealnames that the user inputs on the create and edit form. I can create an Article with many Deals fine, and I can populate the edit form with the data from the Deals table, but when I update my 'deals' table using the Articles Controller it just updates every 'dealname' with the last dealname that is inputted. I only need to update the 'dealname' column as all other columns will stay the same. If I remove the dealname/deals part of the form I can update fine.
How can I update the deals table correctly? I know I have to change something in the update function of my Articles Controller.
I'm using Laravel 5.
The Articles Table has: id, title, image, description, address. The Deals table has: id, dealname, article_id, dayID.
Articles Controller- Update
public function update(ArticleRequest $request, $id)
{
$article = Article::find($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->fill($request->input())->save();
//Get IDs of deals to be updated.
$dealID = Deal::all()->lists('dealname', 'id');
$dealID = $dealID->toArray();
$dealID = array_keys($dealID);
$deals = $request->input('dealname');
foreach($deals as $deal) {
Deal::whereIn('id', $dealID)->update(['dealname' => $deal]);
}
return redirect('/');
}
Form
{!! Form::model($article, ['route' => ['articleUpdate_path', $article->id], 'files' => true, 'method' => 'PATCH']) !!}
{!! Form::label('title','TITLE') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
{!! $errors->first('title','<p class="error">:message</p>')!!}
{!! Form::label('image','PHOTO') !!}
{!! Form::file('image', null, ['class' => 'form-control']) !!}
{!! Form::label('description','DESCRIPTION') !!}
{!! Form::textarea('description', null, ['class' => 'form-control']) !!}
#foreach ($article->deals as $deal)
#if($deal->dayID == '1' )
{!! Form::label('dealname','Monday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '1']) !!}
#endif
#if($deal->dayID == '2' )
{!! Form::label('dealname','Tuesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '2']) !!}
#endif
#if($deal->dayID == '3' )
{!! Form::label('dealname','Wednesday') !!}
{!! Form::text('dealname[]', $deal->dealname, null, ['class' => 'form-control', 'id' => '3']) !!}
#endif
#endforeach
{!! Form::label('address','ADDRESS') !!}
{!! Form::text('address', null, ['class' => 'form-control']) !!}
{!! Form::close() !!}
Articles Controller -Store
public function store(ArticleRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$article = ($request->except(['image']));
$article['image'] = $image_name;
$article = Article::create($article);
// GET INPUT
$deals = $request->input('dealname');
// GET ID OF ARTICLE
$articleID = $article->id;
// N is the day id that increments
$n = 1;
foreach($deals as $deal) {
Deal::create(['dealname' => $deal, 'article_id' => $articleID, 'dayID' => $n++]);
}
return redirect()->route('articles_path');
}
ARTICLE MODEL
class Article extends Model
{
public function deals()
{
return $this->hasMany('App\Deal');
}
protected $fillable = array('title', 'photo', 'description', 'address');
}
DEAL MODEL
class Deal extends Model
{
public function article()
{
return $this->belongsTo('App\Article')->withTimestamps();
}
protected $fillable = array('dealname', 'article_id', 'dayID');
}
I'm really not sure to fully understand your question, but would something like that could be useful in your case:
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
$article->deals->where('dayID',1)->first()->dealname = $request->input('dealname')[0];
$article->deals->where('dayID',1)->first()->save();
$article->deals->where('dayID',2)->first()->dealname = $request->input('dealname')[1];
$article->deals->where('dayID',2)->first()->save();
$article->deals->where('dayID',3)->first()->dealname = $request->input('dealname')[2];
$article->deals->where('dayID',3)->first()->save();
}
Are they only those 3 dayIds you are using in your form?
EDIT:
You could also try with a for loop. This is untested code, so you might want to optimize it :)
public function update(ArticleRequest $request, $id) {
$article = Article::findOrFail($id);
if( $request->hasFile('image') ){
// photo saving stuff.
}
$article->update($request->all());
for($i = 0; $i < sizeof($request->input('dealname')); $i++) {
$article->deals->where('dayID',($i + 1))->first()->dealname = $request->input('dealname')[$i];
$article->deals->where('dayID',($i + 1))->first()->save();
}
}
I'm trying to update my records in my ProjectsController, however when I try to route to the controller I am getting thrown the following error:
ErrorException
Undefined variable: project
I'm not too sure as too what I've done wrong and I'm sorry to overload you guys with code but not sure where the problem lies. Bit of a newbie with Laravel so would be great to get some help!
The function it is referring to is the following:
public function edit($id)
{
// get the project
$project = Project::find($project);
// show the edit form and pass the project
return View::make('projects.edit')
->with('project', $project);
}
My update function is as follows:
public function update($id)
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'project_name' => 'required',
'project_brief' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('projects/' . $id . '/edit')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
// store
$project = Project::find($id);
$project->project_name = Input::get('project_name');
$project->project_brief = Input::get('project_brief');
$project->save();
// redirect
Session::flash('message', 'Successfully updated!');
return Redirect::to('profile');
}
}
I route to the Project Controller as follows:
Route::group(["before" => "auth"], function()
{
Route::any("project/create", [
"as" => "project/create",
"uses" => "ProjectController#create"
]);
Route::any("project/{resource}/edit", [
"as" => "project/edit",
"uses" => "ProjectController#edit"
]);
Route::any("project/index", [
"as" => "project/index",
"uses" => "ProjectController#index"
]);
Route::any("project/store", [
"as" => "project/store",
"uses" => "ProjectController#store"
]);
Route::any("project/show", [
"as" => "project/show",
"uses" => "ProjectController#show"
]);
});
My form is as follows:
<h1>Edit {{ $project->project_name }}</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::model($project, array('route' => array('projects.update', $project->id), 'method' => 'PUT')) }}
<div class="form-group">
{{ Form::label('project_name', 'Project Name') }}
{{ Form::text('project_name', null, array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('Project Brief', 'Project Brief') }}
{{ Form::textarea('project_brief', null, array('class' => 'form-control', 'cols' => '100')) }}
</div>
{{ Form::submit('Edit the Project!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
Looks like you misplaced $project in find(), should be $id here:
public function edit($id)
{
// get the project
$project = Project::find($id);
// show the edit form and pass the project
return View::make('projects.edit')
->with('project', $project);
}