Laravel 5 How to Pass 2 Models to a Form - php

I have form and i am using form model binding. My form is
{!! Form::model($vehicle,['url' => '/pages/store']) !!}
<table style="width:650px; margin-left: 4px;" >
<tbody>
<tr>
<td>ID</td>
<td>Model</td>
<td>Brand</td>
<td>License Plate</td>
</tr>
<tr>
<td>{!! Form::text('id' ,null , ['readonly'], ['class' =>'textboxlong form-control', 'style'=>'height:23px;']) !!}</td>
<td>{!! Form::text('model' ,null ,['class' =>'textboxlong form-control', 'style'=>'height:23px;']) !!}</td>
<td>
{!! Form::select('brand_id', $brands, null, ['id'=>'brandBox', 'style' => 'width:150px;']) !!}
</td>
<td>{!! Form::text('licenseplate' ,null ,['class' =>'textboxlong form-control', 'style'=>'height:23px;']) !!}</td>
</tr>
<tr>
<td colspan="2">Client</td>
</tr>
<tr>
<td colspan="2">{!! Form::select('representive_client_id', $clients, null, ['id'=>'clientSelectBox', 'class' => 'selectbox']) !!}</td>
</tr>
<tr>
<td colspan="2">Telephone Number</td>
</tr>
<tr>
<td colspan="2">{!! Form::text('tel_number' ,null ,['class' =>'textboxlong form-control', 'style'=>'height:23px;']) !!}</td>
</tr>
<tr>
<td colspan="2">Adress</td>
<td colspan="2">{!! Form::textarea('address' ,null ,['class' =>'textboxlong form-control','style'=>'height:60px;']) !!}</td>
</tr>
</tbody>
</table>
<div id="buttoncontainer">
<a class="btn btn-default" href="{{ URL::to( 'pages/vehicleprocess/' . $first -> id ) }}"><<</a>
#if($previous)
<a class="btn btn-default" href="{{ URL::to( 'pages/vehicleprocess/' . $previous ) }}">PREVIOUS</a>
#endif
#if($next)
<a class="btn btn-default" href="{{ URL::to( 'pages/vehicleprocess/' . $next ) }}">NEXT</a>
#endif
<a class="btn btn-default" href="{{ URL::to( 'pages/vehicleprocess/' . $last -> id ) }}">>></a>
<a class="btn btn-default" id="add">EKLE</a>
{!! Form::submit('EDIT', array('class'=>'btn btn-primary')) !!}
{!! Form::submit('NEW RECORD', array('class'=>'btn btn-primary')) !!}
</div>
{!! Form::close() !!}
I am passing the $vehicle as
$vehicle = Vehicle::where('vehicles.id',$id)->join('clients', 'vehicles.representive_client_id', '=', 'clients.id')->first();
Store Function
$client = new Client;
$client -> full_name = $client_id;
$client -> tel_number = $tel_number;
$client -> mobile_number = $mobile_number;
$client -> save();
$last_client_id = $client -> id;
$input = Request::except('client_id');
$vehicle = Vehicle::create($input);
$u_vehicle = Vehicle::orderBy('created_at', 'desc')->first();
$u_vehicle -> update(array('client_id' => $last_client_id));
I am able to see all values of these fields in my view but when it comes to store a new record to my database i am getting this error
Column not found Unknown column 'tel_number'
Guess i need to pass 2 models (Vehicle and Client) to the form but not sure how to make it. Any help would be appreciated.

In short you need to pass your view a instance of Vehicle with Client - I know you're trying to do that with the join but I'm guessing that isn't the right way to do it. I set up a clean install with Laravel and it appears to work when you set up the relationship on the model.
I'm unsure what your relationships are so let's assume a Client has one Vehicle so the Vehicle belongs to the Client. So we can put your relationship in your Vehicle.php
public function client() {
return $this->belongsTo('App\Client'); // or whatever the namespace to your class is
}
See more here on defining relationships: http://laravel.com/docs/5.1/eloquent-relationships#defining-relationships
Then when you load the model in your view you can do this:
$vehicle = \App\Vehicle::with('client')->where('id', $id)->first();
The important part being: with('client')
Then any text fields with Client attributes should be populated with the existing data.
I hope that helps, if you need more help please let me know. I've got sample code of it working in a blank laravel project so I can throw that up on github if you need to see it.

Related

Data doesn't display

Need some help here, I'm using Laravel app, my problem is my data wont display on the table. I tried some ways to display my data but it doesn't work.
Here's my code.
<tbody>
#if (count($expenses) > 0)
#foreach ($expenses as $expense)
<tr data-entry-id="{{ $expense->id }}">
<td field-key='expense_category'>{{ $expense->expense_category->name or '' }}</td>
<td field-key='entry_date'>{{ $expense->entry_date }}</td>
<td field-key='amount'>{{ $expense->amount }}</td>
<td field-key='created_by'>{{ $expense->created_by->name or '' }}</td>
<td>
#can('view')
#lang('quickadmin.qa_view')
#endcan
#can('edit')
#lang('quickadmin.qa_edit')
#endcan
#can('delete')
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("quickadmin.qa_are_you_sure")."');",
'route' => ['expenses.destroy', $expense->id])) !!}
{!! Form::submit(trans('quickadmin.qa_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}
#endcan
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="9">#lang('quickadmin.qa_no_entries_in_table')</td>
</tr>
#endif
</tbody>
here is my expenseController.
but i have never touched this code, i always work on the table form.
class ExpensesController extends Controller
{
/**
* Display a listing of Expense.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (! Gate::allows('expense_access')) {
return abort(401);
}
if ($filterBy = Input::get('filter')) {
if ($filterBy == 'all') {
Session::put('Expense.filter', 'all');
} elseif ($filterBy == 'my') {
Session::put('Expense.filter', 'my');
}
}
$expenses = Expense::all();
return view('admin.expenses.index', compact('expenses'));
}
}
try to find are you getting data from DB or not ....
$expenses = Expense::all();
dd($expenses);
It will show your data collection.
As I Think you are not getting any data from here.

undefined index on empty array laravel 5

Fellow coders,
It might be a stupid question but I really am stuck on this part in my application.
I am making an hourregistration system for the company i'm an intern at. What I have done is creating a delete button in my application that deletes a record with the click of a simple button. Yet what I did was to delete all the visible records in the table I created that shows all the registrations.
When I deleted the final record I got an error of "undefined index hourregistration".
public function index()
{
$hoursregistrations = Hoursregistration::latest()->get();
$user_id = Sentinel::getUser();
$project_id = Project::pluck('description', 'id');
$company_name = Company::where('status','client')->pluck('company_name', 'id');
$activity_name = Subproject::pluck('id');
//dd($hoursregistrations);
return view('hoursregistrations.index', compact('hoursregistrations', 'user_id', 'project_id',
'activity_name', 'company_name'));
}
I think the problem lies at
$hoursregistrations = Hoursregistration::latest()->get();
Because I'm trying to get the latest value of the registration but there is none right?
Now i'm wondering how I could still show my view without breaking my inserting and/or viewing portion of the app.
#foreach ($hoursregistrations as $hoursregistration)
<tr>
<td hidden>{{ $user_id->first_name }}</td>
<td >{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}</td>
<td>{!! $hoursregistration->note !!}</td>
<td>{!! \App\Helpers::dateFormat($hoursregistration->date) !!}</td>
<td>{!! $hoursregistration->hours !!}</td>
<td>
<button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="{{$hoursregistration->id}}">Edit</button>
<form action="hoursregistrations/{{ $hoursregistration->id }}/delete" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button id="btn-delete" type="submit" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="{{ $hoursregistration->id }}">Delete</button>
</form>
</td>
</tr>
#endforeach
This is the foreach loop that shows the data in the index.blade.php view
I would love some help so I can continue finishing this application
public function index()
{
$hoursregistrations = Hoursregistration::latest()->get();
$user_id = Sentinel::getUser();
$project_id = Project::pluck('description', 'id');
$company_name = Company::where('status','client')->pluck('company_name', 'id');
$activity_name = Subproject::pluck('id');
//dd($hoursregistrations);
return view('hoursregistrations.index', compact('hoursregistrations', 'user_id', 'project_id',
'activity_name', 'company_name'));
}
Everything is about s or not s.
The error you are talking about is because you have an occurrence of $hoursregistration (without s) before or after the #foreach of your view. The solution is to check and remove occurrence of $hoursregistration outside your loop:
// You can't use $hoursregistration before
#foreach ($hoursregistrations as $hoursregistration)
{{-- ... do what you want with $hoursregistration --}}
#endforeach
// You can't use $hoursregistration after
I am sure there is a confusion (typo) between $hoursregistration, $hoursregistrations and $hourregistration (the confusion is even in your post VS comment)
you can use if here if $hoursregistrations exists then it populate data else nothing happen
#if($hoursregistrations)
#foreach ($hoursregistrations as $hoursregistration)
<tr>
<td hidden>{{ $user_id->first_name }}</td>
<td >{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}</td>
<td>{!! $hoursregistration->note !!}</td>
<td>{!! \App\Helpers::dateFormat($hoursregistration->date) !!}</td>
<td>{!! $hoursregistration->hours !!}</td>
<td>
<button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="{{$hoursregistration->id}}">Edit</button>
<form action="hoursregistrations/{{ $hoursregistration->id }}/delete" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button id="btn-delete" type="submit" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="{{ $hoursregistration->id }}">Delete</button>
</form>
</td>
</tr>
#endforeach
#endif
i think this might help

Updating multiple records using Laravel 5.3 model binding

I am pulling multiple records from MySQL and looping through model binding and filling all the input fields with some data.
Now, I may change 2 or 10 or all 26 fields and hit update button. I want to update all the records. Now, I don't know how $id works here? usually I update single record and I have $id which I can find and update only that field.
But that's not the case here. I am pulling 13 records(or 26 fields). 13 field_1 and 13 field_2. How to update all?
mycode
Database
Table
-id
-name
-field1 (updating this one)
-field2 (updating this one)
Routes
Route::get('/cat' , 'AdminController#cat');
Route::patch('/cat/{$id}/update','AdminController#cat_update');
Controller
public function cat(){
$cattfs = Catf::all();
return view('/cat',compact('cattfs'));
}
public function cat_update(Request $request, $id) // id = 1
{
$rules = array(
'field1' => 'required',
'field2' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect()->back()->withErrors($validator);
} else {
$cat = Cattf::find($id); //This wont work :/
$cat ->field1 = Input::get('field1');
$cat ->field2 = Input::get('field2');
$cat ->save();
return redirect('/cat');
}
}
Views
<div class="col-md-6" style="background-color:#fff">
<table class="table table-hover">
<thead>
<tr>
<th style="text-align: center">Product</th>
<th style="text-align: center">Pr</th>
<th style="text-align: center">Co</th>
</tr>
</thead>
<tbody>
#foreach ($cattos as $catto)
{!! Form::model($catto,[ 'method' =>'PATCH', 'url' => ['/cat/.$catto->id./update']]) !!}
<tr>
<td>{{$catto->name}}</td>
<td> {!! Form::text('field1' ,null , ['class'=>'form-control']) !!}</td>
<td> {!! Form::text('field2' ,null , ['class'=>'form-control']) !!}</td>
</tr>
#endforeach
<td colspan="3">
{!! Form::submit('UPDATE', ['class'=>'btn btn-primary btn-block']) !!}
{!! Form::close() !!}
</td>
</tr>
</tbody>
</table>
</div>
snapshot of the form
I don't think you can do this with Model binding (correct me if I'm wrong someone).
What you can instead do is generate an array of data to post to your controller.
For example:
{!! Form::open(['route' => 'catupdate']) !!}
#foreach ($cattos as $catto)
<tr>
<td>{{$catto->name}}</td>
<td>{!! Form::text('categories['.$catto->id.'][field1]', null, ['class'=>'form-control']) !!}</td>
<td>{!! Form::text('categories['.$catto->id.'][field2]', null, ['class'=>'form-control']) !!}</td>
</tr>
#endforeach
{!! Form::close() !!}
You should then receive an array in your controller, which you can loop around and update each record.
public function catupdate()
{
$categories = request()->input('categories');
foreach($categories as $id => $values) {
$cat = Cattf::find($id);
$cat->field1 = $values['field1'];
$cat->field2 = $values['field2'];
$cat->save();
}
}
You can then also validate the array by doing the following in your Request file
public function rules()
{
return [
'categories.*.field1' => 'required',
'categories.*.field2' => 'required'
];
}
this is untested and is an example demonstrating the concept

How to sync pivot with extra field in Laravel?

I need some help about a problem in Laravel . I have 3 tables:
pellets
specie (there are the trees)
specie_pellet (this is the pivot table)
The specie_pellet table is a pivot for the composition of a pellet and has an extra field called percentuale (percentage).
Obviously the relation is belongsToMany in Specie Class and belongsToMany in Pellet Class
In detail Pellet Class:
// Imposto la relazione con le Specie
public function specie()
{
return $this->belongsToMany(Specie::class)->withPivot('percentuale');
}
In detail Specie Class:
// Imposto la relazione con i Pellets
public function pellets()
{
return $this->belongsToMany(Pellet::class)->withPivot('percentuale');
}
To modify the table i use a form:
{!! Form::model($pellet, ['method' => 'PUT', 'route' => ['composizione.update', $pellet->id]]) !!}
<table class="table table-bordered">
<thead>
<th>Specie</th>
<th>Percentuale</th>
<th>Azione</th>
</thead>
<tbody>
#foreach($pellet->specie as $specie)
<tr>
<td>{!! Form::select('specie[]', $listaSpecie, $specie->id, ['class' => 'form-control']) !!}</td>
<td>
<input type="text" class="form-control" name="percentuale[]" value="{{ $specie->pivot->percentuale }}">
</td>
<td><a class="btn btn-danger" href="{{ url('composizione/pellet/elimina/id/' . $pellet->id . '/specie/' . $specie->id) }}">Elimina</a> </td>
</tr>
#endforeach
</tbody>
</table>
{!! Form::submit('Aggiorna Composizione', ['class' => 'btn btn-success']) !!}
{!! Form::close() !!}
the request pass to the route
Route::put('composizione/pellet/update/{id}', 'PelletController#updateComposizione')->name('composizione.update');
And finally I have the controller
public function updateComposizione(\App\Http\Requests\ComposizioneUpdateRequest $request, $id)
{
$pellet = Pellet::find($id);
$specie = Input::get('specie');
$percentuali = Input::get('percentuale');
$pellet->specie()->sync([$specie => ['percentuale' => $percentuali]]);
return redirect('admin/pellets/')->with('ok_success', 'Composizione aggiornata correttamente');
}
But I get this error: Illegal offset type
in PelletController.php line 94
at HandleExceptions->handleError(2, 'Illegal offset type', '/srv/users/serverpilot/apps/laraweb/app/Http/Controllers/PelletController.php', 94, array('request' => object(ComposizioneUpdateRequest), 'id' => '5', 'pellet' => object(Pellet), 'specie' => array('1', '7'), 'percentuali' => array('50', '50'))) in PelletController.php line 94
at PelletController->updateComposizione(object(ComposizioneUpdateRequest), '5')
at call_user_func_array(array(object(PelletController), 'updateComposizione'), array(object(ComposizioneUpdateRequest), 'id' => '5')) in Controller.php line 55
...
Can someone help me understand this please?
Thanks a lot and sorry for my english. I'm Italian ;)
I would suggest you review the laravel tutorials on forms and rethink this approach, namely the select may not be the best way to do this. The select is not the best way to solve this one.
Try doing this:
#foreach($pellet->specie as $specie)
{!! Form::open(["url" => "composizione/pellet/update/".$pellet->id, "method" => "PUT"]) !!}
<tr>
<td>
<input type="hidden" name="specie" value={{$specie->id}} />
<input type="text" class="form-control" name="percentuale" value="{{ $specie->pivot->percentuale }}">
</td>
<td><inpyt type="submit" class="btn btn-danger">Elimina</a> </td>
</tr>
{!! Form::close() !}}
#endforeach
The rest would probably work. What's happening here is you're going to update a single specie / percentuale combination at once, not multiple ones.

Pass a variable to an other view

I try to load a view(project_template) in an other view.
My problem ist, how i can give my $project-variable to the 'project_template'-view which i create in my main-view with "View:make".
Actually i use
->with($project)
But when I try to use it in my template_view, i get an non-object-error
I also used "compact" what also not worked for me.
In my main-view i can use the $project-variable without problems
View:
#foreach($projects as $project)
<tr class="gradeA">
<td>
<td>{!! $project->description !!}</td>
<td>
{!! View::make('shared.tables.project_template')->with($project)->render() !!}
</td>
</tr>
#endforeach
Project_Template-View:
{!! $project->project_name !!}
Error-Message
ErrorException in 0f9dcdc70fd0be3b50d7a39ad7bc90d7 line 4:
Trying to get property of non-object
Thanks for the help!
Change to this:
#foreach($projects as $project)
<tr class="gradeA">
<td>
<td>{!! $project->description !!}</td>
<td>
#include('shared.tables.project_template')
</td>
</tr>
#endforeach
Simply use the #include(viewName, [data]).
That means, in your case:
#include('shared.tables.project_template', ['project' => $project])

Categories