mardi 31 mai 2022

Laravel Eloquent Query Building ORM

Let's assume, There Is two Table 'student' & 'state', 'student' table contain 'id', 'name', 'state_id'. and 'state' table contain 'id', 'state_name'. In 'student' table contain the corresponding State ID.

Now I want to fetch the student's details including the state name. (Note: In the student table, I contain only the state id) How can I achieve this?



via Chebli Mohamed

lundi 30 mai 2022

DateTime::__construct(): Failed to parse time string (May 5 2022 12:00:00:AM) at position 20 (:): Unexpected character

I'm having the following error

"

ErrorException in /*/web/vendor/nesbot/carbon/src/Carbon/Carbon.php line 555:
DateTime::__construct(): Failed to parse time string (May 5 2022 12:00:00:AM) at position 20 (:): Unexpected character

In my list file,

         

    

The date in sql is a date time "2020-05-20 08:13:00.000"

I've tried some changes like format from DateTime to format to day, I've tried also to parse string and nothing worked.. I've seen some post with the same error but nothing result. Please help me



via Chebli Mohamed

Data repeat for eloquent query in Laravel 8

$data = EmpData::leftJoin('states', 'states.id', 'emp_data.empState')
        ->leftJoin('districts', 'districts.id', 'emp_data.empDistrict')
        ->selectRaw('emp_data.*, states.name as stateName')
        ->selectRaw('emp_data.*, districts.name as districtName')
        ->paginate(30); 

In my model 'EmpData' I contain state id and district id, and the 'state' & 'district' table includes the name of the state or district. so I use left join. Data fetch correctly, but it returns 4 times data, how can I fix it.



via Chebli Mohamed

dimanche 29 mai 2022

How can I upload pictures with queue in laravel

When uploading many images, and the size is large, it takes a lot of time, and sometimes the site appears to be unavailable due to the large size. Can this problem be solved?



via Chebli Mohamed

How to do login using angular and laravel api?

login.component.html

<form class="form-horizontal" #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
    <fieldset>
        <div class="control-group">
            <label class="control-label" for="email">E-mail</label>
            <div class="controls">
                <input type="text" id="email" name="email" placeholder="" class="input-xlarge" ngModel>
            </div>
        </div>

        <div class="control-group">
            <label class="control-label" for="password">Password</label>
            <div class="controls">
                <input type="password" id="password" name="password" placeholder="" class="input-xlarge" ngModel>
            </div>
        </div>

        <div class="control-group">
            <div class="controls">
                <button class="btn btn-success">Login</button>
            </div>
        </div>
    </fieldset>
</form>

login.component.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

    constructor(private http:HttpClient) { }

    ngOnInit(): void {
    }

    onSubmit(form:NgForm){
        const email = form.value.email;
        const password = form.value.password;
        this.http.post("http://127.0.0.1:8000/api/signin",{
            email: email,
            password:password
        }).subscribe((res)=>{
            console.log(res);
        },
        err=>{
            console.log(err);
        });
    }
}

api.php

Route::post('/signin', 'AdminController@signin')->name("signin");

AdminController.php

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use DB;

class AdminController extends Controller
{
    public function signin(Request $request)
    {
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) 
        {
            return response(['message'=>'login success!!'], 200);
        }
        else
        {
            return response(['message'=>'Login details are invalid'], 200);
        }
    }
}

I am new in angular and In above code I am simply want to login using angular and laravel web API. What happen here I am successfully pass parameter using angular and also successfully got in AdminContoller function i.e. signin function when I try to print to check the value of email and password then it show successfully but when I try to login via email and password then it always show Login details are invalid message. I don't know where am I doing wrong? Please help me.

Thank You



via Chebli Mohamed

vendredi 27 mai 2022

how can I make each

i have the following code in php using laravel blade which allows me to get all the days of the current month as a table , I want to make each "" clickable with php , im not sure if thats possible.

    <table class="table-bordered">
  <tbody>
@php
$date = date('F Y');//Current Month Year
$row_count=0;
$col_count=0;

while (strtotime($date) <= strtotime(date('Y-m') . '-' . date('t', strtotime($date)))) {
if($row_count%4==0){
        echo "<tr>";
        $col_count=1;
     }
    $day_num = date('j', strtotime($date));
    $month_num = date('m', strtotime($date));
    $day_name = date('l', strtotime($date));
    $day_abrev = date('S', strtotime($date));
    $day = "$day_name $day_num";
    $date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
    echo '<td>' . $day . '</td>';
    if($col_count==4){
           echo "</tr>";
        }
        $row_count++; 
        $col_count++; 
}
@endphp
  </tbody>
</table>


via Chebli Mohamed

mercredi 25 mai 2022

php artisan optimize handling the post-update-cmd event returned with error code 255

I run composer update to laravel 5.2 project. The website returns HTTP:500 error and php artisan commands returns blank. Please help me with your experience



via Chebli Mohamed

mardi 24 mai 2022

Compare payments.student_id and enroll.student_id if not the payment button should display in laravel

process: from the student registration (enroll) page (figure 3) should be able to check whether student paid or not, if not paid Pay button should be visible. else display PAID message.

to do the above process I should check the enroll table (figure 1) student id with payment table (figure 2) student id ,

index controller code:

  public function index()
    {
 $enrolls = Enroll::where('is_paid_admission',1)->orderBy('id','DESC')->get();

  $payments = DB::table('payments')
                ->join('enrolls','payments.enroll_id','=', 'enrolls.id')
                ->where('payments.student_id','=','enrolls.student_id')
                ->get();
         return view('enroll.index',compact('enrolls','payments'));
    }

ERROR Message shows :

 ErrorException (E_ERROR)
Property [student_id] does not exist on this collection instance. (View: C:\wamp64\www\SRVSYS2021\resources\views\enroll\index.blade.php)
Previous exceptions

    Property [student_id] does not exist on this collection instance. (0)

error message

INDEX Page Code if condition:

 @if ( $enroll->student_id == $payments->student_id )
          <td>  </td>
               
          @else
          <td><a href="" class="btn btn-info btn-xs" role="button">  <i class="fa fa-money"> PAY </i></a></td>
          @endif

(All the details have been attached below)

figure 1: Enroll table figure 1: enroll table

figure 2: payments table

figure 2: payments table

figure 3: page view of enroll table

enrollment page view

I hope you can understand my question. please give me your valuble ideas to solve this problem

QUESTION: I want to compare the student_id on ENROLL_TABLE & PAYMENT_TABLE, and show the payment button if not paid. (payment table only store if the student paid only) whatever the possible answer appreciate



via Chebli Mohamed

Why Respones api time in cloudflare is much more than local server?

If the local time arrives at 200 ms, it reaches 3 seconds in the cloudflare.Why is there such a difference between the ttfb time, even though both Local and cloudflare are the same project? There is also caching Everything in the cloudflare.But I don't understand why there is such a difference ttbf time.

[(local : ttfb = 200.03ms,content download = 6.66ms ),(cloudflare: ttfb = 3.64s, contnet download = 182.06ms)]

I did my best to increase the speed of my website api, and I haven't got the desired result yet.I have also done caching in my web application. I have checked the speed of the controller very carefully through many monitoring tools.Checked by Monitoring tool, my query's average time also comes around 50 ms.

Is this a problem? If so, what is the solution?



via Chebli Mohamed

lundi 23 mai 2022

Laravel 9 add new key and values using crossJoin collection

so i have a table Items my table has a row product and price only. my goal is how to add key with values using crossJoin collect

here is my code when fetching all data in my table im using each collect to add new row with values

public function ProductList(){
    $items = Item::all(); //rows only 'product', 'price'
    $Brand = collect($items)->each(function($newRow){
        $newRow->color = 'Blue'; // adding this in row
        $newRow->size = 'Large'; // adding this in row
    });
    return $Brand ;
}

here is the output of that code

[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
}
]

in the output color and size has been added to key with the values of blue and large. but that it's not the output i want to show. i want is each items color have a BLUE , BLACK , WHITE and size LARGE , MEDIUM , SMALL

like this code: ( i will not include the price )

   public function test(){
        $item = ['Lee','Jeans','Guess','Levis'];
        $size = ['LARGE','MEDIUN','SMALL'];
        $color = ['BLUE','BLACK','WHITE'];
        return collect($item)->crossJoin($size,$color);
    }

the output of this

  [
    [
    "Lee",
    "LARGE",
    "BLUE"
    ],
    [
    "Lee",
    "LARGE",
    "BLACK"
    ],
    [
    "Lee",
    "LARGE",
    "WHITE"
    ],
    [
    "Lee",
    "MEDIUN",
    "BLUE"
    ],
    [
    "Lee",
    "MEDIUN",
    "BLACK"
    ],
    [
    "Lee",
    "MEDIUN",
    "WHITE"
    ],
    [
    "Lee",
    "SMALL",
    "BLUE"
    ],
    [
    "Lee",
    "SMALL",
    "BLACK"
    ],
    [
    "Lee",
    "SMALL",
    "WHITE"
    ],
    [
    "Jeans",
    "LARGE",
    "BLUE"
    ],
    [
    "Jeans",
    "LARGE",
    "BLACK"
    ],
    [
    "Jeans",
    "LARGE",
    "WHITE"
    ],
    [
    "Jeans",
    "MEDIUN",
    "BLUE"
    ],
    [
    "Jeans",
    "MEDIUN",
    "BLACK"
    ],
    [
    "Jeans",
    "MEDIUN",
    "WHITE"
    ],
    [
    "Jeans",
    "SMALL",
    "BLUE"
    ],
    [
    "Jeans",
    "SMALL",
    "BLACK"
    ],
    [
    "Jeans",
    "SMALL",
    "WHITE"
    ],
    [
    "Guess",
    "LARGE",
    "BLUE"
    ],
    [
    "Guess",
    "LARGE",
    "BLACK"
    ],
    [
    "Guess",
    "LARGE",
    "WHITE"
    ],
    [
    "Guess",
    "MEDIUN",
    "BLUE"
    ],
    [
    "Guess",
    "MEDIUN",
    "BLACK"
    ],
    [
    "Guess",
    "MEDIUN",
    "WHITE"
    ],
    [
    "Guess",
    "SMALL",
    "BLUE"
    ],
    [
    "Guess",
    "SMALL",
    "BLACK"
    ],
    [
    "Guess",
    "SMALL",
    "WHITE"
    ],
    [
    "Levis",
    "LARGE",
    "BLUE"
    ],
    [
    "Levis",
    "LARGE",
    "BLACK"
    ],
    [
    "Levis",
    "LARGE",
    "WHITE"
    ],
    [
    "Levis",
    "MEDIUN",
    "BLUE"
    ],
    [
    "Levis",
    "MEDIUN",
    "BLACK"
    ],
    [
    "Levis",
    "MEDIUN",
    "WHITE"
    ],
    [
    "Levis",
    "SMALL",
    "BLUE"
    ],
    [
    "Levis",
    "SMALL",
    "BLACK"
    ],
    [
    "Levis",
    "SMALL",
    "WHITE"
    ]
  ]

so i tried this code but the output i want is not like this.

  public function ProductList(){
        $items = Item::all(); //rows only 'product', 'price'
        $statusBrand = collect($items)->each(function($newRow){
            $newRow->color = 'Blue'; // adding this in row
            $newRow->size = 'Large'; // adding this in row
        })->crossJoin(['BLUE','WHITE','LARGE'],['LARGE','MEDIUM','SMALL']);
        return $statusBrand;
    }

output of this:

[
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"BLUE",
"LARGE"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"BLUE",
"MEDIUM"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"BLUE",
"SMALL"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"WHITE",
"LARGE"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"WHITE",
"MEDIUM"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"WHITE",
"SMALL"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"LARGE",
"LARGE"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"LARGE",
"MEDIUM"
],
[
{
"id": 1,
"product": "Lee",
"price": "500",
"color": "Blue",
"size": "Large"
},
"LARGE",
"SMALL"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"BLUE",
"LARGE"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"BLUE",
"MEDIUM"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"BLUE",
"SMALL"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"WHITE",
"LARGE"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"WHITE",
"MEDIUM"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"WHITE",
"SMALL"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"LARGE",
"LARGE"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"LARGE",
"MEDIUM"
],
[
{
"id": 2,
"product": "Jeans",
"price": "400",
"color": "Blue",
"size": "Large"
},
"LARGE",
"SMALL"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"BLUE",
"LARGE"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"BLUE",
"MEDIUM"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"BLUE",
"SMALL"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"WHITE",
"LARGE"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"WHITE",
"MEDIUM"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"WHITE",
"SMALL"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"LARGE",
"LARGE"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"LARGE",
"MEDIUM"
],
[
{
"id": 3,
"product": "Guess",
"price": "300",
"color": "Blue",
"size": "Large"
},
"LARGE",
"SMALL"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"BLUE",
"LARGE"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"BLUE",
"MEDIUM"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"BLUE",
"SMALL"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"WHITE",
"LARGE"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"WHITE",
"MEDIUM"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"WHITE",
"SMALL"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"LARGE",
"LARGE"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"LARGE",
"MEDIUM"
],
[
{
"id": 4,
"product": "Levis",
"price": "200",
"color": "Blue",
"size": "Large"
},
"LARGE",
"SMALL"
]
]

in that code the crossJoin data entries has been added outside of the data array the output i want to show is the color and size will be add in the data each of them



via Chebli Mohamed

Laravel single blade file used for create and show

Is it possible and recommended that I have one lets say form.blade.php with html form file used for create new data and show existing data by ID.

I want to create this becouse file for insert and dispaly is the some. I want to avoid DRY.

Example: I have product categories, when I create a new category I need create.blade.php a file containing an html form. Now I want to use that same file to display the details of that category that will populate the fields in the fields by the given ID

Controller

   // Create 
   public function create()
   {
      return view('admin.category.form');
   }


  // Show
   public function show(Category $category)
   {
      $category = Category::find($category);

      return view('admin.category.form', [
          'category' => $category
      ]);
   }

Or is it better to make a separate file for insert and separet file for show?



via Chebli Mohamed

dimanche 22 mai 2022

How to include the blade file in to another blade file modal popup using Laravel

I developed the one product details blade file and I want to include another blade file inside the product details page modal popup and this blade file doesn't have a different layout. and I included the second blade file controllers in the product details page controller. Please help me with how to include this blade file.



via Chebli Mohamed

samedi 21 mai 2022

Need to pull out subscription that fallen under condition

I have some issue to resolve the complex nested eloquent whereHas in laravel. I would like to achieve the scenario by using below eloquent query.

The user should only be allowed view the subscription although the subscription has 7 days unpaid invoice and his/her previous invoice must be paid. If the user completed all the unpaid invoice, the subscription should also be displayed

Below are my current model design Subscription

public function invoice(){
        return $this->hasMany(Invoice::class,"subscription_id","id");
}

Invoice

public function subscription(){
        return $this->belongsTo(Subscription::class,"invoice_id","id");
}

Invoice_Status

$s = Subscription::whereHas('invoice',function($q){
        $q->whereHas('status',function($q){
            $q->where(function($q){
                $q->where("status","Unpaid")->whereRaw("DATE_ADD(invoices.created_at,INTERVAL 7 DAY) > CURDATE()");
            })->orWhere(function($q){
                $q->whereHas('invoice.',function($q){
                    $q->latest()->first()->whereHas('status',function($q){
                        $q->where('status','Paid');
                    });
                });
            });
        ->orWhere(function($q){
            $q->latest()->first()->whereHas('status',function($q){
                $q->where('status','Paid');
            });
        });
    })->get();

What I have achieved right now, I can pull those subscription that have unpaid order within 8 day from the date he accessed but if there's no unpaid order, the subscription wont have any data. I no sure which part I have did wrong.



via Chebli Mohamed

Call to undefined function curl_init() on console Command laravel

I want call curl_init() on console Command laravel but getting error "Call to undefined function curl_init()" ?

but when I call curl_init() from Controller laravel is working fine. Any Ideas?



via Chebli Mohamed

jeudi 19 mai 2022

How can I decode a Laravel encrypted String in VB.Net

I can't seem to find a valid answer to this issue...

I am encrypting a password in Laravel using the built in Crypt::encrypt() helper function and passing in a simple string value (let's say 'abcde' for the purpose of this example) I don't want to install any 3rd party libraries in Laravel if I can help it. I also have my Laravel APP_KEY which is a string value starting with Base64:, but I'm not sure where this comes into it.

This generates me an encrypted string to which I pass down to a VB.Net application. I cannot workout how to simply decode the encrypted string in my application to pluck out the raw password of 'abcde'.

I have tried many examples that I can find online, but I keep getting errors about "Not a valid key" or "Not a valid Base64 string", etc.

Does someone have an example of a code snippet that will decode a Laravel encrypted string in .Net?

The best I can get to is breaking the encrypted string down into iv, value and mac, but I can't seem to get any further.

Any help would be appreciated.



via Chebli Mohamed

I am currently using pdftk to generate a fiilable pdf with the data required. However, the data can be for multiple forms

For example, my pdf is fillable and has a attribute name : to be filled However, while generating for a single name Megatron eg. the file generates once but I will have n amount of names which will result in n numbers of output. Is there a way through pdftk that I am able to get the every single separately generated pdf into one single pdf



via Chebli Mohamed

make looping table laravel, where in specific data make a new table

Please help me... i want make table with laravel like this the table i want

but this is what i came up with thead does not appear

this is my code (index.blade.php)


    <?php $index = 0 ?>
    <?php $tempRek = array()?>
    @foreach($datatabel as $datatabel)
    <table id="table" class="table table-striped table-bordered table-hover" style="width: 100%; border-collapse:collapse" border="1">
    @if($index == 0)
      <thead>
        <tr class="judul" id="thead">
          <th width="10%">TANGGAL</th>
          <th width="30%">URAIAN</th>
          <th>REFERENSI</th>
          <th width="10%">DEBET</th>
          <th width="10%">KREDIT</th>
          <th width="10%">SALDO</th>
        </tr>
      </thead>
    @endif
    <?php $index++ ?>
      <tbody>
          <tr>
            <td width="10%"><center></center></td>
            <td width="30%"></td>
            <td></td>
            <td width="10%"></td>
            <td width="10%"></td>
            <td  width="10%" style="text-align: right;"></td>
          </tr>
            <?php $display = FALSE;
            if (!in_array($datatabel['kode'], $tempRek)) {
              $tempRek[] = $datatabel['kode'];
              $display = TRUE;
            }
            ?>
            <b>
            
            
          @if($tempRekening != $datatabel['kode'])</b>
      </tbody>
    </table>
    @endif
    @endforeach

I've been stuck for 2 days...



via Chebli Mohamed

Laravel many times route access

I want to know if Laravel has any route control, not for authentication, but for counting access. That is, I need to know the many times I have accessed this route. Is it possible in Laravel?

Or how can I do this? Is it necessary to store in my database?



via Chebli Mohamed

Laravel 5: Call to undefined method Redis::connection()

I am using redis to publish notifications. Here is how I am suing it:

$redis = \Redis::connection();

I am using _ide_helper package so when I ctrl+click on connection method it takes me to _ide_helper.php:

class Redis extends \Illuminate\Support\Facades\Redis{
        
        /**
         * Get a specific Redis connection instance.
         *
         * @param string $name
         * @return \Predis\ClientInterface|null 
         * @static 
         */
        public static function connection($name = 'default'){
            return \Illuminate\Redis\Database::connection($name);
        }
}

So the method does exist. But it gives me the error:

Call to undefined method Redis::connection()

I am using Homestead with Ubuntu 18.04. My PHP version is 7.1.33 with Laravle 5.5. Whatam I doing wrong here? What is the solution?



via Chebli Mohamed

mercredi 18 mai 2022

Laravel hasOne can't only one attribute from the relation model

I have a Model called User That has one to many relation with orders I'm trying to get using an eloquent relation the first order date he did

I tried adding in the User Model

public function firstOrderDate(){
return $this->hasOne(Order::class)->oldest();
}

My Query

User::whereHas('firstOrderDate')->with('firstOrderDate')->get()

it's returning the Whole Order model I even tried to add select('date') it's returning null now



via Chebli Mohamed

Command "make:import" is not defined

I've installed the Laravel excel as it's required

but I can't run this commande : php artisan make:import TextsImport --model=TextReg

the error : Command "make:import" is not defined.

I would be grateful if anyone could help me to solve this problem



via Chebli Mohamed

mardi 17 mai 2022

Why Redis keys are not created sometimes?

Radis doesn't get cached when I name getFeaturedCatalogsBySubCategoryId but it does get cache when I name getFeaturedCatalogBySubCategoryId.

The code format is this...

not working

if (!Cache::has("getFeaturedCatalogsBySubCategoryId:7e6xbmsd929914d:3nmlshec8da391f:1:10")) {
  $result = Cache::rememberforever('getFeaturedCatalogsBySubCategoryId:7e6xbmsd929914d:3nmlshec8da391f:1:10', function () {
    return DB::select('SELECT * FROM users');
  });
}

It doesn't work when I write like getFeaturedCatalogsBySubCategoryId but it works when I write like getFeaturedCatalogBySubCategoryId.This problem has been found with many cache keys so what can be the solution.



via Chebli Mohamed

lundi 16 mai 2022

Dompdf Laravel return certain table in view as black block

I am using barryvdh/laravel-dompdf version 0.8.4 in Laravel 5 to create a PDF from a view.
Before i do composer update, the pdf working just fine, but now its showing up like this enter image description here
It was supposed to be like this enter image description here

This is the view for the black part

    <table class="header" style="table-layout:fixed;width:100%;background-color:none;border-collapse: collapse;">
            <thead>
                <tr width="100%"><th>
                    <div style="font-weight:200;font-size:16px;margin-top:10px;text-align: center;">
                        <br>
                        <b>COACHING REPORT</b><br>
                        <b>SEMESTER 
                        @if(date('m', strtotime($detail->date)) > 6) 1 @else 2 @endif   
                        - TAHUN PELAJARAN </b>
                    </div>
                    <div style="width: 100%;font-size:11px!important;margin-top:10px">
                        <table style="width: 100%;text-align:left;">
                            <tr style="background: none;">
                                <td style="width: 15%;">Nama Coach</td>
                                <td>:</td>
                                <td style="width: 85%;"></td>
                            </tr>
                            <tr style="background: none;">
                                <td>Nama Coachee</td>
                                <td>:</td>
                                <td></td>
                            </tr>
                            <tr style="background: none">
                                <td>Kelas</td>
                                <td>:</td>
                                <td> </td>
                            </tr>
                            <tr style="background: none;">
                                <td>Periode</td>
                                <td>:</td>
                                <td> -  </td>
                            </tr>  
                        </table>
                    </div>
                </th></tr>
            </thead>
        </table>

This is the view for the bottom part that works just fine

    <table class="tableBorder" width="100%"
            style="margin-top: 10px; clear: both; top: 80px;border-collapse: collapse;">
            <thead>
                <tr class="tableBorder">
                    <th
                        style="font-size: 11px; margin:  5px !important; font-weight: 120;width:7%;">
                        <b>AREA / RANAH PERKEMBANGAN</b></th>
                    <th
                        style="font-size: 11px; margin:  5px !important; font-weight: 120;width:10%;">
                        <b>DESKRIPSI</b></th>
                </tr>
            </thead>
            <tbody class="bordered" style="">
                <tr class="tableBorder">
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        Perkembangan akademik</td>
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        {!! $isi[0] !!}
                    </td>
                </tr>
                <tr class="tableBorder">
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        Perkembangan sikap sosial</td>
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        {!! $isi[1] !!}
                    </td>
                </tr>
                <tr class="tableBorder">
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        Perkembangan karakter</td>
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        {!! $isi[2] !!}
                    </td>
                </tr>
                <tr class="tableBorder">
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        Perkembangan ketrampilan/minat/bakat/talenta</td>
                    <td
                        style="font-size: 11px; margin: 5px !important; font-weight: 60;">
                        {!! $isi[3] !!}
                    </td>
                </tr>
            </tbody>
        </table>

I try to comment the table,thead,tr,and th part, and leaving just the div and its finally showing up, but I have a lot of view that use this, so i was wondering if i can just fix this from the dompdf part without changing the view.



via Chebli Mohamed

vendredi 13 mai 2022

how add image upload in TinyMCeditor laravel

i'm trying to upload images in between my blog content but when i select images from the gallery its shoes the error Route[/] not found, even though the route is defined correctly create.blade.php

<div class="wt-formtheme wt-userform wt-userformvtwo">
{!! Form::textarea('content', null, ['class' => 'wt-tinymceeditor', 'id' => 'wt-tinymceeditor', 'placeholder' => trans('lang.blog_desc_note')]) !!}
 <input name=image type=file id="contentpics" onchange="">
</div>

app.js

tinymce.init({
    selector: "textarea.wt-tinymceeditor",
    height: 300,
    theme: "modern",
    plugins: [
      "code advlist autolink lists link image charmap print preview hr anchor pagebreak",
    ],
    menubar: false,
    statusbar: false,
    toolbar1:
      "undo redo | insert | image | styleselect | bold italic | alignleft aligncenter alignright alignjustify code",
          image_advtab: true,
          automatic_uploads:true,
          images_upload_url:'/upload',
          file_picker_callback: function(callback, value, meta) {
            if (meta.filetype == 'image') {
              console.log("im image")
              $('#contentpics').trigger('click');
              $('#contentpics').on('change', function() {
                var file = this.files[0];
                console.log(file);
                var reader = new FileReader();
                reader.onload = function(e) {
                  callback(e.target.result, {
                    alt: ''
                  });
                };
                reader.readAsDataURL(file);
              });
            }
          },
    image_advtab: true,
    inline_styles: true,
    remove_script_host: false,
    extended_valid_elements: "span[style],i[class]",
    relative_urls: false,
  });

web.php

 Route::post('/upload', 'BlogController@upload');

BlogController.php

public function upload(Request $request){
            $fileName=$request->file('contentpics')->getClientOriginalName();
            $path=$request->file('contentpics')->storeAs('uploads', $fileName, 'public');
            return response()->json(['location'=>"/storage/$path"]); 
    
        }


via Chebli Mohamed

how to get name from url dynamically

How to get a part of the url?

query to be made:

$name = 'LeSant'; // (from url dinamic) //
$event = Dias::where('name', $name)->first();

enter image description here

How can I get name from the url? /event/LeSant



via Chebli Mohamed

jeudi 12 mai 2022

How to load view file from another root directory in Laravel 5.8

I want to load view file from another root directory. Example : return view('http://localhost/laravelApp/view/products', $data);

http://localhost/laravel/view this is my another view file directory and 'products' is view file name and my laravel project directory is laravelApp. My laravel version 5.8



via Chebli Mohamed

mercredi 11 mai 2022

Cache clear probem in Larave

I have a problem. I am download project from hosting. now when I run the project this error shows. pic attached. I think this is cache problem, I clear cache, view, but still same issue.



via Chebli Mohamed

mardi 10 mai 2022

How to get name property from select option in laravel

I want to search from input field but want to get the property from the select option. Like I want mobile number to be searched from DB , but when i select mobile from select option then it should be search and if i select email then inside the input field i will post email and will select the email from select option then want to search. Here I have done some coding.

Blade file code

<select name="option" class="col-sm-4 form-control mg-md-l-2">
    <option value="">Select</option>
    <option value="cc" name="cc">Customer Code</option>
    <option value="cname" name="cname">Company Name</option>
    <option value="email" name="email">Email</option>
    <option value="mobile" name="mobile">Phone</option>
</select>
<div class="col-1"></div>
<input type="text" class="col-sm-6 form-control" placeholder="Type here" name="">

Here the controller code

$user_id= Auth::user()->id;
    $sale = $request->get('sales_id');
    $priority = $request->get('priority');
    $cc = $request->get('cc');
    $cname = $request->get('cname');
    $email = $request->get('email');
    $mobile = $request->get('mobile');
    $from_date = $request->input('from_date');
    $to_date = $request->input('to_date');
    if (empty($from_date)) {
        $from_date = '2019-01-01 00:00:00';
    } else {
        $from_date = $from_date . ' 00:00:00';
    }
    if (empty($to_date)) {
        $to_date = date('Y-m-d H:i:s');
    } else {
        $to_date = $to_date . ' 23:59:59';
    }
    if ($sale || $priority || $cname || $email || $mobile || $cc) {
        $customers = \DB::table('field_customers as u')
                ->where('u.cc', 'LIKE', "%{$cc}%")
                ->where('u.sales_id', 'LIKE', "%{$sale}%")
                ->where('u.priority', 'LIKE', "%{$priority}%")
                ->where('u.cname', 'LIKE', "%{$cname}%")
                ->where('u.email', 'LIKE', "%{$email}%")
                ->where('u.mobile', 'LIKE', "%{$mobile}%")
                ->whereBetween('u.followup', [$from_date, $to_date])
                ->orderBy('u.followup', 'DESC')
                ->paginate(10);
    }
    else{
        $customers = DB::table('field_customers')  
        ->orderBy('id', 'DESC')
        ->paginate(20);
    }

Here what I want enter image description here



via Chebli Mohamed

how to call one api to another api in laravel using wamp server?

in Web.php

Route::get('/apiforsales', [LeadController::class, 'apiforsales']); //this working fine.

Route::get('/apicheck', [LeadController::class,'apicheck123']);

LeadController.php

public function apiforsales(Request $req)
{
 $results = DB::select( DB::raw(" select id,name,implement,lead_type,number,district,state FROM comman_datas where state = '$req->state' and district= '$req->district' and status = '0'  "));   
 return $results;
}

public function apicheck123(Request $req)
{
    $response = Http::get("http://127.0.0.1:8000/apiforsales?state=".$req->state."&district=".$req->district);
    $jsondata= $response->getBody();
    $data =json_decode($jsondata, true);
    return $data;
}

In postman calling a api

http://127.0.0.1:8000/apiforsales?state=Karnataka&district=Bengaluru ..///working fine.

http://127.0.0.1:8000/apicheck?state=Karnataka&district=Bengaluru ..///it will loading to much time not giving a exact cause of



via Chebli Mohamed

lundi 9 mai 2022

Swift_TransportException: Expected response code 250 but got code "", with message "" in AbstractSmtpTransport.php:383

I have a laravel application that has been sending emails for Years now. Recently, emails have been failing to send. When I check the failed_jobs table, below is the error message:

Swift_TransportException: Expected response code 250 but got code "", with message "" in 
/apps/www/ccc.xxxx.com/public_html/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383

Below are things I have attempted:

  • composer dump-autoload
  • php artisan config:cache
  • php artisan config:clear
  • php artisan queue:restart
  • restarted supervisor
  • Ensure username and password is correct in .env file
  • I have connected to the mail box successfully and able to send email to anyone

Below is the .env config

MAIL_DRIVER=smtp
MAIL_HOST=smtp.office365.com
MAIL_PORT=587
MAIL_USERNAME=g.blah@balh.com
MAIL_PASSWORD=Va#@2016
MAIL_ENCRYPTION=TLS

What can be the issue and how to fix this ?



via Chebli Mohamed

Twitter api returning html response as error

My code

$connection = new TwitterOAuth(SOCIOMATIC_HFW_API_KEY, SOCIOMATIC_HFW_API_SECRET);
$connection->setTimeouts(1000, 1000);
$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => 'env('TWITTER_CALLBACK_URL')'));

Response in html :

Abraham\TwitterOAuth\TwitterOAuthException
<!DOCTYPE html>
    <html lang="en" class="dog">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
            <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
            <title>Twitter / ?</title>
            <meta name="version" content="1">
            <link href="https://abs.twimg.com/favicons/favicon.ico" rel="shortcut icon" type="image/x-icon"> 
            <link rel="stylesheet" href="https://abs.twimg.com/errors/fullscreen_errors-


via Chebli Mohamed

dimanche 8 mai 2022

How to upload TAR.GZ file from Laravel

I am trying to send a tar.gz file from Laravel as a response, but it is not working properly. What is the error in the code? Here $filepath is the absolute path to the tar.gz file.

if(file_exists($filepath)) {
        $file = File::get($filepath);
        $response = Response::make($file, 200);
        $response->header('Content-Type', mime_content_type($filepath));
        $response->header('Content-Length', filesize($filepath));
        $response->header('Pragma', 'public');
        $response->header('Content-Disposition', 'attachment; filename="sample.tar.gz"');

        return $response;
        
    }
    else {
        return $this->response->array(array('error' => 'Could not be downloaded, try again'));
    }


via Chebli Mohamed

samedi 7 mai 2022

Undefined variable in boostrap modal - Laravel

I have a $room variable inside a bootstrap modal and it is causing the problem here is the function in the reservationController

    {
        $room=Room::all();
        return view('/allReservationChild', compact('room'));
    }

the blade name is allReservationChild.blade.php and this is the part of the modal :

```<div class="modal fade" id="addres" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLongTitle">Delete Room</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form style="margin: 50px; text-transform: capitalize " action="/addReservation" method="POST" class="needs-validation" novalidate >
                @csrf

                <div class="modal-body">
                    <div class="form-group">
                        <label for="exampleFormControlSelect1">Select the Room you want to reserve</label>
                        <select class="form-control" id="exampleFormControlSelect1" name="room_id" required>
                            <option value=""></option>
                            @foreach($room as $items)
                                <option value=""></option>
                            @endforeach

                        </select>
                    </div>


                    <div class="mb-3">
                        <label for="exampleFormControlTextarea1" class="form-label">Objectif :</label>
                        <select class="form-control" id="exampleFormControlTextarea1" name="objectif" required>
                            <option value=""></option>
                            <option value="Booking room for a replacement session ">Booking room for a replacement session </option>
                            <option value="Booking room for a random session">Booking room for a random session</option>
                            <option value="Booking room for an event">Booking room for an event</option>
                            <option value="Booking room for an exam">Booking room for an exam</option>
                            <option value="Booking room for discussion of the graduation thesis">Booking room for discussion of the graduation thesis</option>
                            <option value="other">other</option>
                        </select>
                    </div>


                    <div class="form-group">
                        <label class="control-label">Reservation date</label></br>
                        <input class="form-control" type="date" id="Date_beginning" name="date" required>
                    </div>

                    <div class="form-group">
                        <label for="time">Select time period</label>
                        <select class="form-control" id="time" name="time" required>
                            <option value=""></option>
                            <option value="8:30-10:30">8.30-10.30</option>
                            <option value="10:30-12:30">10.30-12.30</option>
                            <option value="13:30-15:30">13.30-15.30</option>
                        </select>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-outline-danger" name="supp" >Add Reservation</button>
                </div>
            </form>

        </div>
    </div>
</div>

and for the **web** 

 ```Route::get('/addReservation',[\App\Http\Controllers\reservationController::class,'create']);

I don't know why ha can not know define the $room variable I think it is because of the modal or something. and the modal I'm sure it is right because I used the same modal in another blade and it works perfectly so the problem I think is in the controller or the web I am not sure



via Chebli Mohamed

The url redirection is not working properly in laravel

Any false url redirecting to home page in my laravel site. It is required to be redirected to 404 page.



via Chebli Mohamed

jeudi 5 mai 2022

concatenate two values in register

I am modifying a register page, I need to concatenate two values

UI

<div class="col-xs-12 col-md-3 input-group">
    <input name="tomo" type="text" class="form-control" placeholder="Tomo" required autocomplete="off">
    <span style="font-size: 25px; color: #bfc9d4;" class="input-group-addon"> --- </span>
    <input name="folio" type="text" class="form-control" placeholder="Folio" required autocomplete="off">
</div>

The values are tomo and folio

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        't_matricula' => ['required', 'string', 'max:255'],
        'matricula' => ['required', 'string', 'max:255'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
    ]);
}

/**
 * Create a new user instance after a valid registration.
 *
 * @param  array  $data
 * @return \App\User
 */
protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        't_matricula' => $data['t_matricula'],
        'numero' => rand(100, 9200),
        'matricula' => $data['tomo'] . $data['folio'],
        'password' => Hash::make($data['password']),
    ]);

    Mail::to($user->email)->send(new WelcomeMail($user));

    return $user;
}

I must save the tomo and folio values in the matricula field, the problem is that it does not execute the registry, please help.



via Chebli Mohamed

mercredi 4 mai 2022

You do not have the SUPER privilege and binary logging is enabled

I am running a laravel migration from jenkins that creates a stored procedure and the following error appears:

SQLSTATE[HY000]: General error: 1419 You do not have the SUPER privilege an  
  d binary logging is enabled (you *might* want to use the less safe log_bin_  
  trust_function_creators variable) (SQL:                                      
              CREATE TRIGGER ...

How can I fix this and allow the migration to create triggers, etc. without problems.



via Chebli Mohamed

Undefined class constant 'MAIN'

We have the following migration:

class CreateAccounts extends Migration
{

    public function up()
    {
        $data= [
            "id" => \App\Account::MAIN,
            "container" => null,               
        ];

        \App\Account::create($data);
    }

}

And here is the class Account, it contains some constants and methods:

namespace App;

use Illuminate\Database\Eloquent\SoftDeletes;

    class Account extends MainModel
    {
        const MAIN = 47;
    
    ...
    
    }

The migration works fine in our dev server but on production it complaints saying

Undefined class constant 'MAIN'

The same error from tinker.



via Chebli Mohamed

lundi 2 mai 2022

how to use whereHas in laravel

I am new to laravel, I need to create a query for the db,

 $query = Deal::query();

I want to use the wherehas operator. this is my code that is worked.

else if ($group_by == 'precedence') {
                if($get_deals_for == 'noprecedence'){
                    $get_deals_for = 0;
                }
                $precedenceStatus = $get_deals_for;
                $query-> where('precedence', '=', $precedenceStatus);
            //    \Log::info('The request precedence: '.$precedenceStatus);
               

            }

I want to add this code also to the query

if($person) {
                    $query->whereHas('personnel', function ($subQuery) use ($person) {
                        $subQuery->where('id', '=', $person);
                    });
                }

So I need to change the first code? how I can convert the first code to wherehas? the first code is from table called deal, the second section is from realtionship called personnel. the second section worked in other places in the code, I just need to fix the first section and not understand what to write in the use



via Chebli Mohamed

how can prevent user to use same token in laravel?

I have created api based web application..Actually I am able to login my lower level user as higher level user when I pass higher level user's token to lower level user.I have used cookie to authenticate user.



via Chebli Mohamed