3

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.

    $detail = Barang_Keluar_Detail::findOrFail($id); //15
    $cariid = $detail->pluck('barang_keluar_id');
    $instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
    $instansiid = $instansiquery->pluck('instansi_id');
    $tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31

and the parameter are here

    $cariinstasama = Barang_Keluar::where('id', $cariid)
        ->orWhere(function ($query) use($instansiid, $tanggal) {
            $query->where('tanggal', "'$tanggal'")
            ->where('instansi_id', $instansiid);
        });

Please any help will be appreciated, thank you.

1
  • 6
    Your question is not clear actually or else you'd have definitely got an answer Commented Dec 16, 2019 at 7:12

3 Answers 3

6
+25

Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:

$cariinstasama = Barang_Keluar::where('id', $cariid)
    ->when($instansiid, function ($query, $instansiid) {
        return $query->where('instansi_id', $instansiid);
    })
    ->when($tanggal, function ($query, $tanggal) {
        return $query->where('tanggal', $tanggal);
    })->get();

For more info see https://laravel.com/docs/5.8/queries#conditional-clauses

Sign up to request clarification or add additional context in comments.

Comments

3

You can try this as well.

$cariinstasama = Barang_Keluar::where('id', $cariid);

if($instansiid !== null)
{
   $cariinstasama->where('instansi_id', $instansiid); 
}

if($tanggal !== null) 
{
   $cariinstasama->where('instansi_id', $instansiid);
}

$result = $cariinstasama->get();

Comments

0

Its not clear what exactly you want.

Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :

$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
     $query = $query->where( // if yes apply more parameters to the query
        [
           ['col1', $param1],
           ['col2', $param2]
        ]
     );
else
    $query = $query->where('col1', $param1);
$results = $query->get();

Hope it helps....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.