Laravel RESTful edit screen with multiple tables - laravel

I have 3 tables for storing business details. The main table and a phone numbers table, as a business can have any number of phone numbers attached to it.
Table 1 - Business listing
Table 2 - Business phone numbers
Table 3 - Links table 1 to table 2 as shown here
1 id int(11) No None AUTO_INCREMENT
2 listings_id int(11) No None
3 listingsphone_id int(11) No None
4 created_at timestamp
5 updated_at timestamp
My controller extracts the data from the database and passes it to the view
public function edit($id)
{
// get the listing
$listing = DB::table('listings')
->where('listings.id', '=', $id)
->first();
$listingphone = DB::table('listings')
->leftjoin('listings_listingsphone_rel', 'listings.id', '=', 'listings_listingsphone_rel.listings_id')
->leftjoin('listingsphone', 'listings_listingsphone_rel.listingsphone_id', '=', 'listingsphone.id')
->where('listings.id', '=', $id)
->get();
// show the edit form and pass the listing
return View::make('admin.listings.edit')
->with('listing', $listing)
->with('listingphone', $listingphone);
}
Blade then needs to create multiple Input rows in the form for outputting to the screen, one for each row that exists.
{{ Form::model($listing, array('route' => array('admin.listings.update', $listing->id), 'method' => 'PUT')) }}
<div class="form-group">
{{ Form::label('listingname', 'Company Name') }}
{{ Form::text('listingname', null, array('class' => 'form-control')) }}
</div>
#foreach($listingphone as $key => $value)
<div class="form-group">
{{ Form::label('phone', 'Phone number') }}
{{ Form::text('phone', null, array('class' => 'form-control')) }}
</div>
#endforeach
{{ Form::submit('Edit the Listing!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
The problem with the code is, it will generate for me multiple Input lines with the same Name and ID
<label for="phone">Phone</label>
<input class="form-control" name="phone" type="text" id="phone">
<label for="phone">Phone</label>
<input class="form-control" name="phone" type="text" id="phone">
I obviously need to store that data in the controller with code such as this (psuedo code):-
// store
$listing = Listing::find($id);
$listing->listings_company = Input::get('listings_company');
$listing->save();
// store
$listingphone = ListingPhone::find($id);
foreach ($listingphone as $key => $value)
{
$listingphone->listings_phone = Input::get('phone['$key']');
$listingphone->save();
}
How should I be handling this type of setup within Blade/the controller?

I'm assuming that the problem you are having the text form fields is the same kind of issue that you need to deal with when you have a checkbox. You have multiple fields with the same name that needs to be referenced anyway.
For that you need to use brackets on the form field name.
You can see a similar example related to checkboxes here:
How to get the values for a series of checkboxes in Laravel 4 controller (if checked)

Related

Laravel checkbox problem which I cannot update the pivot table

I'm working on a laravel application. In laravel I'm trying to update a row from a pivot table. In this application I have three tables:
issues: id, title, description
categories: id, name
category_issues:(pivot table) id, issue_id, category_id
In laravel I'm trying to update a row from a pivot table. I have this relationships:
Issue.php
public function categories() {
return $this->belongsToMany('App\Category', 'category_issues');
}
Category.php
public function issues() {
return $this->belongsToMany('App\Issue', 'category_issues');
}
A issue can have many categories.
Html code for displaying category section:
<div class="form-group row">
<label for="category" class="col-md-4 col-form-label text-md-right">{{ __('Category :') }}</label>
<div class="form-check col-md-6">
#foreach ($categories as $category)
<input type="checkbox" name="category[]" id="{{ $category->id }}" value="{{ $category->id }}"
{{ in_array($category->id, $issue->categories->pluck('id')->toArray()) ? 'checked' : '' }}>
<label for="{{ $category->id }}"> {{ $category->name }} </label>
#endforeach
</div>
</div>
Here is the update function file:
public function update(Issue $issue)
{
request()->validate([
'title'=> ['required', 'min:3'],
'description'=> ['required', 'min:3'],
'category' => ['required']
]);
$issue->title = request('title');
$issue->description = request('description');
$issue->save();
//Category_Issue Update
$categoryIssue = new CategoryIssue;
$cats = request('category');
foreach ($cats as $cat) {
$categoryIssue->updateOrCreate([
'issue_id'=> $issue->id,
'category_id' => $cat
]);
}
return redirect('issues')->with('success', 'Issue has been updated');
}
Instead of doing the creation / update on the CategoryIssue model (do you even have a CategoryIssue model?), Laravel makes this really easy to update the pivots of a relationship all at once, with the sync() method. You've set up the relationships correctly already per your code above.
In your update() method, you already have your Issue model, and have saved it. You have a set of categories coming in from the form via the $request object (or none if user didn't choose any), so you can then update the pivot like this:
$issue->categories()->sync($request->get('category', []));
Leaving a blank array as the second argument is optional. One small suggestion: maybe make the name of the field on the form 'categories' instead of 'category' just to keep it easy to remember it is an array coming in.

Laravel 5.4: Using eloquent and fillable field to update multiple model with multiple table

I have two models Driver and DriverCar
I need to display the field values by model let me show you my code of my form header
Note that Driver are related to DriverCar by driver_id
{!! Form::model($driver, [
'route'=>['drivers.update', $driver],
'method'=>'PATCH',
'class'=>'form-horizontal'
]) !!}
now in my form fields I have
<div class="form-group">
{!! Form::label('name', trans('interface.DriverName'), ['class'=>'col-sm-2 control-label']) !!}
<div class="col-sm-10">
{!! Form::text('name', null, ['class'=>'form-control', 'placeholder'=>trans('interface.DriverName')]) !!}
</div>
</div>
which updated successfully when I update. but the DriverCar fields didn't get the fillable values if it's set to null I had to get it by relations like $driver->driverCar->car_model
<div class="form-group">
{!! Form::label('car_model', trans('interface.carModel'), ['class'=>'col-sm-2 control-label']) !!}
<div class="col-sm-10">
{!! Form::text('car_model', $driver->driverCar->car_model, ['class'=>'form-control', 'placeholder'=>trans('interface.carModel')]) !!}
</div>
</div>
is there is any way to get it fillable without giving it relations like that $driver->driverCar->car_model?
second
here is my controller I try to updated the two tables at once
public function update( Request $request, Driver $driver, DriverCar $driverCar ) {
//dd( $driverCar );
$input = $request->all();
$driver->fill( $input )->save();
$driverCar->fill( $input )->save();
return redirect()->route( 'drivers.edit', $driver );
}
in controller too I can't update the two tables it just update the Driver but not touching the DriverCar
any Guide please.
You're not passing driverCar ID to the update controller method, so change code to something like this:
public function update( Request $request, Driver $driver)
{
$input = $request->all();
$driver->fill($input)->save();
$driver->driverCar()->first()->fill($input)->save();
return redirect()->route('drivers.edit', $driver);
}

Return Logged User's Posts Into laravelcollective/html Select Dropdown Menu Within a Form

I am trying to pass only the posts created by the logged in user into a laravelcollective/html select drop down menu within a form.
In my code I have two examples. Using the variable example shows how I can get the dropdown select menu to show all results from the posts table. Using the variable posts in a foreach loop shows how I can return just the posts created by the logged user, but not in a select menu.
I need to have the dropdown menu function as in the form using example but displaying results of the foreach posts loop.
Controller
public function createPost()
{
$example = Post::pluck('title', 'id')->all();
$posts = Posts::all();
return view('post.create', compact('posts', 'example'));
}
Example View
<div class="form-group">
{!! Form::label('example', 'Posts:') !!}
{!! Form::select('example', ['' => 'Select'] + $example, null) !!}
</div>
Foreach Loop Posts View
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach
try $posts = Posts::where('user_id',\Auth::id())->get()->pluck('title','');. It will return only posts of logged in user.
{{ Form::select('example', $posts) }}
You are using select box wrong.
#foreach($posts as $post)
#if(Auth::user()->id == $post->user_id)
{{ $post->title }} <br>
#endif
#endforeach
I would update your controller to only return posts by the user rather than rely on the foreach check if Auth::user()->id == $post->user_id
public function createPost()
{
$posts = Posts::where('user_id', auth()->user()->id)->get();
return view('post.create', compact('posts'));
}
As a side note, your method should probably just be create() to keep inline with the standard CRUD.
Then in your blade,
<div class="form-group">
{!! Form::label('post', 'Posts:') !!}
{!! Form::select('post', ['' => 'Select'] + $posts, null) !!}
</div>

Cannot display values when editing form in laravel 5

There is no output in the form when clicking a value. But I can see the values when using the return function. Here is my code:
ReportController
public function edit($id)
{
$crime_edit = CrimeReport::findOrFail($id);
$victim_info = VictimProfile::findOrFail($id);
return $victim_info;
//return $victim_info->firstname;
//return $victim_info;
$display_crime_type = CrimeType::lists('crime_type','id');
$display_crime_name = CrimeName::lists('crime_description','id');
return view('crimereports.edit',compact('crime_edit','victim_info','display_crime_name,'display_crime_type'));
}
edit view page
{!! Form::model($crime_edit,['method' =>'PATCH','route'=>'crime_reports.update',$crime_edit->id],'class'=>'form-horizontal']) !!}
<div class="form-group">
{!! Form::label('victim_name', 'Victim Name',['class'=>'col-md-3 control-label']) !!}
<div class="col-md-3">
{!! Form::text('victim_name', null, ['class' => 'form-control','placeholder' => 'Firstname']) !!}
</div>
<div class="col-md-2">
{!! Form::text('v_middle_name', null, ['class' => 'form-control','placeholder' => 'Middlename']) !!}
</div>
<div class="col-md-3">
{!! Form::text('v_last_name', null, ['class' => 'form-control','placeholder' => 'Last Name']) !!}
</div>
</div>
{!! Form::close() !!}
Am I missing something?
The null is the default value. I think Form::model is suppose to bind the values, but have you tried removing the null?
I don't use Form::model, but as a default value I always put old('field_name', $model->field_name). The old function will look into both GET and POST and if a key matches that'll be shown. If that doesn't exist, it'll use the second value.
Based on your debug output statements ("return $victim_info;"), it looks like you are trying to bind the form to the $crime_edit model while accessing the values from the $victim_info model. You can not bind a form to two different models at once, so if the blank victim name fields are not attributes of the $crime_edit model, your current implementation will not work.
You will need to either explicitly add $victim_info->victim_name, etc. in place of the 'null' values, or bind the form to the $victim_info model instead of the $crime_edit model.
If victim_name, v_middle_name, and v_last_name are attributes of the $crime_edit model, then I have no idea.

Laravel 4 blade drop-down list class attribute

Laravel blade drop down list class attribute not working.
I cannot find any reference to class or assigning attributes to select / drop-down lists in the documentation.
http://www.laravel.com/docs/html#drop-down-lists
Examples tried:
{{ Form::select('product_id', $productList, array('class'=>'form-control')) }}
{{ Form::select('product_id', $productList, $attributes = array('class'=>'form-control')) }}
Both return the same html but without the class attribute:
<select id="product_id" name="product_id">
... Option Stuff ...
</select>
{{ Form::select('product_id', $productList, null, array('class' => 'form-control')) }}
The third parameter is the key of the currently selected option. Defaults to null.
First get and create list in Controller for example:
$username_lists = Users::lists('username','id');
pass data to view by:
return View::make('layouts.customers')
->with('username_lists', $username_lists);
now get in view:
{{ Form::select('username_lists', $username_lists, null, array('class' => 'form-control')) }}

Resources