I have 2 tables:
CUSTOMERS(id, full_name, company_id)
COMPANIES(id, company_name)
I already created the relation between the two tables, and it's working fine because I can display company name in the customers view like this: $customer->company->company_name
I'm now having issues with the customer create and edit views. I'd like to have the company_name as a drop-down (Form Select) in create and edit views. Then insert the company id to the CUSTOMERS table.
You need to supply Form::select with companies as an array('id'=>'name'):
// Controller, repo or wherever you want it:
$companies = Company::lists('company_name','id');
// $companies passed to the view, then in the create view:
{{ Form::select('company_id', $companies, null, $options) }}
// edit view:
{{ Form::model($customer, array('route' => array('YourCustomerUpdateRoute', $customer->id))) }}
...
{{ Form::select('company_id', $companies, null, $options) }}
// form model binding autopopulates the form, so correct option will be selected
After submitting the form validate the input, check if provided company_id exists on the companies table and save the customer, that's all.
The Jarek Tkaczyk answer is excellent. However if you want make a default value for create form and avoid pre-select the first element in the $companies array, you can do something like this in your controller:
$companies = Company::lists('company_name','id');
$companies = array('0' => 'Select Company') + $companies;
Then pass $companies array to the view as Jarek Tkaczyk said.
Note:
I did
$companies = array('0' => 'Select Company') + $companies;
in order to preserve the array keys.
Related
I a have a one to many relationship between culprits and crimes and also a one to many relationship between species and crime.
culripts
id
first_name
last_name
crimes
id
culprit_id
species_id
fishing_method_id
species
id
species_name
fishing_methods
id
fishing_methods_name
What I need to achieve is to save many species for one crime
my form
{{ Form::select('species_id',$speciesRepository, array('Action'), array('multiple', 'class' =>'form-control')) }}
my controller
public function store(CreateCrimeRequest $request)
{
$input = $request->all();
// $data = implode(',', $input);
// dd($data);
$crime = $this->crimeRepository->create($data);
Flash::success('Crime saved successfully.');
return redirect(route('crimes.index'));
}
When I select 3 species from the dropdown the last selected species is saved while the other two are not.
could anyone help to solve this
You are missing [ ] in your select name attribute
{{ Form::select('species_id[]', $speciesRepository, array('Action'), array('multiple', 'class' =>'form-control')) }}
You're missing () here:
$crime = $this->crimeRepository->create($data);
Must be:
$crime = $this->crimeRepository()->create($data);
You can use createMany too:
$crime = $this->crimeRepository()->createMany($data);
more examples here: https://laravel.com/docs/5.5/eloquent-relationships#the-create-method
Well, you have to code it to create three records in your pivot table. I assume you have a table of species You have a table of crimes. You need a belongsToMany relationship to store many species for one crime and a pivot table of crime_species You will then attach species to crime
and You are missing [ ] in your select name attribute
{{ Form::select('species_id[]', $speciesRepository, array('Action'), array('multiple', 'class' =>'form-control')) }}
I have a table in my database, say users with one of the columns being internal_id. I have a a list of users being displayed in view.blade.php
Now suppose each user is a link which when clicked displays the details of that user and each user has a unique internal_id. I want this internal_id to be used when called for all the column details of the user clicked. How can I do this?
First you need to create a route:
Route::get('user-profile/{internalId}', ['as' => 'profile', 'uses' => 'UserController#showProfile']);
Then you need to create a link. You can use simple URI:
{{ url('user-profile/'.$internalId) }}
Or you can use name of the route:
{{ route('profile', ['internalId' => $internalId]) }}
To get internal ID in a controller, do this:
public function showProfile($internalId)
{
$profile = User::where('internal_id', $internalId)->first();
....
}
//model
return $this->hasMany('App\Model\Order', 'customer_id')->select('name');
//controller
$customer = Model\customer::find($id);
return view('customer', array('data' => $customer));
//view (blade)
{{ $data }} //{"id":1,"name":"Tony"}
{{ $data->orders }} //[{"name":"T-shirt"},{"name":"Macbook"}]
i'm new in laravel
I have a question about passing data to view.blade
I used hasMany to join 2 table together and pass $data to view
when I try to output $data, I could not see order object inside of data object
but when I did $data->orders, it shows object
can anyone tell me how it works?
The behavior you are seeing is because Laravel lazy loads relations when they are accessed. If the relation has not been loaded, Laravel will send another query and add it to your $data object behind the scenes. That's why when you dump the $data variable, you are not seeing the orders.
To demonstrate, run the following snippet.
{{ $data }} //{"id":1,"name":"Tony"}
// Laravel will lazy load the orders relation
{{ $data->orders }} //[{"name":"T-shirt"},{"name":"Macbook"}]
// Now the $data object has the orders property.
{{ $data }} //{"id":1,"name":"Tony", "orders": [{"name":"T-shirt"},{"name":"Macbook"}]}
Solution
You have a couple options here. Here are 2.
1. Eager load relation when querying model.
$customer = Model\customer::with('orders')->find($id);
This is the preferred method as it prevents n+1 querying.
2. Load relation after model has been queried.
$customer = Model\customer::find($id);
$customer->load('orders');
Now when you dump the model, you will see the orders property.
In your model,
public function orders(){
return $this->hasMany('App\Model\Order', 'customer_id');
}
In view
{{ $data->orders->order_name }}
I hope it will works
You have defined hasMany relationship in your model. So, for a particular customer there can be multiple orders. So, it shows in array. You have to loop through:
foreach($data->orders as $order)
{
$order->name
}
to get the orders.
I have two collections on a single page which should be both paginated. But pagination generates the same Parameter for both (?page=X).
How can I solve that kind of an issue?
You can change the param of either pagination by
Paginator::setPageName('someparam');
Read more about Pagination here In the section Customizing The Paginator URI
Note : You should do this before paginator is done i.e.,
$yourCollection = Model::paginate(10);
Example :
I assume you have two pagination like this
Paginator::setPageName('yourFirstParam');
$firstCollection = FirstModel::paginate(10);
Paginator::setPageName('yourSecondParam');
$secondCollection = SecondModel::paginate(10);
Where you use this to get in your view
Paginator::setPageName('yourFirstParam');
$firstCollection->links();
Paginator::setPageName('yourSecondParam');
$secondCollection->links();
There is a way to "automatically" set the page name (in a sense), which I'll get to in a bit.
First, if we go over the paginate method, you'll see that it accepts a pageName argument as its 3rd parameter:
public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
Lets say you have a User and Post model. You can then do something like this in your controller:
$users = User::paginate(10, ['*'], 'users');
$posts = Post::paginate(10, ['*'], 'posts');
return view('example', compact('users', 'posts'));
It works like your normal pagination except the second argument specifies the columns you want to select and the third argument specifies the page name.
In your view, when you render your pagination links, you might run into a problem when you do this:
{!! $users->render() !!}
{!! $posts->render() !!}
While the pagination links will be rendered, when you click on a link to a posts page, the users query string parameter is gone. Therefore, the users are back to page one and vice versa.
To fix this, you can use the appends method to keep the query parameters for both models:
{!! $users->appends(['posts' => Request::query('posts')])->render() !!}
{!! $posts->appends(['users' => Request::query('users')])->render() !!}
All this works, but it's a bit ugly so how can we clean this up? You can create your own method to "automate" this process. In your model, you can add your own paginate method:
// Name it whatever you want, but I called it superPaginate lol
protected function superPaginate($perPage)
{
return $this->newQuery()->paginate(10, ['*'], $this->getTable());
}
This will automatically set the pagination name to the model's table name. So for the User model, the page name will be "users". For the Post model, the page name will be "posts".
There's still the problem with rendering links. You don't want to call appends all the time and specify the query parameters. To fix that, we can improve the superPaginate method into this:
protected function superPaginate($perPage, $columns = ['*'], $page = null)
{
$params = \Request::query();
return $this->newQuery()->paginate(10, $columns, $this->getTable(), $page)->appends($params);
}
Now, all you need to do is Model::superPaginate(10); and $models->render(). Everything should work properly.
hello I am in big trouble please help me about database fetch value show in drop down using laravel 4 my code is below
<?php //echo "<pre>"; print_r($user);exit; ?>
{{ Form::select($user, $user ) }}
in print_r($user); showing all database value fetch from database but i want to show only value = id , user name field I try for each but not working any idea how to show value=id , user name filed
and result showing in to the drop down like this
<select name="[{"id":"1","username":"skaka","name":"sandip","avatar_id":"1","gender":"1","dob":"1989-10-20","grade":"A","school":"kbpv","created_at":"2014-07-22 08:45:59","updated_at":"2014-07-22 08:48:04","parent_email":""},{"id":"2","username":"ttt","name":"test2","avatar_id":"2","gender":"2","dob":"1989-10-20","grade":"A","school":"kbpv1","created_at":"2014-07-22 08:58:25","updated_at":"2014-07-22 08:58:25","parent_email":""}]">
In order to use {{Form::select()}} the easiest way to achieve this is by calling your data from the database with lists() method.
So
$users = User::lists('username', 'id');
Now you have an array with data like this:
$users = [1 => 'skaka', 2 => 'ttt', ....];
So you are ready to use efficiently Form::select() by doing:
{{Form::select('dropdown_name', $users)}}