mercredi 30 novembre 2022

getting error on server(aws) SyntaxError: Unexpected token '<', "

I have deployed my laravel application on AWS server(ubuntu). Application works fine. But when I upload images using custom modal popup, then i got the syntax error from vendors.js.

Here is the error getting from modal popup while uploading images: Here is the error getting from modal popup while uploading images

Can anyone tell about that, how i can resolve that? I am just stuck from last two days.

I have tried run on server npm i body-parser And also re-add the file of vendors.js But same result.



via Chebli Mohamed

mardi 29 novembre 2022

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php:788 Stack trace: #0 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(788): ReflectionClass->__construct('IlluminateContr...') #1 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(667): Illuminate\Container\Container->build('IlluminateContr...') #2 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(615): Illuminate\Container\Container->resolve('IlluminateContr...', Array) #3 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(767): Illuminate\Container\Container->make('IlluminateContr...', Array) #4 C:\xampp\htdocs\erc_new\public\index.php(52): Illuminate\Foundation\Application->make('IlluminateContr...') #5 C:\xampp\htdocs\erc_new\server.php(21): require_once('C:\xampp\htdocs...') #6 {mai in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 788

auto it is showin the Kernel error. thought i have not made any changes. i have already tried checking the Kernel.php files. more over i have already deleated the vendor and composer.lock file and install the composer . But also getting the the above error.

Moreover I also have deleted the every things that recedes on bootstrap/cache/



via Chebli Mohamed

lundi 28 novembre 2022

Laravel 8 - search paginate ( withQueryString ) not working on table when searching NUMBERS on row integer

i can't search when it comes to searching NUMBERS on row int (price), but when searching like String number on row string (name) it's working fine

like this in my table row here is my Product table

category_id
"56"
user_id
"1"
name
"555"
description
"fruit"
price
555

when i am searching the name row "555" it's working fine beacuse its a string. but when it comes to price i can't search it because it's int

here is my code for controller searching

public function index(Request $request){
    $user = Auth::user()->id;
    if($request->search){
        $search = $request->search;
        $products = Products::with('category')
        ->where('name','like',"%$search%")
        ->orWhere('price','like',"%$search%")
        ->where('user_id',$user)->paginate(10);
    }else{
        $products = Products::with('category')->where('user_id',$user)->paginate(10);
    }
      return view('client.product.index',['products'=>$products]);
}

here is my blade

    <form class="w-full" action="">
        <i class="fa fa-search"></i>
        <input placeholder="Search"  type="search" name="search">     
        <button type="submit">Search</button>
    </form>

@foreach ($products as $product)
    <p></p>
    <p></p>
@endforeach



via Chebli Mohamed

How to sort parent data based on child column detial in laravel 5.4?

I have 3 way relationship firstl i have get code like this in a controller

Trial::with('subjects')->where('source_id', $sourceId)->get()->toArray()

Now I want to sort subject.reactions on desc order of subject.reactions.accounts.nb_followers column. I tried to use orderby on relationship but it does not work because it sorting account indsted on reactions. I want to sort reaction based on value of "nb_followes" column present inside account table.

Trail Model

class Trial extends Model
{
    use HasFactory;
    public $table = 'trials';

    public function subjects()
    {
        return $this->hasMany(Subject::class, 'trial_id')->with(['reactions', 'news'])->withCount('reactions');
    }
  } 

Subject Model

class Subject extends Model
{
    use HasFactory;
    public $table = 'subjects';

    public function reactions()
    {
        return $this->hasMany(Reaction::class, 'subject_id', 'id')->with(['accounts' => function ($q) {$q->orderBy('nb_followers', 'DESC');}])->where('twitter_error', 0)->where('active', 1)->orderby('key_reaction', 'DESC');
    }

    public function news()
    {
        return $this->hasone(News::class, 'id', 'news_item_id');
    }

Reaction Model

class Reaction extends Model
{
    use HasFactory;

    public $table = 'reactions';

    public function accounts()
    {
        return $this->belongsTo(Account::class, 'account_id', 'id')->where('name', '!=', '');
    }

Thank you in Advance.



I want to sort reactions based on account table's column yes i cant use simple eloquent query because it will not create a structure that i want so that's why i created these relationships.


via Chebli Mohamed

samedi 26 novembre 2022

laravel Target class [App\Http\Controllers\EmployeeController] does not exist

enter image description here enter image description here

enter image description here

Target class [App\Http\Controllers\EmployeeController] does not exist.

 protected $namespace ='App\\Http\\Controllers';
public function boot()
{
    $this->configureRateLimiting();

    $this->routes(function () {
        Route::middleware('api')
            ->prefix('api')
            ->namespace($this->namespace)
            ->namespace('App\Http\Controllers') 
            ->group(base_path('routes/api.php'));

        Route::middleware('web')
        ->namespace($this->namespace)
        ->namespace('App\Http\Controllers')
        ->group(base_path('routes/web.php'));
    });

}

using but not solving the problem



via Chebli Mohamed

vendredi 25 novembre 2022

Access numeric key in array php [duplicate]

I have a array with a key like "11_check". How to acess this using php/laravel?

            $check=$list[$i]->{11_check};

I'm trying to acess with {} but I'm getting the error

Parse error: syntax error, unexpected '_check' (T_STRING)

Solution:

            $check=$list[$i]->{'11_check'};


via Chebli Mohamed

jeudi 24 novembre 2022

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel. if development is true i want to use different database in laravel.

http://127.0.0.1:8000/graphql?development=true

its working but graphql does not getting development params



via Chebli Mohamed

Error Laravel\Socialite\Two\InvalidStateException In the return method from the Google side

I want use Socialite package but receive in Error !

controller codes :

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;

class GoogleAuthController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callback()
    {
        // when i dd() here i see in the answer in the browser.
        $googleUser = Socialite::with('google')->user();
        // but dd in here isn't working!
       
        $user = User::where('email', $googleUser->email)->first;

        if ($user) {
            auth()->loginUsingId($user->id);
        } else {
            $newUser = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => bcrypt(\Str::random(16)),
            ]);
            auth()->loginUsingId($newUser->id);
        }
        return $this->redirect('/');
    }
}

in web.php :

Route::get('auth/google', 'Auth\GoogleAuthController@redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController@callback');

laravel version : 6.20.26

php version : 7.2.5

please help me. tnks

===============================================================

I try this (https://stackoverflow.com/a/37849202/20355717) :

Socialite::driver('google')->stateless()->user()

but in did't work for me and given an anothe error ! :

GuzzleHttp\Exception\RequestException

cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token


http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W 



via Chebli Mohamed

lundi 21 novembre 2022

Laravel 9 Validation: array is optional but its keys are required: required_array_keys and nullable don't work together

Summary

  1. Context

  2. Sources

    2.1. Unit test

    2.2. FormRequest's rules method

  3. Behaviors

    3.1. Actual behavior

    3.2. Expected behavior

  4. Question


Context

In a Unit test, I want to send data to a FormRequest in a REST call. I am testing the behavior of the validation rules I've written in the rules method of the FormRequest.

Sources

Unit test

    public function test_detach_user_job_status()
    {
        $response = $this->put(route('users.update', ['user' => $this->applier['id']], [
            'job' => [
            ]
        ]));
        $response->assertStatus(200);
    }

FormRequest's rules method

    public function rules()
    {
        return [
            'name' => 'nullable|string',

            'job' => 'nullable|array:id,attach_or_detach,message|required_array_keys:id,attach_or_detach',
            'job.id' => 'integer|gt:0',
            'job.attach_or_detach' => 'boolean',
            'job.message' => 'required_if:job.attach_or_detach,true|string',
        ];
    }

Behaviors

Actual behavior

The test succeeds.

Expected behavior

The test fails. Indeed, the array job is provided but no keys id or attach_or_detach or (eventually) message are provided, whereas the validation rules do specify: required_array_keys:id,attach_or_detach.

Also, if no job array is specified at all, then the validator must not reject the request because this array is not provided, nor its keys: it's perfectly normal since the array must be optional (it is nullable to provide this feature).

Question

Why doesn't Laravel make my test fail since my nullable (= optional) array is provided, and that its keys are required?



via Chebli Mohamed

dimanche 20 novembre 2022

Fetch product first based on values in column laravel

I have this query that fetches properties from table

$properties = Property::with('Category')
            ->orderBy('name','asc')
            ->where('status','Active')
            ->get();

In my table i have added new column featured it's value is either 0 or 1. I want to show property with 1 value in featured column first

Please suggest solution Thanks.



via Chebli Mohamed

samedi 19 novembre 2022

How can I ad more fields for the enrollment and make it appear on the dashboard

So I downloaded this project of laravel from github a laravel course enrollment project and I want to add more fields to the register form and make it appear on the admin panel as well but in with the code, they used the quickadminpanel.com and also repeating this cruds.enrollment.fields.user which is literally not defined any where in the code that I can see. Since I am a beginner with this laravel thing, I could really use some help in building a project using that repository. Thank You

I have tried almost every thing I know and so far...nothing is happening



via Chebli Mohamed

how to pass register data api to another out api

I am have register api for register user data in my users table I want also in the same register api set link for out api to register the same date also in another application how can i do this



via Chebli Mohamed

vendredi 18 novembre 2022

419 page expired error in laravel form submission even after adding csrf

 <form action="/checklogin" method="post" enctype="multipart/form-data" class="account-form" id="login_form_order_page">
                                     
              <div class="error-wrap"></div>
              <div class="form-group">
                 <input type="text" name="email" class="form-control" placeholder="Email*" required>
              </div>
              <div class="form-group">
                 <input type="password" name="password" class="form-control" placeholder="Password*" required>
              </div>
              <div class="form-group btn-wrapper">
                 <button type="submit" id="login_btn" class="submit-btn">Login</button>
              </div>
              <div class="row mb-4 rmber-area">
                 <div class="col-6">
                    <div class="custom-control custom-checkbox mr-sm-2">
                       <input type="checkbox" name="remember" class="custom-control-input" id="remember">
                       <label class="custom-control-label" for="remember">Remember Me</label>
                    </div>
                 </div>
                 <div class="col-6 text-right">
                    <a class="d-block" href="/register">Create New account?</a>
                    <a href="login/forget-password">Forgot Password?</a>
                 </div>
              </div>
              <div class="col-lg-12">
                 <div class="social-login-wrap">
                 </div>
              </div>
           </form>


Route::POST('/checklogin', 'HomeController@checklogin');

I am submitting the form with csrf still after submitting form 419|Page Expired Error. After adding session_start() method on page it shows headers already sent.



via Chebli Mohamed

mercredi 16 novembre 2022

lluminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string

I have a problem trying to send values in the form of an array from the input, what is the solution? And each array of data is in a separate line in the data base and has an id as if I entered the data more than once

I searched a lot, but I did not find a solution to this problem. Can someone help me? Thank you

//blade

<td>
    <input type="text" class="qty form-control" name="p_unit[]">
    @error('p_unit.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_lastPrice[]">
    @error('p_lastPrice.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_averagecost[]">
    @error('p_averagecost.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td><input type="text" class="form-control" name="p_priceA[]"></td>
<td>
    <input type="text" class="form-control weight" name="p_priceB[]">
    @error('p_priceB.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="form-control unit_cost" name="p_priceC[]">
    @error('p_priceC.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>


I have an activated button that repeats the same fields to fill them in again, and after that I want to send the data in an array to the database

// controller

$products = $request->p_code;


for ($i=0; $i<count($products); $i++)
{
    $items = productUnitPrice::create([
        'p_code'               => $request->p_code,
        'p_packing'            => $request->p_packing[$i],
        'p_conversionfactor'   => $request->p_conversionfactor[$i],
        'p_unit'               => $request->p_unit[$i],
        'p_lastPrice'          => $request->p_lastPrice[$i],
        'p_averagecost'        => $request->p_averagecost[$i],
        'p_priceA'             => $request->p_priceA[$i],
        'p_priceB'             => $request->p_priceB[$i],
        'p_priceC'             => $request->p_priceC[$i],

    ]);


via Chebli Mohamed

My Laravel Links keep breaking Each time I restart my server

My Laravel links keep breaking each time I restart my local server

So, I am using Laravel 9 and my links keep breaking each time I reload the page or when I restart the server For example

127.0.0.1:8000/cars/1/edit

will become 127.0.0.1:8000/cars/cars/1/edit next time I click it.

I have searched for a solution and stumbled upon this On every click link changes in blade view

But the problem is that the guy that asked the question is using named routes from web.php route

I, on the other hand, am using resource routes ( I do not know what to call them = Route::resource('/cars', CarsController::class);)Resouce route

For that reason, I'm finding it difficult to implement the route() solution proposed as his had a named route name

The href I want to make changes to looks like this. I am using resources routes in web.php

<a href="cars//edit">Edit &rarr;</a>

Href I want to edit



via Chebli Mohamed

Tom-Select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route

I am attempting to load tom-select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route. However, JS below fetches a json array of 15527 items but won't show on the options

The Select element...

<select id="select-repo" placeholder="Select a Diagnosis" multiple></select>

The JS...

var new_opd1 = "";

     new TomSelect('#select-repo',{
        valueField: 'url',
        labelField: 'icd_name',
        searchField: 'icd_name',
        // fetch remote data
        load: function(query, callback) {
            var url =new_opd1+'?q='+query ;
           // console.log(url)
            fetch(url)
                .then(response => response.json())
                .then(json => {
                    //console.log(json.name); ~undefined
                    callback(json);
                   // console.log(json);
                }).catch(()=>{
                callback();
            });

            
        },
       // custom rendering functions for options and items
         render: {
            option: function() {
                return `<div class="py-2 d-flex">
                            <div>
                                <div class="mb-1">
                                    <span class="h4">
                                        ${(icd_name) } 
                                    </span>
                                </div>
                                <span class="h4">
                                        ${(icd_code) }
                                    </span>
                            </div>
                        </div>`;
            },
            item: function() {
                return `div class="py-2 d-flex">
                            <div>
                                <div class="mb-1">
                                    <span class="h4">
                                        ${(icd_name) }
                                    </span>
                                </div>
                                <div class="description">${(icd_code) }</div>
                            </div>
                        </div>`;
            }
        },


     });

The route...

public function getData(Request $request){

   $users = ICD10Code::project(["_id" => 0])->get(['icd_code','icd_name']);
    
   return json_encode($users->toArray());
 
 }

I am attempting to recreate this https://tom-select.js.org/examples/remote/. However since my dataset is huge I was wondering if really this would work



via Chebli Mohamed

mardi 15 novembre 2022

Exclude from a select more than 2101 records with laravel sql query builder

I am using something like this:

$scanned = DB::table("Persons")
        ->whereNotIn("Person_Id", $exclude)
        ->get();

The problem is $exclude has more than 2101 records, and I get the following error:

SQLSTATE[IMSSP]: Tried to bind parameter number 2101.  SQL Server supports a maximum of 2100 parameters.

Is there a way around? how can I solve this?



via Chebli Mohamed

lundi 14 novembre 2022

Is there any way to use eloquent addSelect with different database on a different server in Laravel?

A table called api_call_data is being used in a seperate database (done by the original code author, not me) which is located in another server in our Laravel project (I can't move the table).

Due to that, the original query doesn't work anymore. The original query was like below:

$apicallData->addSelect(DB::raw("
    (SELECT MAX(`reg_time`) FROM `api_call_data` as A WHERE `A`.`app_id` = `apps_data`.`app_id` and reg_time between $request->from_date and $request->to_date) as api_reg_time
"))

(I have omitted the rest of the queries after this here)

Is there any way to make this original query work? I really wanted to make this work but I am totally lost here.



via Chebli Mohamed

dimanche 13 novembre 2022

Wildcard routing with laravel not following recognizing prefix

In my application i have a laravel backend with two spas consuming api from it. Now i want to manage my routes by using wildcard routes where i give both routes prefixes before the wildcard route takes effect. Here is an example

Route::prefix('creditors')->group(function () {
    Route::any('/{all}', function () {
        return view('creditor');
    })->where(['all' => '.*']);
});

Now the issue us if i visit something like /creditors/login the spa returns a 404 not found. I want my spa to start handling routing after "creditors/". How do i go about this?



via Chebli Mohamed

samedi 12 novembre 2022

vendredi 11 novembre 2022

Can config/auth.php be made dynamic?

Can helper functions or through any other medium be used to make changes in config/auth.php? I mean can we get some data from the database through helper function or some other way and just append the data to config/auth.php.

I was trying to append the data to guards key. I made a guards table and formatted the data to the exact format of guards key of config/auth.php.

I called a helper function in config/auth.php and tried to get the data of guards but it showed a bunch of errors.



via Chebli Mohamed

jeudi 10 novembre 2022

CSRF token mismatched in laravel when i moved project to another server

enter image description here

Hii My website is not working on other server code is same into both server

1, Working server

http://programmingly.com/articles/

  • testuser@gmail.com
  • 12345678 (Working perfect)

https://www.vennocracy.com/

  • testuser@gmail.com
  • 12345678 (Not Working)

I tried ajax for that

$('#login-form').validate({
        rules: {
            email: {
                required: true,
            },
            password: {
                required: true,
            },
        },
        messages: {
            email: {
                required: 'Please enter email',
            },
            password: {
                required: 'Please enter password',
            },
        },
        submitHandler: function(form) {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: "",
                type: "POST",
                data: new FormData(form),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function() {
                    $("body").append(
                        "<div class='ajax-overlay'><i class='porto-loading-icon'></i></div>"
                        );
                },
                success: function(res) {
                    $(".ajax-overlay").remove();
                    if (res.status) {
                        $('.all-error').html('');
                        $('.all-success').html('');
                        $('.all-success').html(res.message);
                        setTimeout(function() {
                            $("#loginModal").modal('hide');
                            location.reload();
                        }, 4000);
                    } else {
                        $('.all-error').html('');
                        $('.all-error').html(res.message);
                    }
                },
                error: function(data) {
                    $(".ajax-overlay").remove();
                    var errorString = '';
                    $.each(data.responseJSON.errors, function(key, value) {
                        errorString += value + '<br>';
                    });
                    $('.all-error').html('');
                    $('.all-success').html('');
                    $('.all-error').html(errorString);
                },
            });
            return false;
        }
    });


via Chebli Mohamed

mercredi 9 novembre 2022

how to show multiple filenames in one json format?

I'm not sure where and how I should use the for loop.

I am using Laravel v5.5. I am trying to upload multiple files on my project. I think if I can add all filenames in one json array I can show them in blade page. How can i do that?


        if(request()->hasFile('urun_resmi')) {
            $files = request()->file('urun_resmi');
            $filename = [];
            foreach ($files as $file) {
                if($file->extension() == 'pdf')
                {
                    $filename = $file->extension() . "-" . $entry->id . "-" . time() . "." . $file->extension();
                }else
                {
                    $filename = $entry->id . "-" . time() . "." . $file->extension();
                }
                $file->storeAs('urunler', $filename, 'public');
                $entry->detay()->update(['urun_resmi' => $filename]);
                
          
                if ($file->isValid()) {
                    $file->move('uploads/urunler', $filename);
                    UrunDetay::updateOrCreate(
                        ['urun_id' => $entry->id],
                        ['urun_resmi' => $filename]
                    );
                }
            }

        }


via Chebli Mohamed

mardi 8 novembre 2022

laravel log debug is not working.I checked A response is returned from the server side

laravel log debug is not working.

I create app with laravel5 and vue.js.

I send a request to the server side with vue and catch this with laravel Controller.php.

I code Log::debug to PostsController.php, but the log is not written in laravel.log.

I try use Illuminate\Support\Facades\Log; and use Log; , but both are not working.

Do you find anything wrong with my code?

Thank you for your help.

// web.php

Route::get('/posts/items', 'PostsController@items');
PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Model\Post;
use App\Model\Item;
// use Log;
use Illuminate\Support\Facades\Log;

use App\Http\Resources\Post as PostResource;
use App\Http\Resources\Item as ItemResource;

class PostsController extends Controller
{

    public function items(Request $request)
    {
        Log::info('kita');
        Log::debug('kurukao');
        logger()->debug('debug');

        $post_id = $request->input('post_id');
        return $post_id;
    }

//vue


    methods: {
      mouseenter(id) {
        this.itemId = id;
      },
      mouseleave(id) {
        this.itemId = null;
      },
      getItems() {
        axios.get("/posts/items", {
            post_id: this.$route.params.id
        })
        .then((res) => {
        //   console.log(res.data)
          console.log('ok')
          this.postDataList = res.data.data;
        //   console.log(this.postDataList)
          if(this.postDataList != null){
            this.itemDataList = this.postDataList[0]['items'];
          }
        });
      },


via Chebli Mohamed

Column 'client_id' cannot be null

I am trying to run:

php artisan passport:install

And it is returning me this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null (SQL: insert into oauth_personal_access_clients (client_id, updated_at, created_at) values (, 2022-11-0 8 07:58:48, 2022-11-08 07:58:48))

I am on laravel 5.5 with php 7.1. What am I doing wrong here? Passport version is 2.0.4.



via Chebli Mohamed

lundi 7 novembre 2022

Laravel 5.6: sending email to BCC without adding email in TO()

How to send email to only bcc() without to(). When I tried, I got error

Error Information.

URL: http://example.com Parameters: [] Request Name: Request Method: GET Line Number: 309 File: /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php Client IP: 127.0.0.1 HTTP Referer: Is Secure: Is Ajax: userAgent: Symfony content: Error Message: Whoops! There was an error. ErrorException (E_WARNING) Illegal string offset 'address' ErrorException thrown with message "Illegal string offset 'address'" Stacktrace: #38 ErrorException in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309 #37 Illuminate\Foundation\Bootstrap\HandleExceptions:handleError in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309

Sending email to all bcc without using to



via Chebli Mohamed

dimanche 6 novembre 2022

I want to get the list of users who were present in the club from 10 AM to 12 PM using an SQL query in Laravel eloquent

thank you for reading this issue. please help me with the below issue

I want to user list which users in the club at the time between

  • 022-11-07 11:32:48 - 2022-11-07 12:32:48

below is data store in DB

  • In Time--------------------Out Time----------------- be show in result

  • 2022-11-07 11:32:48 - 2022-11-07 12:32:48 => 1

  • 2022-11-07 10:32:48 - 2022-11-07 11:33:00 => 1

  • 2022-11-07 12:32:00 - 2022-11-07 13:32:00 => 1

  • 2022-11-07 11:45:00 - 2022-11-07 12:15:00 => 1

  • 2022-11-07 10:00:00 - 2022-11-07 13:00:00 => 1

  • 2022-11-07 09:30:00 - 2022-11-07 11:30:00 => 0

  • 2022-11-07 12:35:00 - 2022-11-07 13:32:48 => 0

$activity = Activity::findOrFail($activity_id);

$users = User::whereHas('activities', function ($q) use ($activity) {
   $q->where('activities.activity_id', $activity->activity_id);
})->whereHas('bookingActivities', function ($query) use ($booking) {
   $query->whereNull('cancelled_by')
   ->whereBetween('bookingActivities.entry_time', [$booking->entry_time, $booking->exit_time])
   ->orWhereBetween('bookingActivities.exit_time', [$booking->_entry_time, $booking->exit_time]);
})->paginate();

I have add the query and it will give me 4 result it Should be 5

please help me to how can i add the query so i can get expect result.

thanks in advance



via Chebli Mohamed

samedi 5 novembre 2022

Laravel Fatal error: Uncaught ReflectionException: Class App\Http\Kernel does not exist

Tried to install ** maatwebsite/excel** using composer as,

composer require maatwebsite/excel

but it throws Kernel does not exist error.

There are kernel files in the following locations

app\Console\Kernel.php app\Http\Kernel.php

Also tried composer update, composer dump-autoload. Tried deleting vendor folder and then composer install

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5",
        "laravel/ui": "^3.2",
        "maatwebsite/excel": "^3.1"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "platform-check": false
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

```
`

How do i resolve this issue.


via Chebli Mohamed

vendredi 4 novembre 2022

WhatsApp API integration in Laravel not working

I have issue in my laravel project, the code below is working fine in core php, but it's not workng in laravel

i'm using old laravel version 5.5

even not showing any error

please help me ASAP, i hava a deadline

please help me ASAP, i hava a deadline please help me ASAP, i hava a deadline

`if($request->has('whatsapp') && $request->whatsapp!=0){
                $url = "https://graph.facebook.com/v15.0/{key}/messages";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('{auth key}', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data3 = [
  
    "type"=>"body",
    "parameters" => [
      "type"=>"text",
      "text" => "Mr Jibran"
    ]
];

$data2 = [
  "name"=>"sample_issue_resolution",
"language"=> ["code"=> "en_US" ],
"components" => $data3
];

/*
components:{
  type:body,
  parameters {
    type:text,
    text:Mr Jibran
  }}"

*/

$data = array(
  "messaging_product"=>"whatsapp",
  "to"=>"my number",
  "type"=>"template",
  "template"=> array(
    "name"=>"sample_issue_resolution",
    "language"=> array ("code"=> "en_US" ),
    "components" => array(
      ["type"=>"body",
    "parameters" => array(
      ["type"=>"text",
      "text" => "Mr Jibran"]
    )]
    )
  )
)
;



$fields_string = json_encode($data);

curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);

$resp = curl_exec($curl);
curl_close($curl);

echo $resp;
                
            }

        }

    }`


via Chebli Mohamed

jeudi 3 novembre 2022

Remove/unset specific row from collection in Laravel

I have this eloquent query

 $result= Result::query()
            ->where('city_id', '=', $search_city)
            ->get();
        } 

then inside loop

 foreach($result as $row)
                {
                    if(isset($row->user_id) && $row->user_id!=0)
                    {
                        $UserDetails = User::where('id',$row->user_id)->first();
                        if($UserDetails) 
                        {
                            if($UserDetails->type=='normal user')
                            {
                              // remove this specific row from result 
                            }
                
                        }
                    } 
                }

inside if condition if specific condition met i want to remove only that particular row from the result.

 return view('index', compact('result'));

Any solution Thanks



via Chebli Mohamed

Instance class by some rule

I have some function converting some tag to class name.

function($tag): string {
    return '\App\Services\MyUglyServices\' . ucfirst(Str::camel($tag));
}

I want to instance some class by corresponding tag name. For example:

$obj = app('tag:my_ugly_service');
echo get_class($obj); // I want it to be \App\Services\MyUglyServices\MyUglyService

Is there any way to do it using service providers?



via Chebli Mohamed

mardi 1 novembre 2022

Laravel 5 User::where() My where call isn't working with laravel 5

I have narrowed my error down to this line of code

$user= User::where(['email'=>$req->email])->first();

it it not working with Laravel 5 I think this is from a Laravel 4 project. How do I update it to 5?



via Chebli Mohamed

Why my excel import date format is not working in laravel

I try to import the excel data file but my date format is not working. other than that data import is working file only issue is in the date format Please help to solve this issue.

enter image description here

this is my import code.

<?php

namespace App\Imports;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

use App\student_import;

use App\centres;
use App\Course;

class ImportStudent implements ToModel,WithHeadingRow
{
    /**
    * @param Collection $collection
    */

    public function model(array $row)
    {
        $rowNumber = array_values($row);

        $insert_data[] = array(
            'stud_dob' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[8])),
            'stud_gender' => $rowNumber[9],
            'stud_add1' => $rowNumber[10],
            'stud_nationality' => $rowNumber[13],
            'stud_registration_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[14])),
            'stud_completion_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[15])),
            'stud_course_status' => $rowNumber[16]
        );

    }
}

This is the error I'm getting when import the data file

enter image description here

enter image description here



via Chebli Mohamed