Question About Pluck Results in Laravel 5.7 - laravel

I have a question about the pluck method in Laravel. How can I get the following result in a list?
Name + Lastname + id
I use this line command in a controller
Line: $choferes
public function index()
{
$asignaciones = Asignacion::orderBy('id', 'ASC')->get();
$choferes = Chofer::orderBy('id', 'ASC')->pluck('nombre', 'id');
$dueños = Dueño::orderBy('id', 'ASC')->pluck('nombre', 'id');
$asignaciones->each(function ($asignaciones)
{
$asignaciones->chofer;
$asignaciones->dueno;
});
return view('admin.asignaciones.index')
->with('asignaciones', $asignaciones)
->with('choferes', $choferes)
->with('dueños', $dueños);
}
The result in a list:
1 => "name 1"
2 => "name 2"
However, I need to combine: name and lastname. It needs to be a list. How can I display it in my view?
<div class="col-xs-6">
{!! Form::label('chofer_id','Lista de Choferes') !!}
{!! Form::select('chofer_id[]', $choferes, null,
['class'=>'form-control select_chofer',
'multiple',
'required','id'=>'list_chofer']) !!}
</div>
I have this result:
result
Thanks!

In your Chofer model define
public funcion getFullNameAttribute()
{
return $this->attributes['first_name'] + ' ' + $this->attributes['last_name'];
}
In controller use this
$choferes = Chofer::orderBy('id', 'ASC')->get(['id`, ...])->pluck('full_name', 'id');

Related

How to store dynamically input name and value both in Controller

This is my blade file where the input type is a radio and I have made name dynamically by giving question id so that I can store in question_id. So How can I store them in Controller.
#foreach($question->answers as $index=> $answer)
<span>
<input type="radio" name="{{$question->id}}" value="{{$answer->id}}" id="answer{{$question->id}}"
class="clickanswer" data-id="{{$answer->id}}">
{{$index+1}}) {!! $answer->answer_body !!}
</span>
#endforeach
Now this is my Controller
public function quizTest(Request $request){
if($request->isMethod('post')){
$data=$request->all();
foreach($data as $question_id => $answer_id){
dd($data);
$result=new Result;
$result->user_id=$data['user_id'];
$result->question_id=$question_id;
$result->answer_id=$answer_id;
$result->save();
}
}
}
Now when I do dd($data); and I want to store data like 1 2 3 4 5 in question_id and 2,6,9,13,18 in answer_id
Change your controller code to this to store it in answer and question format
public function quizTest(Request $request){
if($request->isMethod('post')){
$data=$request->all();
$user_id = $data['user_id'];
unset($data['_token']);
unset($data['user_id']);
foreach($data as $question_id => $answer_id){
$result = new Result;
$result->user_id = $user_id;
$result->question_id = $question_id;
$result->answer_id = $answer_id;
$result->save();
}
}
}

How to use a Form::Select with a Pivot Table in Laravel 5.6

I try to use Form::select in Laravel 5.6, but when I went to the Edit Page, in the select, there are options with all the data of the object Model instead of a regular field.
I have a Game Model with a relationship ManyToMany with a Tag Model.
In my edit function from the Game Controller
public function edit($item)
{
$tags = Tag::all();
return view('megadmin.games.edit', compact('item', 'tags'));
}
In my Form Blade :
{!! Form::select('tags', $tags, array_pluck($tags, 'id_tag','name'), ['class' => 'form-control'])!!}
Here the result :
The result
I just want a normal select/options with the data AND i want to retrieve the model Tag associated with the Game in the Game Form.
Thanks you for your help ^^
I assume you are using Form model binding, so you can do this:
In your Game model create a new method only for you Form Model Binding:
class Game extends Model
{
use FormAccessible;
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function formTagsAttribute()
{
return $this->tags()->pluck('id_tag');
}
}
In your Controller:
public function edit($item)
{
$tags = Tag::pluck('name', 'id_tag');
return view('megadmin.games.edit', compact('item', 'tags'));
}
In your view:
{!! Form::model($game, [$attributes]) !!}
{!! Form::select('tags', $tags, null, ['class' => 'form-control']) !!}
.
.
.
{!! Form::close() !!}
Controller
public function edit($item)
{
$tags = Tag::all();
$goodTag = $item->tags()->first()->id;
//here assuming `$item` is your Game object and
//you have ManyToMany relation with tags with `tags` function in game model
//lots of assuming
return view('megadmin.games.edit', compact('item', 'tags', 'goodTag));
}
View
{!! Form::select('tags', array_pluck($tags,'name', 'id_tag'), $goodTag, ['class' => 'form-control'])!!}
Here is the laravel form select source code https://github.com/illuminate/html/blob/master/FormBuilder.php#L393
and array_pluck https://laravel.com/docs/5.6/helpers#method-array-pluck

Laravel5.6 "Call to a member function delete() on null " , delete a row in table

I want to delete a row from table. The function I used in controller is:
public function destroy($id) {
$category = Category::find($id);
$category->delete();
return redirect()->back();
}
However it throws me an error:
Call to a member function delete() on null
When I use this code:
public function destroy($id) {
$category = Category::find($id);
dd($id);
}
It is showing the correct id i.e.
"1"
And when I use
public function destroy($id) {
$category = Category::find($id);
dd($category); // or
dd(Category::find($id);
}
I get the output
null
on the screen.
As mentioned in comments, the error you're getting is probably due to no category exists in the database for the given ID.
Then, when you try to find the category for that ID:
$category = Category::find($id);
The value of $category variable is null. Therefore, you get an error for trying to call delete() method on null. Under the hood, it would be the same as doing the following:
null->delete();
Which, doesn't work.
You could check the value of $category before trying to delete it. Or you may use a query to delete all records matching a given condition, in your case id = $id. This way:
public function destroy($id)
{
Category::where('id', $id)->delete();
return redirect('/')->back();
}
Refer to Deleting Models By Query in the Eloquent docs for details on how that works.
What worked for me is the following (I ensured that the $id was passing from the view):
public function destroy($id)
{
$vendor = Vendor::findorFail($id);
$vendor->delete():
}
for some reason when I did the following it showed null
public function destroy($id)
{
$vendor = Vendor::find($id);
$vendor->delete():
}
This is the view part:
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("global.app_are_you_sure")."');",
'route' => ['vendor.destroy', $vendor->vendor_id])) !!}
{!! Form::submit(trans('global.app_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}

Laravel 5.5 - Save multiple data continiously from blade

I want to make a PHP method using laravel. I want to do the comparison of criteria and criteria. Here is the controller code :
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
return view('kriteria_kriterias.create')->with('kriteria1', $kriteria1)->with('kriteria2', $kriteria2)->with('data', $data);
}
and this is the blade code :
It will make the form appear as total of criteria#
The problem is, I can't save it all to database. How do I get it to do this?
Updated method in the controller to the following:
public function create()
{
$kriteria1 = Model\Kriteria::pluck('nama_kriteria', 'id');
$kriteria2 = Model\Kriteria::pluck('nama_kriteria', 'id');
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
How to output in the blade file:
{{ $kriteria1 }}
{{ $kriteria2 }}
Or you update the controller to pass the complete results:
public function create($id1, $id2)
{
$kriteria1 = Model\Kriteria::find($id1);
$kriteria2 = Model\Kriteria::find($id2);
$data = [
'kriteria1' => $kriteria1,
'kriteria2' => $kriteria2
];
return view('kriteria_kriterias.create')->with($data);
}
And the in the blade you can accss the data in various ways, one way is a foreach loop using blade in the blade template:
#foreach($kriteria1 as $k1)
{{ $k1 }}
#endforeach
#foreach($kriteria2 as $k2)
{{ $k2 }}
#endforeach'
To accept multiple values dynamicaly in the controller you can try something like this:
public function create($ids)
{
$results = collect([]);
foreach($ids as $id) {
$kriteria = Model\Kriteria::findOrFail($id);
if($kriteria) {
$results->put('kriteria' . $id, $kriteria);
}
}
return view('kriteria_kriterias.create')->with($results);
}
Then use the same looping method mentioned above to display them in the blade or a for loop that gets the count and displays accordingly.
maybe you forgot to add the opening tag ;)
{!! Form::open(array('url' => 'foo/bar')) !!}
//put your code in here (line 1-34)
{!! Form::close() !!}

Creating a Value List Using Values from Another Table in Laravel

I have a simple database application that records contacts (name, address, etc.). I am trying to draw on various other tables to generate value lists for the forms. Then I would like to have all form values entered by the user to be saved into the appropriate tables on submit.
For example, I have the people table which includes the name and address. I have a title table with the different possible values for the title (i.e. Mr., Mrs., Ms. Dr.). Upon filling in the contact form, I would like to generate the values for the title field in the form from the title table. I am trying to do this one model for Contact that includes separate classes for the people table and the title table.
In my ContactController.php I have:
class ContactController extends Controller {
public function index()
{
$people = Contact::all();
// return main homepage for Contacts section
return view('pages.contacts.home', compact('people'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
$title = Contact::lists('title', 'id');
return view('pages.contacts.create');
}
In my Contact.php model I have the following:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model {
protected $table = 'people';
protected $fillable = [
'title_id',
'name_first',
'name_middle',
'name_last',
'date_birth',
'date_death',
'bio',
'created_at',
'modified_at'
];
public function title() {
return $this->belongsTo('Title', 'title_id', 'id');
}
}
class Title extends Model {
protected $table = 'title';
protected $fillable = [
'title',
'created_at',
'modified_at'
];
public function contacts() {
return $this->hasMany('Contact', 'title_id', 'id');
}
}
In the form I have the following:
<div class="form-group">
{!! Form::label('title', 'Title: ') !!}
{!! Form::select('title', $title) !!}
</div>
<div class="form-group">
{!! Form::label('name_first', 'First Name: ') !!}
{!! Form::text('name_first', null, ['class' => 'form-control']) !!}
{!! Form::label('name_middle', 'Middle Name: ') !!}
{!! Form::text('name_middle', null, ['class' => 'form-control']) !!}
{!! Form::label('name_last', 'Last Name: ') !!}
{!! Form::text('name_last', null, ['class' => 'form-control']) !!}
{!! Form::label('name_nick', 'Nickname: ') !!}
{!! Form::text('name_nick', null, ['class' => 'form-control']) !!}
</div>
I am getting an error saying the variable title is undefined. I cannot determine why the value list is not being returned. Are my relationships returned incorrectly?
You don't pass the $title variable to your view.
In your create method in the ContactController, assign the $title variable to your view:
public function create()
{
$title = Contact::lists('title', 'id');
return view('pages.contacts.create')->with('title', $title);
}
See http://laravel.com/docs/5.0/views for more documentation.

Resources