PHP Laravel: A better way than these if statements

PHP Laravel: A better way than these if statements

By : user2172915
Date : October 22 2020, 08:10 AM
around this issue I think the functions looks to "if-y" because your statements are more complicated than they have to be. Also you are always loading all of your fallbacks, which isn't neccessary in every case. I would refactor the function to only load the next level if necessary. This could look something like this:
code :
private function addDefaultOnlineCommission ( Price $price ) {

    // load the type commission
    $commission = $price->type->commissions()->where( 'is_online', '=', true )->first();

    // if there is no type commission, check client commission
    if( empty($commission) ){
        $commission = $price->type->client->commissions()->where( 'is_online', '=', true )->first();

    // if there is no client commission either, fall back to the default
    if( empty($commission) ){
        $commission = (object)Commission::DEFAULT_COMMISSIONS;

    $price->commissions()->create( [
        'commission_type'  => $commission->commission_type,
        'commission_value' => $commission->commission_value,
        'min_value'        => $commission->min_value,
        'is_online'        => true,
        'valid_from'       => Carbon::now()->format( 'Y-m-d H:i:s' ),
    ] );


Share : facebook icon twitter icon
How to make Aptana shows Laravel statements color in .php files(support Laravel)?

How to make Aptana shows Laravel statements color in .php files(support Laravel)?

By : Joao Natalino
Date : March 29 2020, 07:55 AM
Hope that helps Sublime Text 2 provides a package for Laravel Blade templates - this means it 'understands' the code and can colour it correctly.
This option does not exist in Aptana - so you cannot do it.
Where and If Statements Laravel Eloquent

Where and If Statements Laravel Eloquent

By : user2306246
Date : March 29 2020, 07:55 AM
seems to work fine Very similar to this: Method Chaining based on condition
You are not storing each query chains.
code :
$query = Scrapper::query();

if (Input::has('cat-id')) {
    $query = $query->where('cat_id', '=', Input::get('cat-id'));
if (Input::has('band')) {
    $query = $query->whereBetween('price', [$high, $low]);
if (Input::has('search')) {
    $query = $query->where('title', 'LIKE', '%' . Input::get($search) .'%');

// Get the results
// After this call, it is now an Eloquent model
$scrapper = $query->get();

Laravel 5 use statements

Laravel 5 use statements

By : user3312727
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further The process of using use statements in files is called aliasing or importing. http://php.net/manual/en/language.namespaces.importing.php gives a good explanation of it, but in short:
If you reference a class using a 'relative' or just the class's name(Such as Session), PHP is going to check the current namespace for the existence of that class. Laravel 4 controllers were not technically in a namespace. They were part of the root namespace of the application, and therefor a reference to another class in the root namespace (Session) would find just that. Laravel 5 controllers are namespaced in App\Http\Controllers\. The only way to solve this is to tell PHP the full namespace of a given class, such as in this case \Session, as these classes are added as part of the root namespace. An example would be something like new \App\MyCompany\Models\SomeModel(); The "use" statements at the top of a class file allow you to alias these full class-paths as anything you want. use \App\MyCompany\Models\SomeModel as Foo would allow you to do new Foo() and get an instance of \App\MyCompany\Models\SomeModel. (Most would leave off the 'as' statement, and just reference new SomeModel()) There is no way, nor need to try, to avoid adding these use statements to your classes when trying to leverage classes that are in a different namespace from the current class. It is a useful construct of the language, and not a limitation.
Laravel 5.3 Learning if statements

Laravel 5.3 Learning if statements

By : ITBerger
Date : March 29 2020, 07:55 AM
I hope this helps you . all() returns a collection. Many ways to skin this cat, but I think you're looking for isEmpty()
code :
if($posts->isEmpty()) { ... } 
How to get rid of too many if statements in laravel?

How to get rid of too many if statements in laravel?

By : Sri
Date : March 29 2020, 07:55 AM
hope this fix your issue I would like to create a more readable code by eliminating too many if statements but still does the job. I have tried creating a private method and extract the date range query and return the builder instance but whenever I do that, it does not return the correct builder query result so I end up smashing everything up on this method. , for your suggestions but I came up with another solution:
code :
 * @param array $params
 * @param $orderBy
 * @param $sortBy
 * @return Collection
public function findOrdersBy(array $params, $orderBy = 'id', $sortBy = 'asc'): Collection
    $release_date_start = array_get($params, 'release_date_start');
    $release_date_end = array_get($params, 'release_date_end');

    $orders = $this->model->newQuery();

    if (!is_null($release_date_start) && !is_null($release_date_end)) {
        $orders->whereBetween('releaseDate', [$release_date_start, $release_date_end]);
    } else {
        if (!is_null($release_date_start)) {
            $orders->where('releaseDate', '>=', $release_date_start);
        } else {
            if (!is_null($release_date_end)) {
                $orders->where('releaseDate', '<=', $release_date_end);

    $fields = collect($params)->except($this->filtersArray())->all();
    $orders = $this->includeQuery($orders, $fields);

    return $orders->orderBy($orderBy, $sortBy)->get();

 * @param Builder $orderBuilder
 * @param array $params
 * @return Builder
private function includeQuery(Builder $orderBuilder, ... $params) : Builder
    $orders = [];
    foreach ($params as $param) {
        $orders = $orderBuilder->where($param);

    return $orders;

 * @return array
private function filtersArray() : array
    return [
Related Posts Related Posts :
  • Running two PHP versions on the same server (STRETCH)
  • Checking if a file has been selected for upload
  • Model not updating laravel
  • How to add a description of words from text to an array, to an array key by passing words?
  • Nginx rewrite rule not not passing variables if "/" is at the end of the url
  • Modify decimal point and thousands separator without changing the number of decimals
  • Remove PHP errors from CLI and PHPMyAdmin
  • Yii2 rest api - Url manager add parameters
  • 1-query batch update array of users using PDO
  • Keep getting error: implode(): Invalid arguments passed when updating data
  • Laravel 5.4 - Correct Validation rule for a required parameter that can be zero
  • What does this code mean: $objPHPExcel->getActiveSheet()->toArray(null, true,true,true)
  • Data not being added to mysql table but echo's the data?
  • While fetch row in PHP
  • IP long string filter
  • How to view first image in list per user as its highlight Profile
  • Insert multiple rows from array
  • PHP : How to remove a duplicate array item ONCE
  • Print the input box text as simple text instead of html tag
  • How to read a string variable in php as $_GET or $_POST?
  • MySQL query fetch array not working
  • LogicException with message '... must return a relationship instance.'
  • PHP - create new array with only selected keys from an existing array
  • How to allow backgrounding a process to survive a session termination?
  • How to redirect to Home page (Default page) in zend framework 2?
  • I want to call a jquery variable in php syntax
  • Disabling the default /?add-to-cart= animation on buttons in Woocommerce
  • How to use query data for another sql query in yii2
  • Replace string enclosed in specified characters based on data type
  • Symfony FormType: how to get prototype in form type file
  • Handle reply messages properly after some operations in php
  • PHP Changed Domain, how to remove old Session Cookies
  • mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in php
  • Error: Call to a member function update() on array laravel
  • How to change the format of a float number?
  • run ajax requests by order
  • Wordpress Install 404 Error (Cannot view login in browser)
  • Calcinai xero-php pass config once
  • Fatal error calling to undefined function in PHP file
  • Laravel hasMany and belongsTo parameters
  • How do I call a Controller method in php Laravel?
  • How to replace "@" post tag with regex in PHP?
  • Laravel : when insert record in table. How can i add that Record in the list without querying the db
  • It is possible that I could user email address to get customer id from simPRO API?
  • PHP add and merge sql result
  • laravel ckeditor dark theme
  • Laravel belongsToMany not working
  • laravel 5.4 datatables not working jquery $ referenceError
  • Zend Form 2 multiselect field is empty after validation
  • PHP - Laravel 5 get data to html table from 3 SQL database tables with column DATA as headers
  • Can't use token authorization with Laravel Passport
  • splitting lines of dates and presenting in desired format
  • Laravel 5.2 Heroku Deployment Failed to install system packages
  • Laravel relationships - are there multiple *unnecessary* database calls?
  • htaccess rewrite rule for serving index.php from parent directory
  • PHP/MongoDB - $concat aggregation
  • Remove ajax.googleapis.com from my Wordpress site
  • Image saved always empty with Storage::put in Laravel
  • How to count and sort data in junction table
  • Get common number of values in a single array
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org