Related
So, I have three tables: farms, crops and harvests. When I want to register a harvest on my web page, I use pluck to display a dropdown list for farms and another dropdown list for crops in the same view. The thing is, when I select a farm from the dropdown, I can still see and select crops related to other farms, and das not good. How can I list only crops related to the previously selected farm? My HarvestController looks like this:
public function create()
{
$farms = Farm::where('users_id', Auth::id())->with('alias')->pluck('alias', 'id');
$crops = Crop::where('users_id', Auth::id())->pluck('id', 'id');
return view('harvest.create')
->with('farms', $farms)
->with('crops', $crops);
}
The relationships in models:
class Farm extends Model
{
public function crops(){
return $this->hasMany('App\Crop');
}
}
class Crop extends Model
{
public function farm(){
return $this->belongsTo('App\Farm');
}
public function harvest(){
return $this->hasOne('App\Harvest');
}
}
And the view looks like this:
<div class="form-group">
{!! Form::label('farms_id', 'Farm') !!}
{!! Form::select('farms_id', $farms, null, ['class' => 'form-control', 'required']) !!}
</div>
<div class="form-group">
{!! Form::label('crops_id', 'Crop ID') !!}
{!! Form::select('crops_id', $crops, null, ['class' => 'form-control', 'required']) !!}
</div>
Any help will be highly appreciated, constructive roasting too
I am working on a laravel 5.2 project. I am referencing category_id from Posts.
My Post model looks like
class Post extends Model
{
protected $fillable=['category_id '];
public function category(){
return $this->belongsTo('App\category');
}
}
Also, my form looks like
<div class="form-group">
{!! Form::label('category_id','Category:') !!}
{!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}
</div>
My table data
#foreach($posts as $post)
<tr>
<td>{{$post->category['name']}}</td>
</tr>
#endforeach
The Problem is, whenever I create a new post, the category name doesn't save in the database nor does it show on the front end.
My Post Schema table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->index()->unsigned()->nullable();
});
Even when I dd() the input field for the category id on the post table, its empty. Can someone help me with this, it's making me go crazy. Thanks
I am using a resource contoller,heres my create request controller
public function store(Request $request)
{
$user=Auth::user();
$input = $request->all();
Post::create($input);
return redirect('admin/posts');
}
It is because the fillable field only is the category_id try to add the category name field on your fillable like this.
//this are the fields that is fillable
protected $fillable=['category_id','name'];
With this the category name field will be able to catch and save data.
In continuation of my comment. Your migration should look like this.
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->index()->unsigned()->nullable();
$table->string('category_name')->nullable();
});
Your model,
class Post extends Model
{
protected $fillable=['category_id','category_name'];
}
Form
<div class="form-group">
{!! Form::label('category_id','Category:') !!}
{!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}
{!! Form::input('category_name',old('category_name'),['class'=>'form-control', 'id' => "input_name"]) !!}
</div>
and lastly your table data should look like this.
#foreach($posts as $post)
<tr>
<td>{{$post->category_name}</td>
</tr>
#endforeach
Double check your fillable and input fields if they are the same.
your given concern you only show this one.
<div class="form-group">
{!! Form::label('category_id','Category:') !!}
{!! Form::select('category_id', $categories, '1',['class'=>'form-control']) !!}
</div>
how about the other fields. We expect you already had this on your form too.
<div class="form-group">
{!! Form::label('input_name','Name:') !!}
{!! Form::input('name',old('name'),['class'=>'form-control', 'id' => "input_name"]) !!}
</div>
In your store method it should look like this
$new_post = new Post;
$new_post->category_id = Input::get(‘category_id’);
$new_post->name = Input::get(‘name’);
$new_post->save();
Just in case you’re not using the fill method of $request
In order to access your relationship's attributes, you should do:
$post->comment->name;
And try to use 'fill()' when saving
$post = new Post;
$post->fill($request->all());
$post->save();
I fixed the error using this in my form.
{!! Form::select('category_id', [''=>'choose Categories'] + $categories,['class'=>'form-control']) !!}
and this on my table.
<td>{{$post->category['name']}}</td>
Thanks all for your effort.
I'm trying to save to database my data, but I get error "Array to string conversion". It's my controller
public function create()
{
$listapacjentow = Patient::pluck('nazwisko','id');
return view('leczenie.create')->with('listapacjentow', $listapacjentow);
}
public function store(CreateOperacjaRequest $request)
{
$operacja = new Operacja($request->all());
$PacjenciIds = $request->input('PacjentList');
$operacja->user()->associate($PacjenciIds);
$operacja->save();
return redirect('leczenie');
}
It's my form
<div class="form-group">
<div class="col-md-4 control-label">
{!! Form::label('PacjentList','Wybierz pacjenta:') !!}
</div>
<div class="col-md-6">
{!! Form::select('PacjentList[]', $listapacjentow); !!}
</div>
When I return $operacja is everything ok, but I can't save it to database
Try with this approch in your store method.
$operacja = new Operacja($request->all());
$operacja->user_id = $request->input('PacjentList.0');
$operacja->save();
$operacja->user()->saveMany($patients);
If you want to associate only one user with Operacja, do this:
{!! Form::select('user_id', $listapacjentow); !!}
$operacja = Operacja::create($request->all());
If you want to add many users to the Operacja, you'll need to revert one to many relationship, so User will have operacja_id and Operacja will not have user_id.
If you want to make Operacja have many users and a user could have many Operacja, use many to many relationship.
I have made the following migration in Laravel:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class QualityCheckTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('quality_check', function (Blueprint $table) {
$table->increments('id');
$table->boolean('favicon');
$table->boolean('title');
$table->boolean('image-optimization');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('quality_check');
}
}
I have the following controller method that runs when the form in the frontEnd is submitted:
public function store(CreateArticleRequest $request) {
// $input = Request::all();
Article::create($request->all());
return redirect('articles');
}
My form looks like , so:
{!! Form::open([ 'action' => 'QualityCheckController#validateSave' , 'class'=>'quality-check-form' , 'method' => 'POST' ]) !!}
<div class="input-wrpr">
{!! Form::label('favicon', 'Favicon') !!}
{!! Form::checkbox('favicon', 'value' ); !!}
</div>
<div class="input-wrpr">
{!! Form::label('title', 'Page Title') !!}
{!! Form::checkbox('title', 'value'); !!}
</div>
<div class="input-wrpr">
{!! Form::label('image-optimization', 'Image Optimization') !!}
{!! Form::checkbox('image-optimization', 'value'); !!}
</div>
{!! Form::submit('Click Me!') !!}
{!! Form::close() !!}
So when the method runs the values of the checkboxes are saved to the database.
As of now , all entries are showing as 0 , Like so:
Now how to make it such that when the checkbox is checked , 1 is saved and when the checkbox is left unchecked the value in is left at 0 ??
When a checkbox is ticked, it's value is present in the posted data. When it is unticked, it's value is not present. This means when you do $request->all() it will contain only the checkboxes that were ticked. So in your case, if you leave all 3 checkboxes unticked, your $request->all() could yield an empty array (Assuming that no other fields are posted).
When you run Article::create($request->all()); with no checkboxes ticked you would be essentially passing it an empty set of data, which means that your database is going to be populated with the default values for the fields that you didn't provide.
Since you didn't provide a default in your migration, MySQL is going to guess what the default should be based on the field type, which in the case of a boolean will be 0. You may see some warnings/errors though.
There are loads of ways you can get this to work so that a 1 is saved when a checkbox is ticked or 0 when it is not ticked. The easiest way in your scenario would be to set the value of each checkbox to be 1 and explicitly set up default values in your migration i.e.
Migration:
$table->boolean('favicon')->default(0);
Form:
{!! Form::checkbox('title', '1'); !!}
This way, when the title checkbox is ticked, your $request->all() returns an array containing an item 'title' => '1' and this is saved in your database. All of the unticked boxes are defaulted to 0 as per your migration.
I prefer however to be more explicit when I write my method for handling the store.
$article = new Article();
$article->title = $request->has('title'); // Will set $article->title to true/false based on whether title exists in your input
// ...
$article->save();
Have you remembered to pass them in the $fillable array in the Article Model?
protected $fillable = [
'favicon',
'title',
'image-optimization'
];
and as a sidenote to the checkboxes thing. You can just make a hidden input with the same name, and make it false. That way, if the checkbox is unchecked, it will be false, but if it is checked, it will return true, as it is the last value:
<div class="input-wrpr">
{!! Form::label('title', 'Page Title') !!}
{!! Form::hidden('title', false); !!}
{!! Form::checkbox('title', 'value'); !!}
</div>
With VUE you can do it like this:
Add this line to your table
$table->boolean("image-optimization")->default(0);
Add this to your model, it will modify the value inserted in the database
protected $casts = ['image-optimization' => 'boolean'];
You don't have to modify the request with this method
Docs: https://laravel.com/docs/8.x/eloquent-mutators
You can check if checkbox is set with isset($request->favicon) or empty($request->favicon) or ->has('favicon'):
public function store(CreateArticleRequest $request) {
foreach (['favicon', 'title', 'image-optimization'] as $box) {
$request($box) = $request->has($box);
}
Article::create($request->all());
return redirect('articles');
}
I want to create a select box like the one below using illuminate\html :
<select>
<option value="$item->id">$item->name</option>
<option value="$item->id">$item->name</option>
</select>
In my controller I tried this:
public function create()
{
$items = Items::all(['id', 'name']);
return view('prices.create', compact('id', 'items'));
}
And in my view this:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
{!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>
The issue is that instead of $item->name is displaying all the info of the entity.
Laravel provides a Query Builder with lists() function
In your case, you can replace your code
$items = Items::all(['id', 'name']);
with
$items = Items::lists('name', 'id');
Also, you can chain it with other Query Builder as well.
$items = Items::where('active', true)->orderBy('name')->lists('name', 'id');
source: http://laravel.com/docs/5.0/queries#selects
Update for Laravel 5.2
Thank you very much #jarry. As you mentioned, the function for Laravel 5.2 should be
$items = Items::pluck('name', 'id');
or
$items = Items::where('active', true)->orderBy('name')->pluck('name', 'id');
ref: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0 -- look at Deprecations lists
Laravel >= 5.3 method lists() is deprecated use pluck()
$items = Items::pluck('name', 'id');
{!! Form::select('items', $items, null, ['class' => 'some_css_class']) !!}
This will give you a select box with same select options as id numbers in DB
for example if you have this in your DB table:
id name
1 item1
2 item2
3 item3
4 item4
in select box it will be like this
<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
I found out that pluck now returns a collection, and you need to add ->toArray() at the end of pluck...so like this: pluck('name', 'id')->toArray();
Just change your controller to the following:
public function create()
{
$items = Subject::all(['id', 'name']);
return View::make('your view', compact('items));
}
And your view to:
<div class="form-group">
{!! Form::Label('item', 'Item:') !!}
<select class="form-control" name="item_id">
#foreach($items as $item)
<option value="{{$item->id}}">{{$item->name}}</option>
#endforeach
</select>
</div>
Hope this will solve your problem
Controller
$campaignStatus = Campaign::lists('status', 'id');
compact('campaignStatus') will result in [id=>status]; //example [1 => 'pending']
return view('management.campaign.index', compact('campaignStatus'));
View
{!! Form::select('status', $campaignStatus, array('class' => 'form-control')) !!}
In your controller, add,
public function create()
{
$items = array(
'itemlist' => DB::table('itemtable')->get()
);
return view('prices.create', $items);
}
And in your view, use
<select name="categories" id="categories" class="form-control">
#foreach($itemlist as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
#endforeach
</select>
In select box, it will be like this,
<select>
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
...
</select>
Laravel use array for Form::select. So I passed array like below:
$datas = Items::lists('name', 'id');
$items = array();
foreach ($datas as $data)
{
$items[$data->id] = $data->name;
}
return \View::make('your view', compact('items',$items));
In your view:
<div class="form-group">
{!! Form::label('item', 'Item:') !!}
{!! Form::select('item_id', $items, null, ['class' => 'form-control']) !!}
</div>
I have added toArray() after pluck
$items = Item::pluck('name', 'id')->toArray();
{{ Form::select('item_id', [null=>'Please Select'] + $items) }}
Laravel 5.3 use pluck($value, $key )
$value is displayed in your drop list and $key is id
controller
$products = Product::pluck('name', 'id');
return view('main.index', compact('products'));
view
{{ Form::select('id', $products, null, ['class' => 'form-control']) }}
Laravel 5.*
In your controller:
$items= Items::pluck('name', 'id')->toArray();
return view('your view', compact('items', $items));
In your view:
{{ Form::select('organization_id', $items, null, []) }}
Sorry for the late reply
Obviously lists method has been deprecated in Laravel, but you can use the pluck method.
For Eg:
Laravel 5.7
public function create()
{
$countries = Country::pluck('country_name','id');
return View::make('test.new')->with('countries', $countries);
}
and in the view if you are FORM components just pass as
{{ Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}
if will generate the dropdown
but i have a situation to show that select country as the first option and as null value
<option value="" selected="selected">--Select Country--</option>
so I have referred to
https://stackoverflow.com/a/51324218/8487424
and fixed this, but in later times if I want to change this I hate being changing it in the view
So have created the helper function based on https://stackoverflow.com/a/51324218/8487424 and placed in the Country Model
public static function toDropDown($tableName='',$nameField='',$idField='',$defaultNullText='--Select--')
{
if ($idField == null)
{
$idField="id";
}
$listFiledValues = DB::table($tableName)->select($idField,$nameField)->get();
$selectArray=[];
$selectArray[null] = $defaultNullText;
foreach ($listFiledValues as $listFiledValue)
{
$selectArray[$listFiledValue->$idField] = $listFiledValue->$nameField;
}
return $selectArray;
}
and in controller
public function create()
{
$countries = Country::toDropDown('countries','name','id','--Select Country--');
return View::make('test.new')->with('countries', $countries);
}
and finally in the view
{{ Form::select('testname',$countries,null,['class' => 'required form-control select2','id'=>'testname']) }}
and the result is as expected, but I strongly recommend to use pluck() method
For Laravel 5 :
$items = Items::lists('name', 'id');
Push an item onto the beginning of the collection.
$items->prepend($value, $key = null);
To populate the drop-down select box in laravel we have to follow the below steps.
From controller we have to get the value like this:
public function addCustomerLoyaltyCardDetails(){
$loyalityCardMaster = DB::table('loyality_cards')->pluck('loyality_card_id', 'loyalityCardNumber');
return view('admin.AddCustomerLoyaltyCardScreen')->with('loyalityCardMaster',$loyalityCardMaster);
}
And the same we can display in view:
<select class="form-control" id="loyalityCardNumber" name="loyalityCardNumber" >
#foreach ($loyalityCardMaster as $id => $name)
<option value="{{$name}}">{{$id}}</option>
#endforeach
</select>
This key value in drop down you can use as per your requirement.
Hope it may help someone.
Many has been said already but keep in mind that there are a times where u don't want to output all the records from the database into your select input field ..... Key example I have been working on this school management site where I have to output all the noticeboard categories in a select statement. From my controller this is the code I wrote
Noticeboard:: groupBy()->pluck('category')->get();
This way u get distinct record as they have been grouped so no repetition of records
I was trying to do the same thing in Laravel 5.8 and got an error about calling pluck statically. For my solution I used the following. The collection clearly was called todoStatuses.
<div class="row mb-2">
<label for="status" class="mr-2">Status:</label>
{{ Form::select('status',
$todoStatuses->pluck('status', 'id'),
null,
['placeholder' => 'Status']) }}
</div>
Try this one. Without using controller
{{ Form::select('apartment_id', \App\Apartment::all()->pluck('apartment_name', 'apartment_id')->toArray(), null,['class'=>'select2 form-control', 'multiple'=>'multiple','required','id' => 'apartment_id']) }}