Laravel 5.3 Best practices - load lists from other models to populate dropdowns - laravel

i'm new to Laravel and i'm using InfyOm laravel generator to create an app.
I came to an issue and would like to know what is the best practice to do this:
I have a model "Mission". When creating a mission, it need to have a client id and agent id associated with it.
In my view, i want to display 2 dropdown lists, one containing all the active clients (id + name) and the other containing all the active agents (id + name).
my controller
public function create()
{
return view('missions.create');
}
my view blade
{!! Form::select('client_id', ?????? , null, ['class' => 'form-control']) !!}
Thanks for your suggestions

Most convenient way is to use pluck() method to build a list from a collection, for example:
public function create()
{
return view('missions.create', [
'users' => User::pluck('name', 'id')
]);
}
Then use $list variable:
{!! Form::select('client_id', $users , null, ['class' => 'form-control']) !!}

Related

How to query data from laravel relationship using vue.js? [ laravel, vue ]

I want to query my data in relationship using vue.js and still, I cant make it work.
Also, I got an errors like below.
[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
When I changed my code like this
<span v-for="user in users">
{{ user.address.city }}
</span>
And in my Controller
public function index(Request $request)
{
$query = Customers::with('address')
->with('purchases')
->paginate(10);
return CustomersResource::collection($query);
}
<div v-for="user in users">
<span v-if="user.address && user.address.name">{{ user.address.name }}</span>
</div>
Always check if your object exists before accessing it.
Add withDefault after your relationship.
public function address(){
return $this->belongsTo('App\Address','user_id','id')->withDefault([
'name' => '-'
]);
}
There is existing code that depends on the result of any Eloquent relationship to either be null, a Model instance, or a Collection of Model instances. However, the current functionality of the withDefault() method opens up the potential for returning an object that is not one of those three expected values.

Accessor parameter is giving me null in Laravel 5.3

I am working on one to many relationship between tasks and Projects, i.e. a task can only belong to a single project, and I have used laravel's Accessor to get the selected project in my view in drop down:
my code is as follow:
public function getAssignUserAttribute($value)
{
dd($value); // gives me null
// if $value have id of user I want to get that user from db
}
and my view contains the drop down is:
{!! Form::select('assign_user', $assign_user, null, ['class' => 'form-control select2', 'id' => 'assign_user']) !!}
I have accessed all the users from database into TasksController to the view as:
$assign_user = User::pluck('title', 'id');
return view('tasks.edit', compact('task', 'assign_user'));
But I get all users selected, while I only want to have the selected user in my drop down.
Can someone guide me to the right path.
Thank you
finally I solved the issue by myself I have edit the Accessor as follow:
public function getAssignUserAttribute()
{
return [0 => $this->attributes['assign_user'] ];
}
Since I required an array so I assigned the current user to the array index 0 and return, in that case the view selected the returned user in drop down :)
This may help someone :)

Form model binding for polymorphic relationship

I have set up a polymorphic relation where the table structure is like:
companies
id - integer
name - string
company_branches
id - integer
name - string
incharges
id - integer
name - string
inchargable_id - integer
inchargable_type - string
I have also set up the models accordingly and the data is saved correctly. The problem that I'm having is showing the data of the incharges table during editing by using model binding. The view for editing is like:
{!! Form::model($company, array("route" => array("companies.update", $company->id), "method"=>"PUT", "files"=>true)) !!}
<label>Company Name</label>
<div>
{!! Form::text('name') !!}
</div>
<label>Incharge Name</label>
<div>
{!! Form::text('incharge_name') !!}
</div>
{!! Form::close() !!}
The data that appears in the name text field while editing is correct. But how do I display the incharge name for editing? I can acess the incharge name by doing $company->incharge->name.
EDIT: In the PersonInCharge model, I have set up the polymorphic relation as:
public function inchargable()
{
return $this->morphTo();
}
In Company model:
public function incharge()
{
return $this->morphOne('PersonInCharge', 'inchargable');
}
In CompanyBranch model:
public function incharge()
{
return $this->morphOne('PersonInCharge', 'inchargable');
}
Try, {!! Form::text('incharge[name]') !!}
Further more you need to (lazy)-eager-load your relation for the form model binding. You can use the Model::with('realtion') or set the $with = ['relation'] property in your Eloquent model. More information about Laravel (Lazy-)Eager-Loading.
Try:
{!! Form::text('incharge_name', $company->incharge->name) !!}
Add in a join to your controller in this fashion:
$company = Company::where('id',$companyID)
->leftJoin('incharges', 'inchargable_id.company_id', '=', 'company.id')
->first();
(need to use the correct fields though!)

Laravel Foreign Keys Drop-down List

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.

Soft delete laravel : page does not exist or hard delete

I have a problem with sofdelete in Laravel ..
In my destroy method :
public function destroy($id)
{
$sessions = DB::table('sessions')->where('id','=', $id);
$sessions->delete();
Session::flash('flash_message', 'it works !');
return redirect()->route('sessions.index');
}
it doesn't make a soft delete ...
If i change the request using eloquent :
$sessions = Sessions::findOrFail($id);
$sessions->delete();
I have : Sorry, the page you are looking for could not be found.
In my view I created the form
{!! Form::open([
'method' => 'DELETE',
'route' => ['sessions.destroy', $session->id]
]) !!}
{!! Form::submit('delete?', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
I don't know why it doesn't work...
thanks for your help
You're saying that when you're using DB::table('sessions') it deletes the record and when you're using Sessions:: it doesn't
I think you don't understand what soft deleting is.
When you use DB::table('sessions'), the record will be just deleted and not soft deleted.
When you use Session::, the record will stay there but Eloquent will add deleted_at timestamp.
From the docs:
When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted.
Session is facade of laravel so it might be create issue for you. please refer following link
https://laravel.com/docs/5.6/session

Resources