Mohammadreza Ahmadpour
Mohammadreza Ahmadpour

Reputation: 111

remove & take out from the null entry

I have a project & branches model in Laravel, each project has many branches. this function is work very well but it saved Empty records from $request->branches

$data = $request->except('branches');
$branches = collect($request->branches)->transform(function($branch) {
    $branch['name'] = $branch['name'];
    return new Branch($branch);

});        

$data = $request->except('branches');
$data['user_id'] = $user->id;
$project = Project::create($data);
$project->branches()->saveMany($branches);
return response()->json(['created' => true,]);

I want to remove empty record from branches request. this is the log of array:

$request->branches:

 local.INFO: array (
  0 => 
  array (
    'name' => NULL,
  ),
) 

$branches (after collect) :

local.INFO: [{"name":null}]  

Upvotes: 0

Views: 42

Answers (2)

Mohammadreza Ahmadpour
Mohammadreza Ahmadpour

Reputation: 111

I use the reject function

->reject(function ($branch) {return empty($branch['name']);})

Upvotes: 0

Tirdad Abbasi
Tirdad Abbasi

Reputation: 737

You can use the filter function

$filteredBranches = $branches->filter();

See Documention.

Upvotes: 1

Related Questions