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]
)
!!}
Related
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>
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?
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?
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']) }}
I have a simple task list project under Laravel.
When I click a checkbox it does not show a checked condition. (The second item is in the true condition in the database and thus shows checked. I cannot uncheck this item) I have searched for an answer to why on the net but cannot find a solution or reason.
Code:
home.blade.php (in views folder) -
#extends('layouts.main')
#section('content')
<h1>Tasks</h1>
<ul>
#foreach ($items as $item)
<li>
{{ Form::open() }}
<input type="checkbox" onClick="this.form.submit()" {{ $item->done ? 'checked' : '' }}>
<input type="hidden" name="id" value="{{ $item->id }}">
{{ $item->name }}
{{ Form::close() }}
</li>
#endforeach
</ul>
#stop
HomeController.php (inControllers folder) -
<?php
class HomeController extends BaseController {
public function getIndex() {
$items = Auth::user()->items;
return View::make('home', array(
'items' => $items
));
}
public function postIndex() {
$id = Input::get('id');
$user_id = Auth::user()->id;
$item = Item::findOrFail($id);
if($item->owner_id == $userId) {
$item->mark();
}
return Redirect::route('home');
}
}
Item.php (in models folder) -
<?php
class Item extends Eloquent {
public function mark() {
$this->$done = $this->done ? false : true;
$this->save();
}
}
routes.php -
<?php
Route::get('/', array('as' => 'home', 'uses' => 'HomeController#getIndex'))->before('auth');
Route::post('/', array('uses' => 'HomeController#postIndex'))->before('csrf');
Route::get('/login', array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login', array('uses' => 'AuthController#postLogin'))->before('csrf');
in your code, you never update the model's done value. i assume, you want to change it with the post method. so you'd need to take the value from the checkbox name (e.g. Input::get('box-ID'))
you could also create a checkbox using the form class:
// public function checkbox($name, $value = 1, $checked = null, $options = array())
{{ Form::checkbox('name', 'value', true, ['onClick' => 'alert(123)']) }}
reference: Formbuilder -> checkbox
You should modify your form like this. It works me I hope will work for you also.
{{ Form::open(['route' => ['items.update', $items->id], 'class' => 'form-inline', 'method' => 'put']) }}
Thanks