I want to return the only fields I needed but when the collection has relationship it would not work.
For example:
$items = $items->map(function($item) {
return collect($item)->only([
'id',
'posts.title',
'name',
'created_at'
]);
});
Only thing that did not return is 'posts.title'
How to solve this?
Related
I am using brackets ui in my laravel admin panel
I am trying to sort my list by desc order with search as well but it is not working
My Controller and I have tried that
public function index(Request $request)
{
// create and AdminListing instance for a specific model and
$data = AdminListing::create(Order::class)->attachOrdering('id', 'desc')->processRequestAndGet(
// pass the request with params
$request,
// set columns to query
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note'],
// set columns to searchIn
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note']
);
if ($request->ajax()) {
return ['data' => $data];
}
return view('admin.orders.index', ['data' => $data]);
}
Have done this according to the documentation.
It does not give an error, but does not work as well.
Please add get() method
please modify the query like below.
$data = AdminListing::create(Order::class)->attachOrdering('id', 'desc')->processRequestAndGet(
// pass the request with params
$request,
// set columns to query
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note'],
// set columns to searchIn
['id', 'name', 'created_at', 'phone', 'total_amount', 'status','discount','user_order_note']
)->get();
I have user input following the rules below;
public function rules()
{
return [
'phone_number' => 'required|array',
'amount' => 'required|string|max:4',
'phone_number_debit' => 'required|string|max:15',
];
}
I would want to save the data in a model Transaction. For the phone_number it is an array that could have one value or multiple. So that leaves for foreach loop.
This is what I want to achieve, save different rows determined by the number of records in the array.
$transaction = new Trasaction();
$transaction->phone_number = $req->phone_number; //Value in the array
$transaction->amount = $req->amount;
$transaction->phone_number_debit = $req->phone_number_debit;
$transaction->save();
Save diffrent records according to the records in the phone_number array.
However I can not think of a way to achieve this.
Anyone?
try this :
$data = request(['amount', 'phone_number', 'phone_number_debit']);
foreach($data['phone_number'] as $phone_number) {
Trasaction::create([
'amount' => $data['amout'],
'phone_number' => $phone_number,
'phone_number_debit' => $data['phone_number_debit']
]);
}
make sure in your Trasaction modal you've set to fillable property like this :
class Trasaction extends Model
{
protected $fillable = ['amount', 'phone_number', 'phone_number_debit'];
}
There are many ways to do this, in a nutshell:
collect(request('phone_number'))->each(function ($phone) use ($req) {
$transaction = new Trasaction();
$transaction->phone_number = $phone; // element of the array
$transaction->amount = $req->amount;
$transaction->phone_number_debit = $req->phone_number_debit;
$transaction->save();
});
TL;DR
One-to-Many Relationship
In order to get a better code, you can create a transaction_phones table, creating a one-to-many relationship.
You'll create a TransactionPhone model and add this:
public function transaction()
{
return $this->belongsTo(Transaction::class);
}
The TransactionPhone migration:
Schema::create('transaction_phones', function (Blueprint $table) {
$table->increments('id');
$table->integer('transaction_id');
$table->string('phone_number');
$table->timestamps();
});
In your Transaction model you'll have the inverse:
public function phones()
{
return $this->hasMany(TransactionPhone::class);
}
public function addPhone($phone)
{
return $this->phones()->create(['phone_number' => $phone]);
}
And in you Controller:
$transaction = Trasaction::create(request()->only('amount', 'phone_number_debit'));
collect(request('phone_number'))->each(function ($phone) use ($transaction) {
$transaction->addPhone($phone);
});
I hope this answer can help you.
In yajra/laravel-datatables, I want to determine that current model is soft-deleted or not. if it is deleted , a success bootstrap class apply to row containing that model details.
this is my backend code:
$courses =
Course::select(['course_id', 'title', 'start_date', 'end_date', 'picture', 'lesson_count', 'status', 'active', 'teacher','start_date','end_date','reg_start_date','reg_end_date']);
if ($request->has('showDeleted') && $request->get('showDeleted') == 1) {
$courses = $courses->withTrashed();
}
$datatable = app('datatables')->of($courses)
->orderBy('created_at', 'desc')
//columns come here
->setRowClass(function ($course) {
return ($course->trashed() ? 'danger' : 'sdasd');
});
return $datatable->make(true);
As you see I used:
->setRowClass(function ($course) {
return ($course->trashed() ? 'danger' : ' ');
});
to apply desired class But $course->trashed return false always for all model instances even those is not trashed.
what is best solution?
I found the solution.
It was my mistake that I should included deleted_at field in columns selection on select method:
$courses =
Course::select(['course_id', 'title', 'start_date', 'end_date', 'picture', 'lesson_count', 'status', 'active', 'teacher','start_date','end_date','reg_start_date','reg_end_date','deleted_at']);
I have the following model.
class Training extends \Eloquent {
// Add your validation rules here
public static $rules = [
'name' => 'required',
'city' => 'required',
'province' => 'required',
'budget_year' => 'required|integer',
's_date' => 'required|date',
'e_date' => 'required|date'
];
// Don't forget to fill this array
protected $fillable = [
'name',
'city',
'province',
'budget_year',
's_date',
'e_date'
];
public function material(){
return $this->hasMany('Material');
}
public function budget(){
return $this->belongsToMany('Budget')->withPivot('amount');
}
public function budgetById($training_id){
$this->belongsToMany('Budget')->where('training_id', '=', $training_id)->get();
}
}
when I debug the budgetById method using DB::getQueryLog, the query is as follow
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id is null and training_id='6'
which return 0 rows, but when I try to modify the query and run it in pgadmin, the following script works well.
select budgets.*,
budget_training.training_id as pivot_training_id,
budget_training.budget_id as pivot_budget_id
from budgets inner join budget_training on budgets.id = budget_training.budget_id
where budget_training.training_id='6'
notice I remove training_id is null and from Laravel generated query. What is wrong with my budgetById method?
You have called get() and didn't use return here:
public function budgetById($training_id){
// = in where is optional in this case
$this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}
You should use like this:
public function budgetById($training_id){
// = in where is optional in this case
return $this->belongsToMany('Budget')->where('training_id', '=', $training_id);
}
In Lavarel 7.X, you can use the wherePivot method to filter columns on the pivot table, like this:
return $this->belongsToMany('Budget')->wherePivot('training_id', '=', $training_id);
or
return $this->belongsToMany('Budget')->wherePivotNotNull('training_id');
If I create a comment like this:
$post->comments()->create(array('body' => 'Comment message'));
And I have the model on my post:
public function comments()
{
return $this->morphMany('Comment', 'shared_comments');
}
It fills the polymorphic relationship field between post and comment.
I also have the model on my comment:
public function author()
{
return $this->belongsTo('User');
}
How can I also fill the 'user_id' field in the comment table?
You can just explicitly specify the user id in the array.
$post->comments()->create(array(
'body' => 'Comment message',
'user_id' => Auth::user()->id
));
Alternatively, you could create the comment and then insert the relationship with both the posts and users tables.
$post = Post::find($whatever);
$user = Auth::user()->id;
$comment = Comment::create(array(
'body' => 'Comment message'
));
$post->comments()->insert($comment);
$user->comments()->insert($comment);
In Laravel 4, you would use save($comment) instead of insert($comment) for the last two lines. This is a breaking change from Laravel 3.