jeudi 29 juin 2023

How to get sorted one to many field with respect to max of a column in Laravel?

I am using Laravel 5.1 and want to get items sorted with respect to one column of the many field.

I have members and subscriptions. Each member has multiple subscriptions with end date as one of the column. I want to sort members with respect to subscriptions with maximum end dates.

I am using the code below but it selects first subscriptions and sort members with respect to first subscriptions.

Member::join('trn_subscriptions as subs', 'subs.member_id', '=', 'mst_members.id')
            ->select('mst_members.*', DB::raw('max(subs.end_date) latest_sub'))
            ->groupBy('mst_members.id')
            ->orderBy('latest_sub','desc')
            ->where('subs.end_date', '<', Carbon::today());

How can I achive sorting with respect to subscriptions for each member having maximum end dates below certain date?

Thank you in advance.



via Chebli Mohamed

mardi 27 juin 2023

How to Count Data from Another Function

I have a trouble from my controller. When i want to count the array from another function in controller is get a error cannot to count

I get this error

Call to a member function get() on array

This my controller :

Function A
public function detailFees(){
$dataArray = array(
    'datapayment' => $datapayment,
    'countafter' => $countafter,
    'countbefore' => $countbefore
  );
}

Function B
public function data(){
$data = count($this->detailFees($market)->get(datapayment))
}

I want to count data with result in number

Thanks for help!



via Chebli Mohamed

lundi 26 juin 2023

Enable tls for phpredis configuration in laravel 5.6 application

the error shows that something like

[2023-06-27 13:51:56] dev.ERROR: read error on connection to {"exception":"[object] (RedisException(code: 0): read error on connection to /var/www/adflow2/webapp/vendor/laravel/framework/src/Illuminate/Redis/Connectors/PhpRedisConnector.php:69)

am currently using this configuration in config/database.php file. but it doesn't enable tls in aws.

    'redis' => [
        'client' => 'phpredis',

        'default' => [
            'scheme' => 'tls',
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_DB', 0),
         
        ],
        'session' => [
            'scheme' => 'tls',
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => env('REDIS_SESSION_DB', 1), // Use a different Redis database for session
         
        ],
    ],

also restart the server after making changes.



via Chebli Mohamed

mercredi 21 juin 2023

How can I fetch business detail by business ID in Laravel?

how am i going to fetch business detail by business ID in Laravel. how to retrieve the information about a business, such as its name, description, and address, given the business ID,s List.

Business Id 123 124 125

If i click on 123 I should get the information regarding 123. Business list is being fetched using user_email(unique and foreign key).

NOte- One user can have multiple businesses.



via Chebli Mohamed

How To Downgrade Laravel 10 To Laravel 8 Version?

How To Downgrade Laravel 10 To Laravel 8 Version ?? if you know please reply ..How To Downgrade The body of your question contains your problem details and results. Minimum 220 characters. your title still describes the problem! Now is a good time to make sure that Thankyou



via Chebli Mohamed

mardi 20 juin 2023

Property ... does not exist on this collection instance [duplicate]

I have 3 table :

  • Table Grade :

    // MIGRATION
    Schema::create('grade', function (Blueprint $table) {
                $table->id();
                $table->string('grade');
                $table->timestamps();
            });
    
    // MODEL
    public function relationToBobot(){
    return $this->belongsToMany(Bobot::class, 'gradebobot', 'grade_id', 'bobot_id');
    }
    
  • Table Bobot :

    // MIGRATION
    Schema::create('bobot', function (Blueprint $table) {
                $table->id();
                $table->string('bobot');
                $table->integer('harga');
                $table->timestamps();
            });
    
    // MODEL
    public function relationToGrade(){
    return $this->belongsToMany(Grade::class, 'gradebobot', 'bobot_id', 'grade_id');
    }
    
  • Table Grade Bobot (Pivot)

    // MIGRATION
    Schema::create('gradebobot', function (Blueprint $table) {
                $table->id();
                $table->bigInteger('grade_id')->unsigned();
                $table->bigInteger('bobot_id')->unsigned();
                $table->timestamps();
                $table->foreign('grade_id')->references('id')->on('grade')->onDelete('cascade');
                $table->foreign('bobot_id')->references('id')->on('bobot')->onDelete('cascade');
            });
    

I want to show "grade" where have "bobot". This is my Controller :

public function test(){
        $grade = Grade::all();
    return view('welcome', compact('grade'));
    }

And this is my Blade View :

@foreach ($grade as $item)
    <h1></h1>
    @foreach ($grade->relationToBobot->where('grade_id', $item->id) as $item)
        <p></p>
    @endforeach
@endforeach

Can someone help me.. Thanks

Expectation :

A

100

200

300

400

B

500

600

700

800

C

900

1000

1100

1200



via Chebli Mohamed

lundi 19 juin 2023

file_exists(): open_basedir restriction in effect

I am develope a laravel app. I go to the route folder myapp/routes/web.php on serve and register a new route as follows:

Route::get('/linkstorage', function () {
    Artisan::call('storage:link');
});

when i enter https://chanvay.store/linkstorage and hit enter. Error appeared

ErrorException (E_WARNING) file_exists(): open_basedir restriction in effect. File(/home/chanvays/domains/chanvay.store/public_html/public/storage) is not within the allowed path(s): (/home/chanvays/:/tmp:/var/tmp:/opt/alt/php81/usr/share/pear/:/dev/urandom:/usr/local/lib/php/:/usr/local/php81/lib/php/) Anybody help me ?

Anybody help me fix this issue ? I can not comman php artisan storage:link on serve.



via Chebli Mohamed

dimanche 18 juin 2023

Firebase Push Notification with Laravel 5.6

I am asking for help in push notification (especially Firebase Cloud Messaging : FCM). I already have checked the official documentation about it and it was pretty clear but i just wanna know how to have a simple summary of implementation of it using PHP Laravel 5.6 and what's the best practices on it . Thank you in advance for your help. I checked the official documentation of Firebase Cloud Messaging



via Chebli Mohamed

I Need to translate custom request validation Laravel

I Need to translate custom request validation laravel like extras.*.id.required

I Need to translate custom request validation laravel like extras.*.id.required i need to translate it without using messages() method i need the result get from translation files ,validation laravel



via Chebli Mohamed

samedi 17 juin 2023

Laravel Custom Rule Validation with Array of Form Fields

I want to access attribute values in the custom validation rule I created.

HTML

Designation Dropdown
<select name="resource[{?}][designation]>
<option value=1>First Value</option>
<option value=2>Second Value</option>
</select>

Allocation Dropdown
<select name="resource[{?}][allocation]>
<option value=1>First Value</option>
<option value=2>Second Value</option>
</select>

Controller Code

'resource.*.allocation' => ['required',new ResourceQuotation()],
'resource.*.designation' => 'required',

Laravel Custom Rule - ResourceQuotation

public function passes($attribute, $value)
{

$designation = request()->input("resource.*.designation"); <!--//I am confused here, how to access the designation array value since we might have multiple.!->

$allocations = ResourcePrice::select('allocation','fixed_allocation')->where('id',$designation)->first();

 if($allocations->fixed_allocation=1){
    $this->message = "Maximum allocation allowed is 10%";
    return false;
 }

 else{
   return true;
 }

}

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

First I thought to use a loop but how to display individual message errors? I found this tutorial but they are using it for a single value comparison, not with different field attributes.



via Chebli Mohamed

vendredi 16 juin 2023

how to store form with 1500 plus fields using jquey ajax in laravel

How can I store a form with more than 1500 fields in Laravel 5.8?

Controller:

public function store(Request $request)
{
     dd($request->all());
}

View file:

@extends('main')
@section('content')

<form class="add_form" id="add_form" enctype="multipart/form-data">
@csrf
<input type="text" name="text_1" >
.
.
.
.
to 1514 parameters
<button type="button" id="submit" >Submit</button>
</form>

@endsection
@push('scripts')

<script type="text/javascript">
  $(document).ready(function(){
    $("#submit").on("click",function(e){
      e.preventDefault();
      if($("#add_form").valid()){
        $.ajax({
          type:"POST",
          url:"",
          data: new FormData($('#add_form')[0]),
          processData: false,
          contentType:false,

          success: function(data){
            if(data.status==='success'){
                  location.reload();
            }else if(data.status==='error'){
                  location.reload();
            }
          }
        });
      }else{
        e.preventDefault();
      }
    });
  });
</script>

@endsection

In my function, I'm only getting an array of 1000 fields, but in my form there are 1514 fields. How can I handle this?



via Chebli Mohamed

Wrong php version - laravel 5

I have a problem with the PHP version after running php --version. It should be the 5.6.40 PHP version, but after running this command into my Laravel (php --version), it shows PHP 8.2.40, but when I try to run phpinfo(), it shows 5.6.40 (this is the version I need, not 8.2.40). What am I going to do?

should be the 5.6.40 PHP version



via Chebli Mohamed

mardi 13 juin 2023

How can I filter on Multiple Checkbox values retrieved?

am working on a filtering system in Laravel PHP framework and I am trying to filter on products brand selected from a checkbox input.

When I try to retrieve Products lets say for example with the brand Intel which I have 3 product it works fine but when I try to filter on more then one value it's only receive the first selected checkbox item.

here is my view code:

<div id="filters-status" class="mt-3 collapse" aria-labelledby="filters-status-heading"
                            style="">
                            <ul class="space-y-6 mb-8">
                                @foreach ($prods->unique('marque') as $itme)
                                    <li>
                                        <label class="flex items-center cursor-pointer w-full">
                                            <input type="checkbox" id="terms" name="marque[]"
                                                value=""
                                                class="h-5 w-5 mr-2 rounded border-jacarta-200 text-accent checked:bg-accent focus:ring-accent/20 focus:ring-offset-0 dark:border-jacarta-500 dark:bg-jacarta-600">
                                            <span class="dark:text-white">
                                                
                                            </span>
                                        </label>
                                    </li>
                                @endforeach
                            </ul>
                            <input
                                class="cursor-pointer rounded-full bg-accent-lighter w-full py-3 px-8 text-center font-semibold text-white transition-all hover:bg-accent-dark"
                                type="submit" value="Soumettre">
                        </div>```

enter image description here This are the brands checkbox

and this is my controller code:

public function fliter(Request $request)
    {
        $brand = ($request->marque);
        $disponible = ($request->disponibilite);
        $query = DB::table('produits');
        if($brand){
            $query->where('marque', $brand);
        }
        if($disponible) {
            $query->where('disponibilite', $disponible);
        }
        $filtterProduits = $query->get();
        return response()->json($filtterProduits); 
    }

this is the Json result if i select one brand

{
"id": 3,
"sous_categorie": 1,
"fournisseur_id": 1,
"ref": "104081",
"filenames": "[\"168591280568.webp\"]",
"description": "13th Generation Intel® Core™ i5 Processors 10Coeur 16 Threads Max Turbo",
"designation": "CORE I5 13400F PROCESSOR",
"prix_achat": 35000,
"prix_gros": 36800,
"prix_vent": 40000,
"marque": "INTEL",
"disponibilite": 0,
"quantite": 10,
"created_at": "2023-06-04 21:06:45",
"updated_at": "2023-06-11 20:15:11"
},
{
"id": 4,
"sous_categorie": 1,
"fournisseur_id": 2,
"ref": "103329",
"filenames": "[\"168616970297.webp\"]",
"description": "13th Generation Intel® Core™ i7 Processors\r\nTotal Cores 16\r\nTotal Threads 24\r\nMax Turbo Frequency\r\n5.40 GHz",
"designation": "CORE I7 13700KF PROCESSOR",
"prix_achat": 45000,
"prix_gros": 50000,
"prix_vent": 56400,
"marque": "INTEL",
"disponibilite": 0,
"quantite": 10,
"created_at": "2023-06-07 20:28:22",
"updated_at": "2023-06-11 20:15:21"
},
{
"id": 5,
"sous_categorie": 1,
"fournisseur_id": 2,
"ref": "103327",
"filenames": "[\"168616985056.webp\"]",
"description": "13th Generation Intel® Core™ i9 Processors\r\nTotal Cores 24\r\nTotal Threads 32\r\nMax Turbo Frequency 5.80 GHz",
"designation": "CORE I9 13900KF PROCESSOR",
"prix_achat": 74000,
"prix_gros": 74500,
"prix_vent": 82000,
"marque": "INTEL",
"disponibilite": 0,
"quantite": 15,
"created_at": "2023-06-07 20:30:50",
"updated_at": "2023-06-11 20:15:31"
}

as u can see 3 items

when I try to retrieve more than one brand it's only gets me the first checkbox selected values.

please don't give me negative comments I am new to Laravel, thanks in advance .



via Chebli Mohamed

lundi 12 juin 2023

filters the data of a school to which the user belongs

I want to display the list of students from a school the user belongs to and not display data from other schools. for that I created two user tables: id , school_id school table: id, name, address,.... student table: id,school_id,name,address,.... I want to display the students of the school to whom this user belongs the display is done in browse.blade.php generated by voyageur how can i make this filter Thank you for help

the user belongs to a company and can only see data from that school I have a browse in /views/students that shows students from all schools



via Chebli Mohamed

dimanche 11 juin 2023

dependent drop in laravel with ajax doesn't work

**this is the blade **


    
                            <label class="form-label" for="basic-default-password12">اختر فصل دراسي</label>
                            <div class="input-group">
                                <span class="input-group-text" id="basic-addon11"><i class='bx bx-category-alt bx-tada'
                                        style='color:black'></i></span>
                                <select type="text" name="semester_id" class="form-control">
                                    <option value="">None</option>
                                    @foreach ($semesters as $key => $semester)
                                        <option value=""></option>
                                    @endforeach
                                </select>
                            </div>
                            <label class="form-label" for="basic-default-password12">اختر مرحلة دراسية</label>
                            <div class="input-group">
                                <span class="input-group-text" id="basic-addon11"><i class='bx bx-category-alt bx-tada'
                                        style='color:black'></i></span>
                                <select type="text" name="stage_id" class="form-control">
                                    <option value=""></option>
                                </select>
                            </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js"
        integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>


    <script type="text/javascript">
        $(document).ready(function() {
            $('select[name="semester_id"]').on('change', function() {
                var semester_id = $(this).val();
                if (semester_id) {
                    $.ajax({
                        url: "/" + semester_id,
                        type: "GET",
                        dataType: "json",
                        success: function(data) {
                            $('select[name="stage_id"]').html('');
                            var d = $('select[name="stage_id"]').empty();
                            $.each(data, function(key, value) {
                                $('select[name="stage_id"]').append(
                                    '<option value="' + value.id + '">' + value
                                    .stage_name + '</option>');
                            });
                        },

                    });
                } else {
                    alert('danger');
                }
            });
        });
    </script>


   satgecontroller

`public function GetStage($semester_id){         $data = Stage::where('semester_id',$semester_id)->orderBy('stage_name','ASC')->get();             return json_encode($data);      }`

**this is th web.php **


`Route::controller(StageController::class)->group(function(){
    Route::get('/stage/ajax/{semester_id}' , 'GetStage');

});`

i want to get the stage by semester_id when i choose the semester but when i choose any thing in semester the stage doesn't show me any results why my code doesn't work?

I have made several many attempts, but nothing works and I do not know why when I put Ajax CDN in the admin dashboard and restore it via

@extend(admin.admin.dashboard) 

a path that does not work, it requires me to put it in the same code



via Chebli Mohamed

samedi 10 juin 2023

Uncaught Error: Class "IlluminateFoundationApplication" not found

PHP Fatal Error:  Uncaught Error: Class "IlluminateFoundationApplication" not found in /home/prasaanth/myport/bootstrap/app.php:14
Stack trace: #0 /home/prasaanth/myport/artisan(20): require_once()
#1 {main} 
thrown in /home/prasaanth/myport/bootstrap/app.php on line

When I try to create a Laravel project, it is creating without a vendor file. Some other files are missing, and the  console is showing this error. Also, when I run the Artisan server, the same error is coming.

I had tried by creating new project and modify the composer



via Chebli Mohamed

mercredi 7 juin 2023

Make Reset APIs without sanctum

(using POSTMAN and Only Laravel api.php routes and Middleware and Don’t use any external packages, also don’t forget to secure your API routes with a KEY)

Description: 1 - Create authentication API for user login and register.

2 - make end-point for profile which get user profile data (name, email, photo, age, etc..).

3 – let’s assume we have (categories, subcategories and user_subcategories table) and each category have some Subcategories for example (development category has subcategories (front-end, back-end, flutter and UI)) and we have a user in development category and he has only two subcategories in user_subcategories table,

(challenge: what’s the best way to view all these relations if the mobile app Requests a user profile data with categories?), show this API in a Laravel project

I searched for any explanation without the sanctum, but I did not find it



via Chebli Mohamed

Why Laravel passport login suddenly not working?

I am getting error for when try to login. I am not update any package at all but suddenly getting this error.

There was an error while creating the signature: error:0909006C:PEM routines:get_name:no start line

But i am sure that the key file is in the correct format:

storage/oauth-private.key -----BEGIN RSA PRIVATE KEY----- KEY VALUE -----END RSA PRIVATE KEY-----

storage/oauth-public.key -----BEGIN PUBLIC KEY----- KEY VALUE -----END PUBLIC KEY-----

Any idea ? I am using Laravel 5.7, Passport 7.5.1, PHP 7.2.24.

Fix the error

There was an error while creating the signature: error:0909006C:PEM routines:get_name:no start line

on vendor/lcobucci/jwt/src/Signer/OpenSSL.php:27



via Chebli Mohamed

mardi 6 juin 2023

Dispatch on laravel 5.6 won't run function handle(), only run construct()

Hi i try to create queue job, using queue=redis in laravel 5.2 But i've checked using log, my job only run construct() not running handle()

can you suggest what's wrong?

my dispatch scheme like this :

Controller -> dispatch -> dispatch_now() -> dispatch_now()

here is my code :

class LogHelper implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $transId;

    public function __construct(int $transId)
    {
        $this->transId = $transId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(){
       //do code
    }
}

expecting of those job was running normally like normal job and code excuted



via Chebli Mohamed

lundi 5 juin 2023

Is there any ready-made solution or code available in Laravel for Users, Access, Locations Management etc

IN Laravel : Is there any ready-made solution or code which includes common area for project (for avoiding repetitive task such as User management, Access management, Location based access, Department based access etc.)

(Ready made common needs area to make new projects)



via Chebli Mohamed