Laravel 5.3 select pluck method - php

Controller method:
public function edit($id){
$match2 = Match::pluck('team_a_id', 'id');
return view('admin.accept.edit', compact('match2'));
}
And view file:
{{ Form::select('matches_id', $match2, null, ['class' => 'form-control']) }}
And my table:
Table from model Match (table name: matches):
Table from model Team (table name: teams):
Table teams is connected (references) with table matches( team_a_id and team_b_id is connected with table teams). The select method with view returned me only ID with tables:
I need have team_name with table teams not id.
When I change method pluck:
$match2 = Match::pluck('id', 'id');
And view:
{{ Form::select('matches_id', Team::find($match2)->team_a_id." vs. ".Team::find($match2)->team_b_id, null, ['class' => 'form-control']) }}
Laravel returned error:
Invalid argument supplied for foreach() (View:
C:\xampp\htdocs\football\football\resources\views\admin\accept\edit.blade.php)
This is metohd edit so I must have highlighted record that was previously selected.

Ok I repair this. I write method:
public function edit($id){
$match = Match::select()->orderBy('updated_at', 'asc')->get();
$selectedMatch = DB::table('usermatches')->find($id)->matches_id;
return view('admin.accept.edit', compact('match', 'selectedMatch'));
}
And view:
<select name="matches_id" id="matches_id" class="form-control selectpicker" data-live-search="true" data-size="5">
<option value=0>Wybierz wydarzenie</option>
#foreach($match as $role)
<option value="{{ $role->id }}" {{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}>
{{ Team::find($role->team_a_id)->team_name }} vs. {{ Team::find($role->team_b_id)->team_name }} ({{$role->date}}; <?php echo date('G:i',strtotime($role->time)); ?> | Liga {{ League::find($role->league_id)->name }} | {{ Sport::find($role->sport_id)->name }})
</option>
#endforeach
</select>
In model view I compare id with two tables and it working ;)
{{ $selectedMatch == $role->id ? 'selected="selected"' : '' }}

Related

Determine selected options based on many-to-many relationship

I have three tables: products, categories and category_product.
In my edit form page I'm displaying the categories and subcategories values in a select box.
The chosen category options are saved in the pivot table category_product. This table has product_id and category_id.
Here's my code.
Product model
public function category() {
return $this->belongsToMany('App\Models\Category');
}
Category model:
public function products()
{
return $this->belongsToMany(Product::class);
}
edit product page view:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}">{{ $parentCategory->name }}</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
subcats-select view
#foreach($subcategories as $subcategory)
<option value="{{ $subcategory->id }}">---{{ $subcategory->name }}</option>
#if(count($subcategory->subcategory))
#include('includes.subcats-select',['subcategories' => $subcategory->subcategory])
#endif
</div>
#endforeach
How can I put "selected" attribute to the chosen category options, so when I edit the page to apply the changes properly?
You can get pivot table columns the following way:
Product model
public function category() {
return $this->belongsToMany('App\Models\Category')->withPivot('selected');
}
edit product page View:
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}" selected="{{ $parentCategory->pivot->selected }}">
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>
EDIT: While the above answer might be helpful for others, it doesn't answer the question. So here's my second try after some clarification in the chat.
<select name="category_id[]" class="form-control" multiple size = 10>
#foreach ($parentCategories as $parentCategory)
<option value="{{ $parentCategory->id }}"{{ $product->category->contains($parentCategory->id) ? 'selected' : '' }}>
{{ $parentCategory->name }}
</option>
#if(count($parentCategory->subcategory))
#include('includes.subcats-select',['subcategories' => $parentCategory->subcategory])
#endif
#endforeach
</select>

Getting selected option on edit form in laravel 6

i want to edit user profile which has a country, country field is a select option, i want to get a user's country value in select field, i tried the answer in stack but it didn't work for me knowing there is relationship between user and country belongsTo hasMany.
edit.blade.php
<select id="country" name="country_id" class="form-control" >
<option value="" selected disabled>Select</option>
#foreach($countries as $country)
<option value="{{$country->id}} {{ $country->id == $users->country_id ? 'selected' : '' }}"> {{ $country->name }}</option>
#endforeach
</select>
usersController.php
public function edit($id)
{
$users = Auth::user();
$countries = Country::all();
return view('users.edit')->with([
'users' => $users,
'countries' => $countries
]);
}
Instead of this:
<option value="{{$country->id}} {{ $country->id == $users->country_id ? 'selected' : '' }}"> {{ $country->name }}</option>
I believe you want this:
<option value="{{$country->id}}"{{ $country->id == $users->country_id ? ' selected' : '' }}> {{ $country->name }}</option>

Cannot add or update a child row laravel 5.4 many to many relation

in many to many join i get this error :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(laravel.posts_tag, CONSTRAINT posts_tag_tag_id_foreign FOREIGN
KEY (Tag_ID) REFERENCES Tag (ID) ON DELETE CASCADE) (SQL: insert
into Posts_Tag (Posts_ID, Tag_ID) values (26, Tag num 2))
my controller :
public function Share(Request $request)
{
$posts = Posts::create($request->all());
$posts->tags()->attach(Input::get('Tag'));
return $posts;
return Redirect()->back();
}
my model :
public function tags()
{
return $this->belongsToMany('App\Tag', 'Posts_Tag', 'Posts_ID', 'Tag_ID');
}
view :
{{ Form::open(array('url'=>'post')) }}
{{ Form::label('Title') }} : {{ Form::text('Title') }}
<br>
{{ Form::label('Content') }} : {{ Form::textarea('Content') }}
<br>
{{ Form::label('Tag :') }}
<select name="Tag" id="Tag" class="Tag">
#foreach($tag as $tag)
<option>{{ $tag->Tag }}</option>
#endforeach
</select>
<br>
{{ Form::submit('Share Post') }}
{{ Form::close() }}
Because you are not passing any tag id, fill the option's value
<select name="tags" id="Tag" class="Tag">
//tags is a better name for collection of tgas
#foreach($tags as $tag)
<option value='{{$tag->id}}'>{{ $tag->Tag }}</option>
#endforeach
</select>
And in your controller
$post->tags()->attach($request->tags);
You can't use actual tag names with attach(). Because you're passing name instead of ID, you need to get tag ID first:
$post = Posts::create($request->all());
$tagId = Tag::where('name', $request->tag)->value('id');
$post->tags()->attach(tagId);

laravel 5.4 form dropdown from database

I want to fetch drop down option value & name from database, to do that my controller code is
$roles = Role::pluck('role','user_id');
return view('users.add_role',compact('roles'));
to fetch this data from drop down list my view file code is
<select name="role" class="form-control" >
#foreach($roles as $role)
<option value="{{ $role->user_id }} "> {{ $role->role }} </option>
#endforeach
</select>
but it says error
Trying to get property of non-object (View: C:\xampp\htdocs\auth2\resources\views\users\add_role.blade.php)
if i just only use
<select name="role" class="form-control" >
#foreach($roles as $role)
<option value="{{ $role }} "> {{ $role }} </option>
#endforeach
</select>
then it shows role column of the table, but it not pass option value to database. so what is the correct way to generate option value & name from database?
Your $roles variable containt an array which is looks like
[0] => 'your_role'
[1] => 'your_role'
Where is 0 and 1 index is user_id. So your user_id is set as an index of your $roles array. Simply do it dd($roles) and check the output. $key as $role will work. Where $key will containt the user_id.
#foreach($roles as $key => $role)
<option value="{{ $key }} "> {{ $role }} </option>
#endforeach
I use laravel collective package to generate dropdown list much more easier,
you can do things like, on your blade template and it will render the list for you
{{ Form::select('role', $role )) }}

Repopulate Laravel Input::old() on Form::select

I can't manage to repopulate a Select field input after a query, using Laravel 4:
// Route
Route::get('blog', 'BlogController#getPosts');
// BlogController
public function getPosts()
{
$posts = Post::where('category_id', Input::get('category'))->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, Input::old('category')) }}
{{ Form::close() }}
I managed to make it work this way, but it's not the best practice
<select name="category" id="category">
<option value="1" {{ (Input::get('category') == 1) ? 'selected="selected"' : null }}>Category 1</option>
<option value="2" {{ (Input::get('category') == 2) ? 'selected="selected"' : null }}>Category 2</option>
<option value="3" {{ (Input::get('category') == 3) ? 'selected="selected"' : null }}>Category 3</option>
</select>
I think the Input::old('category') doesn't work because it is a GET request, am I right? Is there any workarounds?
Update : I finally made it work using Input::get() instead of Input::old() :
{{ Form::select('category', $categories, Input::get('category')) }}
It seems you're not even retrieving the old input, you will need to pass it to the view. You can do that in one of two ways, the easiest and best to understand is to just specify that you want to pass input.
return View::make('blog', compact('categories', 'posts'))->withInput();
Also, you don't need the markup in your HTML. Laravel will do this for you if you just give it the value of the old Input. It works very well.
Perhaps this will work
public function getPosts()
{
$category_id = Input::get('category');
$posts = Post::where('category_id', $category_id)->paginate(25);
$categories = Category::lists('title', 'id');
return View::make('blog', compact('categories', 'posts', 'category_id'));
}
// Blog view
{{ Form::open('method' => 'get', 'id' => 'form-search') }}
{{ Form::select('category', $categories, $category_id) }}
{{ Form::close() }}

Categories