lundi 28 février 2022

How to configure web app to accept incoming emails?

I have 8 Lorex cameras, model number (N881A6), and it send out emails when motion detected. This is an example of camera number 7.

Alarm: Motion Detect 
Alarm input channel No.: 7  
Alarm device name: N881A6

enter image description here

Note : Subject line always show as ALERT

Since I don't have control over the subject line. I want to configure my Lorex to email to my owned site/server which is running on latest Ubuntu and running a Laravel App. I can accept incoming email from Lorex, parse for channel No.: 7 and create new email accordingly to trigger@applet.ifttt.com with custom subject line.

Ex. Subject : #lorex-action1 for camera 1 alexa routine

Is there away configure any web server to intercept email, parse it and create a new email ?



via Chebli Mohamed

LARAVEL : Passing an id through a form to a foreign key

I'm a beginner with Laravel and I'm a little bit confused with something.So what I'm trying to do is creating a familly through a form , then save this familly and after that we are redirect to a minorstudent form where you can create a student that is link to the familly you just created before.Everything on my models, migrations is okay because in my controller I can see the student and the familly.But my problems is when I create the familly I want to pass the 'id' of the table 'familly' to the table familly which has in its table the foreign key 'familly_id' ...But I dont know how to do it on my controllers.Thanks for the future help.

else {
          $minorstudent = new Minorstudent;
          $minorstudent->first_name = $request->first_name;
          $minorstudent->last_name = $request->last_name;
          $minorstudent->phone_number = $request->phone_number;
          $minorstudent->street_address = $request->street_address;
          $minorstudent->postal_code = $request->postal_code;
          $minorstudent->city = $request->city;
          $minorstudent->email_address = $request->email_address;
          $minorstudent->level = $request->level;
          if ($request->school!="none") {
              $minorstudent->school()->associate($request->school);
          }
          $minorstudent->save();
          return redirect('/familly');
        }

And I want the 'id' of the familly i created before being pass to the minorstudent into 'familly_id' wich is a foreign key.

 else {
        $minorstudent = Minorstudent::where('id',$request->id)->first();
        if ( $request->get('add_student_next') !== null ) {
          $familly = new Familly;
          $familly->first_name = $request->first_name;
          $familly->last_name = $request->last_name;
          $familly->phone_number = $request->phone_number;
          $familly->street_address = $request->street_address;
          $familly->postal_code = $request->postal_code;
          $familly->city = $request->city;
          $familly->email_address = $request->email_address;
          $familly->absence = 1;
          $familly->rules = 1;
          $minorstudent->familly_id()->attach($familly); 
          $familly->save();
          return redirect("/familly/id/student/new");
        }
        

This the familly controllers (form) where you create the familly and after that you are redirect to the minorstudent form

ps:Dont worry about the else at the beginning



via Chebli Mohamed

dimanche 27 février 2022

Laravel Two request value get decrement and insert in column

I'm New in Laravel I controller trying to get decrement (subtract) two input request value and pass result in ( balance_amount ) column.

example

input price request       100
input paid_amount request  50
result balance_amount      50

my Controller

 public function pay(Request $request)
    {
$request['price'] = $request->price;  
$request['paid_amount'] = $request->paid_amount;
$request['balance_amount'] = $request->balance_amount; 
 
    Installment::create($request);   
           }              

  return redirect( )->with('success',' PAID SUCCESSFULLY');

    }  


via Chebli Mohamed

Laravel 5.8: Uniqueness validation multiple columns with nested array wildcard (*.)

How to validate the uniqueness of combined column value in the nested array?

The input data is

$request = [
    [id, vol, number], 
    [id2, vol2, number2], 
    ...
];

The combination of vol and number must be unique with the data in magazines table.

id | vol | number
------------------
0  | 001 | 0001
1  | 001 | 0002
2  | 002 | 0001

Here's what my code looks like for now.

$validatedRequest = $request->validate([
            '*.id' => ['required', 'string'],
            '*.vol' => ['required', 'string'],
            '*.number' => ['required', 'string'], //need to add some rule here, I guess
        ]);

I've read the docs about how to validate nested array data with Rule::forEach() and also read the tutorial on how to validate the uniqueness on multiple column. However, I still cannot figure the way to access the *.vol data when creating rule for number.



via Chebli Mohamed

Copying .zip file failed because: filesize(): stat failed for /home/golden/test-pms.goldenholidaysbd.com/storage/laravel-backups/temp//2022

I cant backup the img file of public folder by spatie(v-3) and laravel (v-5.5). This is showing error. But this is working properly in locally.

This is the cpanel terminal error



via Chebli Mohamed

vendredi 25 février 2022

Laravel5.5-How to use morph to query different fields of different tables according to type

In Laravel 5.5,I have three tables.

posts
id - integer
name - string

users
id - integer
nickname - string

images
id - integer
url - string
imageable_id - integer
imageable_type - string

Then we add the morphTo association to the images model.

public function imageable()
{
    return $this->morphTo();
}

Problem:

Images::with(['imageable:id,name'])->get();

A problem found in the above use process is that when we design the table, the fields in posts and users are different, then there will be a requirement to judge in with whether the source of the table is posts or users to query different The table fields have the desired effect.

Similar to whereHasMorph:

Images::whereHasMorph(
    'imageable',
    [Users::class, Posts::class],
    function (Builder $query, $type) {
        if ($type === Users::class) {
            $query->selectRaw("id,nickname");
        } elseif ($type === Posts::class) {
            $query->selectRaw("id,name");
        }
    }
);

At present, no effective way has been found to achieve this purpose. The only one that can be achieved is as follows.

$imageUsers = images::with([
    'imageable' => function ($query) {
        $query->selectRaw("id,nickname");
    }
])->where('imageable_type', 'App\Users')->get();

$imagePosts = images::with([
    'imageable' => function ($query) {
        $query->selectRaw("id,name");
    }
])->where('imageable_type', 'App\Posts')->get();

So, My question is how to determine whether the source of the table is posts or users in with to query different table fields to achieve the desired effect.



via Chebli Mohamed

Passport package not reflecting on Laravel after installation

After I have installed the passport package in Laravel enter image description here

Why is the Passport package not reflecting in my Laravel code. I'm using Laravel Framework 8.79.0 version enter image description here



via Chebli Mohamed

Getting invalid file error when we use mime_types (text/csv)

When i am going to import file(vendor.csv). Then i get invalid file error. The reason is that one record in first column data is C & G which create error if we remove space then its working. why? As you can see here in attached screenshot: screenshort of csv

Here is my code

public function import()
    {
        set_time_limit(0);
        $input = Input::all();
        $validator = Validator::make($input, ['file' => 'required|mime_types:text/csv']);

        if($validator->fails()) {
            return ApiResponse::validation($validator);
        }
}

error:

{
    "error": {
        "status_code": 412,
        "validation": {
            "file": [
                "Invalid file type."
            ]
        },
        "message": "Validation Failed"
    }
}

Uploaded file name is testing.csv File data is :

Header:

Display_Name Address City State Zip Type

Data:

  • C & G sdsd 42gfdf DE MI 226 Other

  • asa 516 DYKE SH MI 315 Other

  • A-1 FA 16601 end Ro MI 466 Other

  • A-1 R 30001 CHU MT MI 443 Other

Request sent through Postman Request send through

If we send data like this type then its working Data:

  • C&G sdsd 42gfdf DE MI 226 Other

  • asa 516 DYKE SH MI 315 Other

  • A-1 FA 16601 end Ro MI 466 Other

  • A-1 R 30001 CHU MT MI 443 Other



via Chebli Mohamed

jeudi 24 février 2022

Laravel 5.2: How to test helper function?

I'm new to laravel. I have read the laravel documentation on testing but I do not seem to understand it. Could someone guide me on the steps to test this helper function?

Below is the function.

function getUnreadInboxMessagesForAUserById($id)
{

    $past_period_months = Carbon::now()->subMonths(6);

    $message = App\Message::select("*")
    ->whereIn("conversation_id", App\Conversation::select("id")
    ->where([
        ["user_one", "=", $id],
        ["delete_user_one", "=", 0]
    ])
    ->where(function($query) {
        $query->where("created_at", ">", $user_one_convo_deleted_at)->orWhereNull("user_one_convo_deleted_at");
    })
    ->where(function($query) {
        $query->where("created_at", ">", $user_one_msgs_deleted_at)->orWhereNull("user_one_msgs_deleted_at");
    })
    ->orWhere(function($query) {
        $query->where([
        ["user_two", "=", $id],
        ["delete_user_two", "=", 0]
        ])
        ->where(function($query) {
        $query->where("created_at", ">", $user_two_convo_deleted_at)->orWhereNull("user_two_convo_deleted_at");
        })
        ->where(function($query) {
        $query->where("created_at", ">", $user_two_msgs_deleted_at)->orWhereNull("user_two_msgs_deleted_at");
        });
    })
    )
    ->where([
    ["is_seen", "=", 0],
    ["user_id", "<>", $id]
    ])
    ->whereNotIn("user_id", App\DeactivateAccount::select("user_id"))
    ->where(function($query) {
    $query->whereNotIn("user_id", App\User::select("id")
        ->where([
        ["flag", "=", 0],
        ["id", "=", $user_id]
        ])
        ->orWhereIn("user_id", App\User::select("id")
            ->where("id", "=", $user_id)
            ->whereIn("membership", ["admin","premium","free-premium","diamond"]))
        );
    })
    ->where(function($query) {
    $query->where("hard_delete", "=", 0)->orWhereNull("hard_delete");
    })
    ->where(function($query) {
    $query->where("deleted_from_receiver", "=", 0)->orWhereNull("deleted_from_receiver");
    })
    ->where(function($query) {
    $query->where("isflaged", "!=", 1)->orWhereNull("isflaged");
    })
    ->where("created_at", ">=", $past_period_months)
    ->orderBy("created_at", "desc")
    ->get()
    ->count();

    return $messages[0];
}

It would be really helpful if you could list the steps in detail.



via Chebli Mohamed

Laravel 5.2: Syntax errors after converting raw query to eloquent using converter tool

I've converted the below raw query to eloquent using https://jjlabajo.github.io/SQLtoEloquent/ but there seems to be a couple of syntax errors.

RAW

$messages = DB::select(DB::raw("SELECT COUNT(*) AS count FROM messages as m WHERE conversation_id IN ( SELECT id FROM conversations WHERE (user_one = {$id} AND delete_user_one = 0 AND (m.created_at > user_one_convo_deleted_at OR  user_one_convo_deleted_at IS NULL) AND (m.created_at > user_one_msgs_deleted_at OR user_one_msgs_deleted_at IS NULL)) OR (user_two = {$id} AND delete_user_two = 0 AND (m.created_at > user_two_convo_deleted_at OR user_two_convo_deleted_at IS NULL) AND (m.created_at > user_two_msgs_deleted_at OR user_two_msgs_deleted_at IS NULL) ) ) AND is_seen = 0 AND user_id <> {$id} AND user_id NOT IN ( SELECT user_id FROM deactivateaccount ) AND ( user_id NOT IN ( SELECT id FROM users WHERE flag = 0 AND id = user_id ) OR user_id IN ( SELECT id FROM users WHERE membershiptype IN ('admin','premium','free-premium','diamond') AND id = user_id ) ) AND (hard_delete = 0 OR hard_delete IS NULL) AND (deleted_from_receiver = 0 OR deleted_from_receiver IS NULL)  AND (isflaged IS NULL OR isflaged != 1) AND m.created_at >= '{$past_period_months}' ORDER BY created_at DESC"));

return $messages[0]->count;

ELOQUENT

DB::table("messages as m")
    ->select("count (*) as count")
    ->whereIn("conversation_id", function($query){
    $query->from("conversations")
    ->select("id")
    ->where("(user_one", "=", {$id}]
    ->where("delete_user_one", "=", 0)
    ->where("(m.created_at", ">", user_one_convo_deleted_at)
    ->whereNull("user_one_convo_deleted_at");
    })
    ->where(DB::raw("where_subquery_group_3_)"))
    ->where(DB::raw("(user_two = {$id} and delete_user_two = 0 and (m.created_at > user_two_convo_deleted_at or user_two_convo_deleted_at is null)"))
    ->where("is_seen", "=", 0)
    ->where("user_id", "<>", {$id})
    ->where(DB::raw("( user_id not in ( select id from users where flag = 0 and id = user_id )"))
    ->whereIn("user_id", function($query){
    $query->from("users")
    ->select("id")
    ->whereIn("membershiptype", "('admin',");
    })
    ->where("id", "=", user_id)
    ->where(DB::raw("(hard_delete = 0 or hard_delete is null)"))
    ->where(DB::raw("(deleted_from_receiver = 0 or deleted_from_receiver is null)"))
    ->where(DB::raw("(isflaged is null or isflaged != 1)"))
    ->where("m.created_at", ">=", {$past_period_months})
    ->orderBy("created_at","desc")
    ->get();

Here's a screenshot of the errors

Why are there errors and how do I fix them? Thank you



via Chebli Mohamed

Laravel 5.2: How to convert raw query to eloquent?

Here's the raw query.

$past_period_months = Carbon::now()->subMonths(6);

$messages = DB::select(DB::raw("SELECT COUNT(*) AS count FROM messages as m WHERE conversation_id IN ( SELECT id FROM conversations WHERE (user_one = {$id} AND delete_user_one = 0 AND (m.created_at > user_one_convo_deleted_at OR  user_one_convo_deleted_at IS NULL) AND (m.created_at > user_one_msgs_deleted_at OR user_one_msgs_deleted_at IS NULL)) OR (user_two = {$id} AND delete_user_two = 0 AND (m.created_at > user_two_convo_deleted_at OR user_two_convo_deleted_at IS NULL) AND (m.created_at > user_two_msgs_deleted_at OR user_two_msgs_deleted_at IS NULL) ) ) AND is_seen = 0 AND user_id <> {$id} AND user_id NOT IN ( SELECT user_id FROM deactivateaccount ) AND ( user_id NOT IN ( SELECT id FROM users WHERE flag = 0 AND id = user_id ) OR user_id IN ( SELECT id FROM users WHERE membershiptype IN ('admin','premium','free-premium','diamond') AND id = user_id ) ) AND (hard_delete = 0 OR hard_delete IS NULL) AND (deleted_from_receiver = 0 OR deleted_from_receiver IS NULL)  AND (isflaged IS NULL OR isflaged != 1) AND m.created_at >= '{$past_period_months}' ORDER BY created_at DESC"));

return $messages[0]->count;

Now, how do I convert this to eloquent?



via Chebli Mohamed

Laravel storage link won't work on production on online server

I have a problem with showing the images that have been uploaded to my Database, but all the data comes normally, but the images do not appear. I think the problem is in the folder from which the images come, knowing that the matter

//php artisan storage:link

works normally on my machine but while uploading the project to an actual server the images don't work Knowing that someone told me to get out all the files that are in the public folder, and put them in the main path

my Codes

///config/filesystems.php

        'public' => [
            'driver' => 'local',
            'root' => storage_path('app/public'),
            'url' => env('APP_URL').'/storage',
            'visibility' => 'public',
        ],

//controller sample


    public function add_item(Request $req){
      $req->validate([

        'i_name'=>'required',
        'i_price'=>'required',
        'i_size'=>'required',
        'i_unit'=>'required',
        'i_cat'=>'required',
        'i_short'=>'required',
        'i_full'=>'required',
        'i_photo'=>'required',
        'i_photo1'=>'required',
        'i_photo2'=>'required',
        'i_photo3'=>'required',
        'i_photo4'=>'required',
      ]);
      $i=new item;
     $email=$req->session()->get('supplier');
     $i->supplier=$email;
     $i->name=$req->input('i_name');
      $i->price=$req->input('i_price');
      $i->size=$req->input('i_size');
      $i->unit=$req->input('i_unit');
      $i->category=$req->input('i_cat');
      $i->short_desc=$req->input('i_short');
      $i->full_desc=$req->input('i_full');
      $i->image_url=$req->file('i_photo')->store('items_photo','public'); //fule upload= store
      $i->image1_url=$req->file('i_photo1')->store('items_photo','public'); //fule upload= store
      $i->image2_url=$req->file('i_photo2')->store('items_photo','public'); //fule upload= store
      $i->image3_url=$req->file('i_photo3')->store('items_photo','public'); //fule upload= store
      $i->image4_url=$req->file('i_photo4')->store('items_photo','public'); //fule upload= store
      $i->save(); //insert

      return redirect('s_setting'); 
      }

// from my index view

  <div class="imgs-container">
            <!-- start item div  -->
@if(count($data)>0)
@foreach($data as $d)
            <div class="box">
                <img class="photo" src="" alt="">
                <div class="caption">
                    <h4></h4>
                    <!-- <p></p> -->
                    <p></p>
                    <p></p>
                    {!! Form::open(['url' => 'items/anony']) !!}




{!! Form::close() !!}
                </div>


            </div>
@endforeach
@endif

Any idea



via Chebli Mohamed

Query records from the last 7 days

enter image description here

Today is 2/24/2022

On my report page, I read interval from the query params, and this is what I have in my controller:

$inputs    = Request::all();
$interval  = 'week'; // <<------------ Default Value 

if(array_key_exists('interval', $inputs)){
    $interval  = $inputs['interval'];
}


switch ($interval) {
    case 'day':
    $q = BabyLog::where('updated_at', '>', now()->today());
    break;
    case 'week':
    $q = BabyLog::where('updated_at', '>', now()->subWeek());
    break;
    case 'month':
    $q = BabyLog::where('updated_at', '>', now()->subMonth());
    break;
    case 'year':
    $q = BabyLog::where('updated_at', '>', now()->subYear());
    break;
    default:
    $q = BabyLog::orderBy('updated_at', 'desc');
    break;
}




$logs = $q->where('babyId',$baby->id)->orderBy('updated_at', 'desc')->get()->groupBy(function ($log) {
    return $log->updated_at->format('Y-m-d');
});

dd($logs);

return

Illuminate\Database\Eloquent\Collection {#344 ▼
  #items: array:8 [▼
    "2022-02-24" => Illuminate\Database\Eloquent\Collection {#352 ▶}
    "2022-02-23" => Illuminate\Database\Eloquent\Collection {#353 ▶}
    "2022-02-22" => Illuminate\Database\Eloquent\Collection {#351 ▶}
    "2022-02-21" => Illuminate\Database\Eloquent\Collection {#349 ▶}
    "2022-02-20" => Illuminate\Database\Eloquent\Collection {#350 ▶}
    "2022-02-19" => Illuminate\Database\Eloquent\Collection {#348 ▶}
    "2022-02-18" => Illuminate\Database\Eloquent\Collection {#346 ▶}
    "2022-02-17" => Illuminate\Database\Eloquent\Collection {#345 ▶}
  ]
}

I only want to display the last 7 days on my graph.

  1. Why does 2022-02-17 is also on the list ??

  2. What did I do wrong on the above codes?

  3. Does subWeek() always return 8 ?

  4. Should I just do subWeek() -1 ?

But ... subMonth(), and subYear() I don't have to do it.



via Chebli Mohamed

mardi 22 février 2022

Get responses from External API after login

I want to get data from External API. but, I must login to get session before Getting data and I must Logout after get data

this is my code

    use GuzzleHttp\Client;

    $client = new Client();
    $res = $client->request('POST', 'Login_URL', [
        'json' => [
            "JSON param"
        ]
    ]);
    $res = $client->request('GET', 'Get_URL');
    $res = $client->request('POST', 'Logout_URL');

but I can only the first step (Login). and I getting error message in the second step to get data

Client error: `GET "Get_URL" ` resulted in a `401 Unauthorized` response:{"message":"You are not logged in."}

how I can run all this code with login session on first step ?



via Chebli Mohamed

laravel 5 : Error running php artisan php.exe

i want to run php artisan in terminal, i got error php program, and i try composer update and didn't work, how to fix this error ?

Program 'php.exe' failed to run: The process cannot access the file because it is being used by another processAt line:1 char:1
+ php artisan
+ ~~~~~~~~~~~.
At line:1 char:1
+ php artisan
+ ~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (:) [], ApplicationFailedException
    + FullyQualifiedErrorId : NativeCommandFailed


via Chebli Mohamed

lundi 21 février 2022

Laravel: how model gets injected from route parameter

I've seen the following route:

Route::prefix('/users/{user}')->group(function () {
   Route::get('groups/{group}', 'UserGroupController@show');
}

And in UserGroupController:

use App\Group;

    public function show(Request $request, User $user, Group $group)
    {
        dd($group);
    }

My question is how does the $group model object gets constructed here from a raw route parameter string?

My guess is laravel's service container does the following magic (maybe sth like

  1. Injecting the Group model,
  2. then do sth like Group::where('id', $group)->first()

but unsure about this.



via Chebli Mohamed

Relationship not loading in production

We have a laravel 5.5 app in production and recently we noticed that eager loading relationships seem to be failing.

The query that is failing is:

$allClients = Client::with([
        'tasks',
        'tasks.task_files',
        'resume_files',
    ])
    ->leftjoin('users', 'users.id', 'clients.client_id')
    ->where([
        ['status', 0],
        ['assigned_to', $user->id],
    ])
    ->orderBy('name', 'ASC')
    ->get();

The tasks.task_files relationship is not loading in production.

If I run the same on my local, it loads data fine.
If I run the same in a tinker shell on production, it loads data fine.
But when the controller is hit via a request, it doesn't load the task_files data.

I've tried logging the queries being run through QueryLog and they seem correct and running the same SQL queries gives the correct data.

The relationships are:

    Model: Client

    /**
     * This is used to get the tasks for the current client.
     *
     * @return Task $tasks[]
     */
    public function tasks()
    {
        return $this->hasMany('App\Task', 'client_id', 'client_id');
    }
    Model: Task

    /**
     * This is used to get the task files for the current task.
     *
     * @return TaskFile $files[]
     */
    public function task_files()
    {
        return $this->hasMany('App\TaskFile', 'task_id', 'task_id')->whereIn('type', ['type1', 'type2'])->latest('updated_at');
    }

I have no clue why would this suddenly stop working in production.



via Chebli Mohamed

dimanche 20 février 2022

Laravel CssSelectorConverter.php - unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST)

Im running php 7.2.5 and laravel 5.8.0, I try to register a user and then this error gets thrown, I have no idea where it is coming from but i think its related to the registration email

syntax error, unexpected 'array' (T_ARRAY), expecting function (T_FUNCTION) or const (T_CONST) and its in the file /var/www/html/vendor/symfony/css-selector/CssSelectorConverter.php



via Chebli Mohamed

vendredi 18 février 2022

Eloquent ORM Query

My query is that

 $uploadedSC = SC::select('id')->with(['cont'=> function ($q) {
                return $q->with('crs:id,title')->select('*');
            }])->where('act', true)->get();

But I wanna add ->where('act',true) query to crs table. But giving error. How can i write this query?

 $uploadedSC = SC::select('id')->with(['cont'=> function ($q) {
                    return $q->with('crs:id,title')->where('act',true)->select('*');
                }])->where('act', true)->get();


via Chebli Mohamed

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for

$data['employees'] = $employees = EmployeesMongodb::select('id', 'first_name', 'middle_name', 'last_name', 'profile_pic', 'documents', 'jobPositions')
    ->where('id', Auth::user()->employee_id)
    ->first();

$data['uploaded_docs'] = $uploaded_docs = DocumentsMongodb::where('employee_id', Auth::user()->employee_id)
    ->where('hiring_pkg_file_id', "!=", "")
    ->whereNotIn('status', [4, 5])
    ->get();
  

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for ▶



via Chebli Mohamed

jeudi 17 février 2022

Missing required parameter for [Route: ajax.offers.edit] [URI: ajax-offer/edit/{offer_id}] [Missing parameter: offer_id]

Route code

    Route::get('edit/{offer_id}' , [App\Http\Controllers\OfferController::class, 'editOffer'])->name('ajax.offers.edit');

Controller code

public function editOffer(Request $request)
{
    $offer = Offer::find($request -> offer_id);
    if(!$offer)
        return response()->json([
            'status' => false,
            'msg' => 'Offer is not exist',
        ]);

    $offer =Offer::select('id', 'name_en', 'name_ar', 'price', 'details_en', 'details_ar')->find($request->offer_id);
    return view('ajaxoffers.edit', compact('offer'));
}

View code

id)}}" class="delete_btn">Ajax Edit

so what's the problem



via Chebli Mohamed

What is in a laravel application Menu::render(), Assets::render(), Notify::render()?

I'm working on a laravel app that I haven't coded. I need to do some modifications and in my blade templates I see some code like this:

 {!! Menu::render('client', 1, 1) !!}
{!! Assets::renderCss() !!}
{!! Notify::render() !!}
{!! Assets::renderJs() !!}

I understand that it used to link some code like stylesheet, script js or menu but I can't find these functions. I search a little in the laravel documentation but no results. Is there some customs functions from my app? The development environment is not very convenient and I can't make search into the whole files... I wanted to modify the related menu and I didn't find the files where I have to modify. Forgive me if my question is silly but I'm starting in development...

Thanks for your answers



via Chebli Mohamed

mercredi 16 février 2022

Fail to load an image from storage on laravel

Can you please give me an example: I used seeder to create an image for the user, but I couldn't load it, even though I ran php artisan storage:link , and checked the path of the image (the url is correct. ). Please help me explain

The code I used in factory file to create an Image

    'image' => $this->faker->image('storage/app/public/users', 140, 180, null, false),

The img tag I used to load an image :

<img src="" class="avatar avatar-sm me-3 border-radius-lg" alt="user1">

When I inspected the url of an image

This is my folder structer



via Chebli Mohamed

show data in column datatables

I´m traying to show items for my contracts in my datatable i´m working with laravel 5.6 and i send all my data from my controller and i´m doing a console.log for my variable and i can show it, but in my function render i can´t show my items i don´t know that i´m doing wrong.

<script>

        jQuery(function(){
            var $tabla = window.One._lMain.find("#contratos");
            var $btnestados = window.One._lMain.find(".btn-estados");
            var productos = @json($productos);

            jQuery.extend(jQuery.fn.dataTable.ext.classes, {
                sWrapper: "dataTables_wrapper dt-bootstrap4",
                sFilterInput:  "form-control form-control-sm",
                sLengthSelect: "form-control form-control-sm",
                
            });

            // Override a few defaults
            /*jQuery.extend(true, jQuery.fn.dataTable.defaults, {
                pageLength: 15,
                lengthMenu: [ 15, 25, 50, 75, 100 ],
                autoWidth: true,
                info: "simple",
                buttons: true,
                language: {
                    url: ""
                }
            });*/

            $btnestados.on( 'click', function() {
                $btnestados.blur();
                var texto = $(this).data("estado");

                $btnestados.removeClass("active");

                $(this).addClass("active");

                table.columns( 10 ).search(  $(this).data("estado").trim() )
                .draw();
            });

            function format (data) {
                var html = '<table class="table table-borderless font-size-sm" cellspacing="0" border="0" p-4"><tbody>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Cliente.:</td>'+
                                '<td>'+data.cliente+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Dirección de instalación.:</td>'+
                                '<td>'+data.direccion+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Provincia.:</td>'+
                                '<td>'+data.provincia+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Población.:</td>'+
                                '<td>'+data.poblacion+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">C.P.:</td>'+
                                '<td>'+data.cp+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Tlf. Fijo.:</td>'+
                                '<td>'+(data.fijo === null ? '' : data.fijo)+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Tlf. Móvil.:</td>'+
                                '<td>'+(data.movil === null ? '' : data.movil)+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Instalador.:</td>'+
                                '<td>'+data.instalador.nombre+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Asignado por.:</td>'+
                                '<td>'+data.historicos[0].empleado.nombre+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td class="font-w600 pl-4">Observaciones.:</td>'+
                                '<td>'+(data.observaciones === null ? '' : data.observaciones)+'</td>'+
                            '</tr>'+
                            '<tr>'+
                                '<td colspan="2" class="font-w600 pl-4 mt-2">Artículos para instalar<hr style="margin: 2px;"></td>'+
                            '</tr>';

                            if(data.productos) {
                                for(var x = 0; x < (data.productos).length; x++) {
                                let producto = productos.productos[data.productos[x]];

                                html += '<tr>'+
                                            '<td class="pl-4" colspan=""><span style="font-weight: bold;">'+producto.text+'</span></td>'+
                                        '</tr>';
                                }
                                html += '</tbody></table>';
                            }   else    {
                                for(var x = 0; x < (data.articulos).length; x++) {
                                    let producto = data.articulos[x];

                                    html += '<tr>'+
                                                '<td class="pl-4" colspan=""><span style="font-weight: bold;">'+producto.ref+' - '+producto.descripcion+'</span></td>'+
                                            '</tr>';
                                    }
                                html += '</tbody></table>';
                            }
                return html;
            }

            var table = $tabla.DataTable({
                pageLength: 15,
                lengthMenu: [ 15, 25, 50, 75, 100, 200 ],
                autoWidth: true,
                info: "simple",
                dom: 'Bfrtip',
                buttons: [
                    'pdf',
                ],
                language: {
                    url: ""
                },
                
                order: [[11, 'desc']],
                data: @json($partes),
                initComplete: function( settings, json ) {
                    $tabla.find(".js-tooltip").tooltip();
                    // style for button export
                    var btns = $('.dt-button');
                    btns.addClass('btn btn-info');
                    
                },
                columns: [
                    /*{
                        data: null,
                        name: 'moredetails',
                        className: 'open-mdl',
                        defaultContent: '<i class="far fa-edit"></i>',
                        searchable: false, orderable: false, search: {value: null, regex: "false"}
                    },*/
                    {data: null, className: "text-center more-details", defaultContent: '<i class="far fa-plus-square"></i>'},
                    {
                        data: 'n_contrato', name: 'n_contrato', className: 'font-w600', searchable: true, orderable: true, search: {value: null, regex: "false"},
                        render: function(data, type, row) {
                            return row.serie+'-'+row.n_contrato+ ' - ' +row.id;
                        }
                    },
                    {data: 'cliente', name: 'cliente', className: 'd-none d-md-table-cell font-w600',  searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    //{data: 'direccion', name: 'direccion', className: 'd-none d-lg-table-cell', searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    {data: 'provincia', name: 'provincia', className: 'd-none d-sm-table-cell d-xl-table-cell', searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    {data: 'poblacion', name: 'poblacion', className: 'd-none d-sm-table-cell d-xl-table-cell', searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    //{data: 'cp',        name: 'cp', className: 'd-none d-xl-table-cell', searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    {data: 'fijo',      name: 'fijo', className: 'd-none', searchable: false, orderable: true, search: {value: null, regex: "false"}},
                    {data: 'movil',     name: 'movil', className: 'd-none', searchable: false, orderable: true, search: {value: null, regex: "false"}},
                    {data: 'instalador.nombre', name: 'instalador', className: 'd-none', searchable: true},
                    {data: 'span_estado', name: 'span_estado', className: 'd-none d-md-table-cell text-center', searchable: true, orderable: false},
                    {data: {_:"fecha", sort:"fechauk"}, name: 'fecha', className: 'd-none d-md-table-cell', searchable: true, orderable: true, search: {value: null, regex: "false"}},
                    { "defaultContent": "", render: function (productos, type, row) {
                            $.each(row.articulos, function(key, value) {
                                console.log(value.descripcion);
                                return '<span class="badge bg-info text-white">'+value.descripcion+'</span>';
                            });
                        },
                    },

                    { data: 'btn_parte', name: 'btn_parte', className: "text-center", searchable: false, orderable: false }
                ],
                /*dom:
                    "<'row'<'col-sm-12 col-md-4'l><'col-sm-12 col-md-2'><'col-sm-12 col-md-6'f>>" +
                    "<'row'<'col-sm-12'tr>>" +
                    "<'row'<'col-sm-12 col-md-12'p>>",*/
            });

            $tabla.on('click', 'td.more-details', function () {
                var tr = $(this).parent();
                var row = table.row( tr )

                if ( row.child.isShown() ) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.find(":first i").attr('class', 'far fa-plus-square');
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    row.child( format(row.data()) ).show();
                    tr.find(":first i").attr('class', 'far fa-minus-square');

                    tr.addClass('shown');
                }
            });
        });
    </script>

this it´s my function to create my datatable. Variable "$productos" it´s my items and my variable "$partes" it´s all my contracts.

In my console.log from my function render in defaultContent

FILTRO SEDIMENTO + CARBÓN PP + C, FILTRO CARBÓN + REMINERALIZADOR ALCALINO T-33
partes:819 DEPURADORA FLUJO DIRECTO AQUALUXE PREMIUM 2.0
partes:819 FILTRO SEDIMENTO + CARBON PP+C, FILTRO CARBON + REMINERALIZADOR ALCALINO T-33
2partes:819 DCALUXE PRO 2.0 DESINCRUSTADOR ELECTRONICO
partes:819 DEPURADORA FLUJO DIRECTO AQUALUXE PREMIUM 2.0
partes:819 DCALUXE PRO 2.0 DESINCRUSTADOR ELECTRONICO
partes:819 JUEGO FILTROS AQUALUXE 2 DE CARBON +1 SEDIMENTOS BAYONETA

this it´s a examples.

Thanks for help me and readme



via Chebli Mohamed

mardi 15 février 2022

Laravel Logger not Working inside console commands

I am using Laravel Logger(Log::info() to be specific) inside a Console Command and it is not working when it is scheduled (scheduled for two times a day), if i run the command manually as php artisan command-name it is working.

I have already tried php artisan config:clear and php artisan optimize

My app.php :

'log' => env('APP_LOG', 'single'),
'log_level' => env('APP_LOG_LEVEL', 'debug'),

My .env :

APP_LOG_LEVEL=debug

My ide_helper :

'Log' => array(
            'debug'     => 'Monolog\Logger::addDebug',
            'info'      => 'Monolog\Logger::addInfo',
            'notice'    => 'Monolog\Logger::addNotice',
            'warning'   => 'Monolog\Logger::addWarning',
            'error'     => 'Monolog\Logger::addError',
            'critical'  => 'Monolog\Logger::addCritical',
            'alert'     => 'Monolog\Logger::addAlert',
            'emergency' => 'Monolog\Logger::addEmergency',
        )


via Chebli Mohamed

how to see the request in laravel 6

Hey I am new to laravel. I have this html code enter image description here

and this is what I have in the method. enter image description here

Is their a way to see the request? in the view? in the developer tools? I just want to see the request.



via Chebli Mohamed

lundi 14 février 2022

eloquent relationship from collection on different models

I have two models as activity and products each operation on the products model will log as audits on the activity table. products table has a few columns which are used to relate to other tables. the output of the activity table will be as follows

    "id" => 166
    "log_name" => "default"
    "description" => "ADMIN has updated PO# : 116"
    "subject_type" => "App\Models\Po"
    "event" => "updated"
    "subject_id" => 5
    "causer_type" => "po"
    "causer_id" => 1
    "product" => "{"old": {"id": 5, "qty": 238, "vendor_auto_id":15}, "new":{"id": 5, "qty": 500}}

I am able to get the category name by querying Product::with('vendor_auto_id') on the controller and querying on Model as follows

    public function vendor_auto_id(){
        return $this->hasOne('\App\Models\Vendor','id', 'vendor_auto_id');
    }

which returns the correct information. the question is I wanted to make a relationship on the Vendor table using the Activity model. can someone recommend the best solution?

following is the package I'm using to log activities on Laravel https://spatie.be/docs/laravel-activitylog/v4/introduction



via Chebli Mohamed

dimanche 13 février 2022

Automatically not insert created_at and updated_at in laravel not working

Automatically not insert created_at and updated_at in laravel not working.

DB::table('commundityvendordata')->insert($commdata);

I am using this above statement passing an array for inserting multiple record $commdataworking fine but when check my created_at and updated_at column in database not getting timestamp.

Model:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class commundityvendordata extends Model
{
    use HasFactory;
    protected $table ='commundityvendordata';
}

Migration:

public function up()
    {
        Schema::create('commundityvendordata', function (Blueprint $table) {
            $table->bigIncrements('vender_id')->unsignedBigInteger();
            $table->date('new_date');
            $table->unsignedBigInteger('cd_id');
            $table->foreign('cd_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('cn_id');
            $table->foreign('cn_id')->references('cd_id')->on('communitydata')->onDelete('cascade');
            $table->unsignedBigInteger('unit_id');
            $table->foreign('unit_id')->references('unit_id')->on('units')->onDelete('cascade');
            $table->unsignedInteger('vender1');
            $table->unsignedInteger('vender2');
            $table->unsignedInteger('vender3');
            $table->unsignedInteger('vender4');
            $table->timestamps();
        });
    }

Controller:

function commundityvendordata(Request $request){
                $collection = count(collect($request));
                $cvendordata = new commundityvendordata;
                for ($i=0; $i < $collection; $i++) {
                $new_date = Carbon::parse($request->new_date)->format('Y-m-d');
                $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
                $cd_id = $CCode['cd_id'];
                $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
                $cn_id = $CName['cd_id'];
                $CUnit=units::where('unit','=',$request->cunit[$i])->first();
                $unit_id = $CUnit['unit_id'];
                $vender1 = $request->vendor1[$i];
                $vender2 = $request->vendor2[$i];
                $vender3 = $request->vendor3[$i];
                $vender4 = $request->vendor4[$i];
                   $commdata = [
                    'new_date'  => $new_date,
                    'cd_id'     => $cd_id,
                    'cn_id'     => $cn_id,
                    'unit_id'   => $unit_id,
                    'vender1'   => $vender1,
                    'vender2'   => $vender2,
                    'vender3'   => $vender3,
                    'vender4'   => $vender4
                ];
                if($cd_id != ''){
                         DB::table('commundityvendordata')->insert($commdata);
                    }else{
                        return back()->with('success','Data Saved...');
                    } 
            }   
    }

database table screen shot: enter image description here



via Chebli Mohamed

how do I update price after in axios response using jquery?

I am writing inventory management system where I what the user to select product and I use axios to get the corresponding price of the product

It is a multiple rows where the user click on add product to select the product and the corresponding price displays

The jquery creates a new row of product and also which allows the user to select a product and it uses axios to request for the price from the server.

When the request returns the price from the server it update the price input field.

But it updates the price with 0 instead of the response from axios

$("#add-product").click(function(e) {
  e.preventDefault();
  $("#new-field").clone().appendTo("#wrapper");
});
$("#payment-method").change(function() {
  $(".full-payment").css({
    "display": "block"
  });
})

$("#wrapper").on('change', '.product', function(e) {
  e.preventDefault();
  $(this).closest('.row-field').find('.price').html("loading...")

  let price = 0;
  axios.get("/api/get-price/" + $(this).val())
    .then(function(response) {
      console.log(response.data.price)
      $(this).closest('.row-field').find('.price').html(price);
      $(this).closest('.row-field').find('.price').val(price);

    });

})

$("#wrapper").on('keyup', '.quantity', function() {
  var total = 0;
  let price = $(this).closest(".row-field").find(".price").val();
  console.log("price", price)
  if (isNaN(price)) {
    alert("Allow the rpice to load")
  } else {

    total = parseInt($(this).closest(".row-field").find(".price").val()) * parseInt($(this).val());
    if (isNaN(total)) {
      $(this).closest(".row-field").find(".sub-total").html(0.00);
      return;
    }
    $(this).closest(".row-field").find(".sub-total").html(total);
    console.log("total", total);

    var total = 0,
      val;
    $(".sub-total").each(function() {
      vals = parseInt($(this).text());
      console.log("value ", vals)
      val = isNaN(vals) || $.trim(vals) === "" ? 0 : parseFloat(vals);
      total += val;
    })
    $(".total").html(total);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6 offset-sm-6">
          <ol class="breadcrumb float-sm-right">
            <li class="breadcrumb-item"><a href="">Dashboard</a></li>
            <li class="breadcrumb-item active">Add New Sales</li>
          </ol>
        </div>
      </div>
    </div>
    <!-- /.container-fluid -->
  </section>

  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <!-- left column -->
        <div class="col-md-12">
          <!-- general form elements -->
          <div class="card card-primary">
            <div class="card-header">
              <h3 class="card-title">Add New Sales</h3>
            </div>
            <!-- /.card-header -->

            <!-- form start -->
            <form role="form" action="" method="post">
              @csrf
              <div class="card-body">
                <div class="row">

                  <div class="col-md-12">
                    <div class="form-group">
                      <label>Payment Method</label>
                      <select name="payment_method" id="payment-method" class="form-control">
                        <option value="">Select Payment Method</option>
                        <option value="cash">Cash</option>
                        <option value="bank_transfer">Bank Transfer</option>
                      </select>
                      <!-- @if ($errors->first())
    <span style="font-size: 12px; color: red"></span>
    @endif -->
                    </div>
                  </div>
                  <div class="col-md-12 right my-3">
                    <a href="#" class="btn btn-danger" id="add-product">Add New Product</a>
                  </div>
                  <div id="wrapper" class="col-md-12">
                    <div id="new-field" class="col-md-12 row-field">
                      <div class="row">

                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Product Name</label>
                            <select name="product[]" class="form-control product">
                              <option value="">Select Product Name</option>
                              @foreach ($products as $product)
                              <option value="" name="product[]">
                                </option>
                              @endforeach
                            </select>
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Quantity</label>
                            <input type="text" name="quantity[]" class="form-control quantity" value="" placeholder="Enter Quantity">
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Unit Price</label>
                            <div class="price form-control">Price</div>
                            <input type="hidden" name="price[]" class="price" />
                          </div>
                        </div>
                        <div class="col-md-3">
                          <div class="form-group">
                            <label>Sub Total</label>
                            <div class="form-control sub-total">0.00</div>
                          </div>
                        </div>
                      </div>
                    </div>

                  </div>
                </div>

                <!-- /.card-body -->
                <div id="new-field" class="row">
                  <div class="col-md-9">
                    Total
                  </div>
                  <div class="col-md-3 total">
                    N
                    <span>0.00</span>

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

              <div class="card-footer">
                <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>
              </div>
            </form>
          </div>
          <!-- /.card -->
        </div>
        <!--/.col (left) -->
      </div>
      <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
  </section>
</div>


via Chebli Mohamed

samedi 12 février 2022

There is a problem with displaying images when it is called from the Database

The AppServ Open Project - 8.6.0 for Windows Now you running on PHP 5.6.30

The problem is that all data and data are being called, but the problem is that the image is not being called

The problem is that all data and data are being called, but the problem is that the image is not being called

And here is a picture from Database

--my items--


    <div class="items_parent">
    @if(count($data)>0)
    @foreach($data as $i)
<!-- start item div  -->
        <div  class="item_part">
            <img src=""
            width="200" height="200"/>
            <b id="price">EGP.</b>
            <b id="name"></b>
            <b id="unit"></b>
            <p id="desc"> </p>

            <a href="s_edit_item"></a>
            {!! Form::open(['url' => 'all_items','files'=>true]) !!}

            
            


            

            {!! Form::close() !!}

        </div>
<!--  end of item div-->
@endforeach
    @endif
    </div>


--supplier code-- //Here is the code for adding products

 public function add_item(Request $req){
      $req->validate([

        'i_name'=>'required',
        'i_price'=>'required',
        'i_size'=>'required',
        'i_unit'=>'required',
        'i_cat'=>'required',
        'i_short'=>'required',
        'i_full'=>'required',
        'i_photo'=>'required'
      ]);
      $i=new item;
     $email=$req->session()->get('supplier');
     $i->supplier=$email;
     $i->name=$req->input('i_name');
      $i->price=$req->input('i_price');
      $i->size=$req->input('i_size');
      $i->unit=$req->input('i_unit');
      $i->category=$req->input('i_cat');
      $i->short_desc=$req->input('i_short');
      $i->full_desc=$req->input('i_full');
      $i->image_url=$req->file('i_photo')->store('items_photo','public'); //fule upload= store
      $i->save(); //insert

      return redirect('s_setting'); 
      }


via Chebli Mohamed

vendredi 11 février 2022

how do I update price when product is selected using jquery?

I am working on an inventory management system that involves sales of products

The form is dynamic

when a user click on add new product it creates another row of product where the user selects the product

I want to update the price of the product as the user selects the product

My HTML Code

<form role="form" action="" method="get">
    @csrf
    <div class="card-body">
        <div class="row">
            <div class="col-md-12">
            </div>
            <div class="col-md-12 right my-3">
                <a href="#" class="btn btn-danger" id="add-product">Add New Product</a>
            </div>
            <div id="wrapper" class="col-md-12">
                <div id="new-field" class="col-md-12 row-field">
                    <div class="row">

                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Product Name</label>
                                <select name="product[]" class="form-control product">
                                    <option value="">Select Product Name</option>
                                    @foreach ($products as $product)
                                        <option value="" name="product[]">
                                            </option>
                                    @endforeach
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Quantity</label>
                                <input type="text" name="quantity[]" class="form-control"
                                    value=""
                                    placeholder="Enter Quantity">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Unit Price</label>
                                <input type="text" name="price[]"
                                    class="form-control price"
                                    placeholder="Enter Quantity">
                            </div>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
    <div class="card-footer">
        <button type="submit" class="btn btn-primary float-md-right">Add Sales</button>
    </div>
</form>

The jquery gets the product id send it to the server through axios and get the price of the product and update the price input field

JQUERY

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        $("#add-product").click(function(e) {
            e.preventDefault();
            $("#new-field").clone().appendTo("#wrapper");
        });
        $("#wrapper").on('change', '.product', function(e) {
        e.preventDefault();
        axios.get("/ims/api/get-price/" + $(this).val())
            .then(function(response) {

                $(this).parent('.row-field').find('.price').val(response.data.price);

            });
    })
</script>

JSON

{
   price: 75800.42
}

How can I make it work?



via Chebli Mohamed

mercredi 9 février 2022

Sort JSON response by date in laravel 5.5

So far I noticed, It is sorting with the first character of the date

My Code

$data = json_decode($json);  
$collection = new Collection($data);
$collection->sortByDesc('CreationDate')

My JSON

"[{"NumberCase":"CCS - 102957","CreationDate":"03/12/2019 16:59:19","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Activo"},{"NumberCase":"CCS - 107539","CreationDate":"23/12/2019 16:49:36","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 110407","CreationDate":"10/01/2020 16:58:42","ServiceName":"Televisión por Cable","ClientReport":"Baja calidad de imágen","StatusCode":"Activo"},{"NumberCase":"CCS - 115482","CreationDate":"04/02/2020 18:55:24","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 118120","CreationDate":"17/02/2020 13:36:58","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189126","CreationDate":"18/08/2021 21:03:10","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 189870","CreationDate":"23/08/2021 16:41:50","ServiceName":"Televisión por Cable","ClientReport":"No ve algunos canales","StatusCode":"Resuelto"},{"NumberCase":"CCS - 82862","CreationDate":"09/09/2019 20:47:16","ServiceName":"Televisión por Cable","ClientReport":"No ve ningun canal","StatusCode":"Activo"},{"NumberCase":"CCS - 85805","CreationDate":"19/09/2019 20:35:24","ServiceName":"Televisión por Cable","ClientReport":"Se congela la imagén y salen cuadros en toda la pantalla","StatusCode":"Activo"}]"


via Chebli Mohamed

How can get polygon from database and show draw on map by using laravel language؟

This is store in database as string parameter polygon [{"long":44.2102114567917,"lat":15.369831802551733},{"long":44.2102114567917,"lat":15.369831802551733},{"long":44.2102114567917,"lat":15.369831802551733},{"long":44.2102114567917,"lat":15.369831802551733}]

      // and this my code  to do polygon




  <script>

function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 13,
    center: {lat: 40.7484404, lng: -73.9878441 },
    
  });
  const poly = new google.maps.Polygon({
    strokeColor: "#000000",
    strokeOpacity: 1,
    strokeWeight: 3,
    map: map,
  });

 
                
  var x =[
    { "lat": 15.362825469475341, "lng": 44.212589263916016 },
    { "lat": 15.359997572657216, "lng": 44.2021433720749 },
    { "lat": 15.354369485881188, "lng": 44.20334500171357 },
    { "lat": 15.351238223587876, "lng": 44.215850830078125 },

    ];
  


  const flightPath = new google.maps.Polygon({
    path: x,
    geodesic: true,
    strokeColor: "#00008b",
    strokeOpacity: 1.0,
    strokeWeight: 2,
  });
  
 
 
  flightPath.setMap(map);  
 
}
</script>

my problem is how I can put that polygon from database instead of value for var x (to get latLng from db) and I am using Laravel languge



via Chebli Mohamed

Composer requires guzzlehttp/guzzle installation failed

Guzzle Installation Failed

$ composer require guzzlehttp/guzzle Using version ^7.4 for guzzlehttp/guzzle ./composer.json has been updated Running composer update guzzlehttp/guzzle Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages.

Problem 1 - Root composer.json requires guzzlehttp/guzzle ^7.4, found guzzlehttp/guzzle[dev-master, 7.4.0, 7.4.1, 7.4.x-dev] but these were not loaded, likely because it conflicts with another require.

Problem 2 - laravel/passport is locked to version v7.5.1 and an update of this package was not requested. - laravel/passport v7.5.1 requires guzzlehttp/guzzle ~6.0 -> found guzzlehttp/guzzle[6.0.0, ..., 6.5.x-dev] but it conflicts with your root composer.json require (^7.4).

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions. You can also try re-running composer require with an explicit version constraint, e.g. "composer require guzzlehttp/guzzle:*" to figure out if any version is installable, or "composer require guzzlehttp/guzzle:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

I have been stuck on this problem with guzzle installation, can someone help me on this type of problem.

Thank you so much in advance



via Chebli Mohamed

mardi 8 février 2022

Laravel get Users->Projects with its ProjectTypes relation, where Users is connected by ManyToMany with ProjectTypes

How can i get Users->Projects with its ProjectTypes relation, where Users is connected by ManyToMany with ProjectTypes.

I have this tables:

User
- id 
- name

Project
- id
- name

ProjectType
- id
- name

project_type_user
- id
- user_id
- project_type_id

project_user
- id
- user_id
- project_id


via Chebli Mohamed

lundi 7 février 2022

How to flush session on Laravel Cartalyst/Sentinel 2 automatic logout

Background

We have a Laravel Application built using Laravel 5.2 and cartalyst/sentinel version 2. When the user is logging in, we're setting some custom session values for our application need, for example:

Session::set('office_name', $officeName);

And in our logout method, we're flushing the session as well:

Sentinel::logout(null, true);
Session::flush();
Session::regenerate();

So, when the user deliberately logs themselves out, the session is working just fine.

Issue

But the issue is: when the Sentinel is automatically logging itself out after a certain (defined?) idle time, it's not flushing the custom sessions. So the user interface is announcing that the user is logged out, and they have to log in again. But we can still see the set session office_name is present there. And there are many other session values that are still present after the automatic logout.

How can we tell the Sentinel to flush the session when itself is automatically logging out?



via Chebli Mohamed

composer require guzzlehttp/guzzle installation failed

Guzzle Installation Failed

$ composer require guzzlehttp/guzzle Using version ^7.4 for guzzlehttp/guzzle ./composer.json has been updated Running composer update guzzlehttp/guzzle Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages.

Problem 1 - Root composer.json requires guzzlehttp/guzzle ^7.4, found guzzlehttp/guzzle[dev-master, 7.4.0, 7.4.1, 7.4.x-dev] but these were not loaded, likely because it conflicts with another require. Problem 2 - laravel/passport is locked to version v7.5.1 and an update of this package was not requested. - laravel/passport v7.5.1 requires guzzlehttp/guzzle ~6.0 -> found guzzlehttp/guzzle[6.0.0, ..., 6.5.x-dev] but it conflicts with your root composer.json require (^7.4).

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions. You can also try re-running composer require with an explicit version constraint, e.g. "composer require guzzlehttp/guzzle:*" to figure out if any version is installable, or "composer require guzzlehttp/guzzle:^2.1" if you know whic h you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.

I have been stucked in this problem on guzzle installation, can someone help me on this type of problem.

Thank you so much in advance



via Chebli Mohamed

dimanche 6 février 2022

Why does some data not toggling?

My 2nd department won't toggle (img not changing). Im not sure why

This is the sample code. I am mapping the table on the controller then calling the js to toggle

My logic is when toggling. I just hide and show the plus and minus img via js. the problem is id 1 is not toggling and the id 2 works just fine

DB tbl.department | id | department_name | | -------- | -------------- | | 1 | Test1 | | 2 | Test2 |

Controller

        $departments = DB::table('department')->get();
        $html.= '<table>';
        foreach($departments as $d) {
                $html.= '<tr>';
                $html.= '   <td><a href=\'javascript:department_toggle("'.$d['id'].'");\'><img id="'.$d['id'].'_img_1" src="'.asset('img/plus.gif').'" width="9" height="9"/><img id="'.$d['id'].'_img_2" src="'.asset('img/minus.gif').'" width="9" height="9" style="display:none"/> '.$d['department_name'].'</a>';
                $html.= '   <div id="'.$d['id'].'_div_1" style="display:none;"></div></td>';
                $html.= '</tr>';
        }
        $html.= '</table>';

JS

function department_toggle(deptid){
var a = $('#'+deptid+'_div_1');
var b = $('#'+deptid+'_img_1');
var c = $('#'+deptid+'_img_2');
if (a.is(':visible'))
{
    a.hide();
    b.show();
    c.hide();
}
else
{
    a.load('my-route', {deptid:deptid}).show(); //my intended data to display after toggle
    b.hide();
    c.show();
}

}

HTML Source:

HTML1 HTML2

Display:

Display



via Chebli Mohamed

Undefined offset: 4 in laravel

Undefined offset: 4 in Laravel

when I click on submit button then other empty rows should be ignored.

Error screen shots enter image description here

enter image description here

dashboard.blade.php form enter image description here

controller.php

function commundityvendordata(Request $request){
            $collection = count(collect($request));
            // Insert data into database
            $cvendordata = new commundityvendordata;
            for ($i=0; $i < $collection; $i++) {
                $new_date = $request->new_date;

                $CCode=communitydata::where('c_code','=',$request->ccode[$i])->first();
                $cd_id = $CCode['cd_id'];
                $CName=communitydata::where('c_name','=',$request->cname[$i])->first();
                $cd_id = $CName['cd_id'];
                $CUnit=units::where('unit','=',$request->cunit[$i])->first();
                $unit_id = $CUnit['unit_id'];

            $vender1 = $request->vendor1[$i];
            $vender2 = $request->vendor2[$i];
            $vender3 = $request->vendor3[$i];
            $vender4 = $request->vendor4[$i];
                $commdata = [
                        'new_date'  => Carbon::parse($new_date)->format('Y-m-d'),
                        'cd_id'     => $cd_id,
                        'cn_id'     => $cd_id,
                        'unit_id'   => $unit_id,
                        'vender1'   => $vender1,
                        'vender2'   => $vender2,
                        'vender3'   => $vender3,
                        'vender4'   => $vender4
                    ];
 DB::table('commundityvendordata')->insert($commdata);
            }
            return back()->with('success','Data Saved...');
    }


via Chebli Mohamed

jeudi 3 février 2022

How can i optimize my query to deal with 10 thousand reocrds in MySql table from Laravel 5.5?

I have 10 thousand records in the MySQL table. I have used indexing to get a better result and all other techniques that are available in WWW. when records were around 3000 then it was taking 3 to 7 seconds but after that, my system takes 15 to 20 seconds to get data. that is too high. I want to reduce this. I am using Laravel 5.5.

I am showing the last 12 months revenue of bookings in Graph.

function pastTwelveMonthsTotalRevenue()
{
    $month = false;
    $today = Carbon\Carbon::now();

    $firstDay_this_month = new Carbon\Carbon('first day of this month');
    $start_date_this_month = $firstDay_this_month->startOfDay();
    $todayYear = $start_date_this_month->subYear(1)->startOfDay();
    $lastDay_last_month = new Carbon\Carbon('last day of last month');
    $end_date_last_month = $lastDay_last_month->endOfDay();



   // filtering all booking id with all condition.   
    $bookings = Booking::whereIn('trip_status', [1, 2])
        ->whereIn('trip_status', [1, 2])
        ->where('status', 1)
        ->where('booking_or_quotes', 1)
        ->whereBetween('booking.booking_time', [$todayYear, $end_date_last_month]);

    if ($franchisees) {
        $bookings->where('franchisees_id', $franchisees);
    }
    else
    {
        $bookings->whereHas('franchisees',function ($q){ $q->where('test_franchisee',0); });
    }

    $bookingsId =  $bookings->select('id')->get()->pluck('id');

    // now directly collecting those records that have filtered.
    // to get quickly i am only uisng filtered bookings Id here.

    $query = \App\BookingDetails::select('booking.booking_time',
        'booking.price_without_vat', 'booking.custom_price','booking_details.*',
        DB::raw("DATE_FORMAT(booking_time,'%Y%m')  as dt"))
        ->join('booking', 'booking.id', '=', 'booking_details.booking_id')
        ->whereIn( 'booking_id' , $bookingsId )
        ->whereBetween('booking.booking_time', [$todayYear, $end_date_last_month])
        ->orderBy(DB::raw("dt"));

    $query->with("booking:id,booking_time,price_without_vat,custom_price");
    $bookingModels = $query->get();

    $dataChart = array();
    $chartLabels = array();
    $color = array();
    $data = array();

    if (collect($bookingModels)->count()) {
        // Group all record on Y-M date order.
        $bookingModelCls = collect($bookingModels)->groupBy(DB::raw("dt"));

        foreach ($bookingModelCls as $key => $models) {

            $month = substr($key, 4, 2);

            $total_ern = $total_exp = 0;

            if (collect($models)->count()) {

                $month = $month * 1;

                $driverRevenue =  graphDriverTotalRevenue($models);
                $companionRevenue = graphCompanionTotalRevenue($models);
                $profit =  $driverRevenue + $companionRevenue ;
                $data[] = round($profit, 2);
                $color[] = getColor($key);
                $chartLabels[] = getMonthsName($month) . "'" . substr($models[0]['dt'], 2, 2);
            }
        }
    }


    $dataChart[] = array(
        'label' => false,
        'fill' => false,
        'backgroundColor' => $color,
        'borderColor' => $color,
        'data' => $data
    );

    return array(
        'labels' => $chartLabels,
        'data' => $dataChart
    );

}

Here in this method, I am using Inner-Join. using that I can get all data that is coming from the BookingDetails Table. but this code was written by a different user and due to lack of time, I did not change the whole code. so i used ->with("bookingDetails") to get data from Booking Details Tables.

So Data is coming around 4 to 6 seconds but when it is being loaded into Chat(Graph). It is taking 10 to 20 seconds or sometimes it is crashing the browser.

enter image description here



via Chebli Mohamed

Optimise laravel 5.2 eloquent query that returns a single row

I'm wondering is there any way to optimise this code:

foo::where('bar_id', $this->bar->id)->first()

Is it possible to optimise this and speed up execution without removing any column fields? As I see that is one of the most suggested answers.

What would be your suggestions?



via Chebli Mohamed

mercredi 2 février 2022

Laravel 3 table join and query

I have 3 database tables. Users, diffacts, offdays.USERS table has user information. In offdays table, the user has date_start field, if a user's date_start field shows today's date, the user is allowed. If today's date appears in the user's date_start field in the diffacts table, I will get the duration field I will create a table at the front end and write the user name-permission status - duration status of each user. When I add today's date to the where part when I join query, it brings the users whose date_start field is today. I need all users, I would appreciate if you could help me.



via Chebli Mohamed

mardi 1 février 2022

Laravel 5.5 : Not Receiving Password Reset Link

When I using my Laravel application in locally and click "Send password Reset link" button this action is sending a password reset link in Mailtrap. But after deploying project on cPanel, this action is not sending a password reset link to selected mail address. What should I do?

.env file:

APP_NAME=Laravel
APP_ENV=local
APP_KEY=**************
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=************

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=*****
DB_USERNAME=*****
DB_PASSWORD=*****

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_FROM_ADDRESS="mail.dmdhakamanpower.com"

MAIL_DRIVER=mail
MAIL_HOST="mail.dmdhakamanpower.com"
MAIL_PORT="465"
MAIL_USERNAME="ddms@dmdhakamanpower.com"
MAIL_PASSWORD=*****
MAIL_ENCRYPTION="SSL"

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

https://i.stack.imgur.com/mTOyD.png



via Chebli Mohamed