samedi 17 avril 2021

Configure database dynamically By using laravel api

Access database according to the user data in laravel API

I want to config a database connection according to users gives the host,port,databaseName,table name by these data I want to access a database in laravel.



via Chebli Mohamed

am trying to save product price inside billProduct table in every bill created

how to take price column and cost price from Product table and save it to BillProducts Table when creating Bill

this is the BillProducts Model Where i need to insert price and cost price in every time i create bill

class BillProduct extends Model
{
    protected $fillable = [
        'bill_id', 'product_id', 'quantity', 'unit', 'packing', 'remark', 'discount','price','cost_price'
    ];

    protected $appends = ['price','profit'];

    public function product()
    {
        return $this->belongsTo(Product::class)->withDefault();
    }


}

also, I have a product table where I do store all products information :

class Product extends Model
{
    use Translatable;

    public $translatedAttributes = ['description', 'title'];
    public $translationModel = ProductTranslation::class;


    const FILLABLE = ['price', 'quantity', 'cost_price', 'supplier_id','item_code'];
    protected $fillable = self::FILLABLE;

    public function createTranslation(Request $request)
    {
        foreach (locales() as $key => $language) {
            foreach ($this->translatedAttributes as $attribute) {
                $this->{$attribute . ':' . $key} = $request->get($attribute . '_' . $key);
            }
            $this->save();
        }
        return $this;
    }

    public function billProduct()
    {
        return $this->hasMany(BillProduct::class);
    }
}


Now every time I choose a product when creating a bill I need to save the product price also in billProducts Table 

I need to do that to avoid changing the bill total when updating any product 

also i use this function in model to create products in billProducts


    public function createProducts(Request $request)
    {
        foreach ($this->billProducts ?? [] as $billProduct) {
            $billProduct->product->updateQuantity($billProduct->quantity);
            $billProduct->delete();
        }
        $dataArr = [
            'status' => true,
            'item' => $this
        ];

        foreach ($request->products ?? [] as $product) {
            $productObj = Product::findOrFail($product['product_id']);
            if ($productObj->updateQuantity(-1 * $product['quantity'])) {
                $product['bill_id'] = $this->id;
                BillProduct::create($product);
            } else {
                $dataArr['status'] = false;
            }
        }
        $this->save();

        return $dataArr;
    }


enter image description here



via Chebli Mohamed

I want to get the students count with age break down using Laravel 7

I wrote the query to get the student's age but I want to have the breakdowns with age and the count. This is my query to getting each student's age.

$students = DB::table('students')->select(DB::raw('TIMESTAMPDIFF(YEAR, stud_dob, CURDATE())+0 AS age'))->orderBy('age')->get();

And I used one query to get the breakdowns but it's giving the wrong count for the students.

$ranges = [ // the start of each age-range.
            '18-24' => 18,
            '25-35' => 25,
            '36-45' => 36,
            '46+' => 46
        ];

$output = Student::where('stud_flag','1')
            ->get()
            ->map(function ($user) use ($ranges) {
                $age = Carbon::parse($user->stud_dob)->age;
                foreach($ranges as $key => $breakpoint)
                {
                    if ($breakpoint >= $age)
                    {
                        $user->range = $key;
                        break;
                    }
                }
                return $user;
            })
            ->mapToGroups(function ($user) {
                return [$user->range => $user];
            })
            ->map(function ($group) {
                return count($group);
            })
            ->sortKeys();

I want the output like. Please help me to fix this issue.

Range      Count 
------    --------

18 - 24     20
25 - 35     15
36 - 45     18
46+         30


via Chebli Mohamed

InvalidArgumentException

C:\xampp\htdocs\perpustakaan-digital>php artisan db:seed

InvalidArgumentException : You requested 1 items, but there are only 0 items available.

at C:\xampp\htdocs\perpustakaan-digital\vendor\laravel\framework\src\Illuminate\Support\Arr.php:476 472| 473| $count = count($array); 474| 475| if ($requested > $count) {

476| throw new InvalidArgumentException( 477| "You requested {$requested} items, but there are only {$count} items available." 478| ); 479| } 480|

Exception trace:

1 Illuminate\Support\Arr::random([]) C:\xampp\htdocs\perpustakaan-digital\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1497

2 Illuminate\Support\Collection::random() C:\xampp\htdocs\perpustakaan-digital\database\factories\BukuFactory.php:18

Please use the argument -v to see more details.



via Chebli Mohamed

vendredi 16 avril 2021

How to get currently inserted row id in laravel 5.5

Here I am using laravel 5.5. My code is

$result = DB::insert('INSERT INTO .......');

Here it returns true . But how can I get inserted id . In my table id is primary key . Thanks in advance



via Chebli Mohamed

Trying to get property of non-object while fetching data in laravel 5.2

<?php
    if(!empty(App\Http\Models\ApplicationData::getDataCodeHtml($application_data->application_data_id)))
    {
?>
        <p>{!! App\Http\Models\ApplicationData::getDataCodeHtml($application_data->application_data_id) !!}</p>
    }
?>

In the above code I am simply fetch data from model but what happen here In some application data are showing but in somewhere it show Trying to get property of non-object. I don't know why? I simply wants if data is not present then it show empty. So, How can I do this? Please help me.

Thank You



via Chebli Mohamed

Laravel application error 500 from SQLSTATE[42S22]: Column not found: 1054 Unknown column

I have a laravel application in xampp with php 7, when I want to login I get an error 500, if I check the error_log in the storage folder, I see that it is the following error:

[2021-04-16 23:36:32] live.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' (SQL: select * from `users` where `username` = admin and `users`.`deleted_at` is null limit 1)
{"exception":"[object] (Illuminate\\Database\\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' (SQL: select * from `users` where `username` = admin and `users`.`deleted_at` is null limit 1) at 
C:\\xampp\\htdocs\\p2\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:664, PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'username' in 'where clause' at C:\\xampp\\htdocs\\p2\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:326)

This is my first time whit laravel, I don't know how to resolve this issue, the code of the lines 326 and 664 are the next:

326

public function select($query, $bindings = [], $useReadPdo = true)
{
    return $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
        if ($this->pretending()) {
            return [];
        }

        // For select statements, we'll simply execute the query and return an array
        // of the database result set. Each element in the array will be a single
        // row from the database table, and will either be an array or objects.
        $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
                          ->prepare($query));

        $this->bindValues($statement, $this->prepareBindings($bindings));

        $statement->execute();

        return $statement->fetchAll();
    });
}
  1. Is only the catch of teh error, maybe could be usefull
protected function runQueryCallback($query, $bindings, Closure $callback)
{
   
    try {
        $result = $callback($query, $bindings);
    }

    // If an exception occurs when attempting to run a query, we'll format the error
    // message to include the bindings with SQL, which will make this exception a
    // lot more helpful to the developer instead of just the database's errors.
    catch (Exception $e) {
        throw new QueryException(
            $query, $this->prepareBindings($bindings), $e
        );
    }

I received this application from a company that has me as an intern, but they didn't give me any more help or guidance, they just want it to work. I appreciate any comments that can help me solve it.



via Chebli Mohamed