mardi 31 août 2021

Why isn't Laravel Dusk launching a browser window?

I am working on upgrading a Laravel application from 5.3 to 5.4, so I can use Laravel Dusk for testing.
I have followed the official Laravel guide as well as this scotch.io tutorial and am having no luck.
Executing php artisan dusk produces the following output:

In Process.php line 1027:

  TTY mode is not supported on Windows platform.

Then the program exits. Is this preventing Dusk from launching a browser window?

Edit: I have also tried installing and running chromeWebDriver as described in this answer.



via Chebli Mohamed

Laravel5.5 is not running in PHP7.0

As the Laravel 8 is not supported on PHP 7.0, I decided to go with lower version of Laravel. Because, we are not in the position of upgrading the server php version.

After reading the requirements here we found the latest Laravel version that is supported in PHP7.0 will be Laravel5.5.

we installed the version using composer. Below is the Laravel version in the server.

enter image description here

However, still the error shows in the nginx server as below

Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 7.2.5".

The composer.json in the laravel root directory as below

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.5.*",
        "laravel/tinker": "~1.0"
    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "~1.0",
        "phpunit/phpunit": "~6.0",
        "symfony/thanks": "^1.0"
    },
}

Any workaround to bring the application live?



via Chebli Mohamed

Laravel / JQGrid - Order by on laravel dynamic property

I'm currently working with free JQGrid 4.6 version and Laravel 5.8 and I have some issue with a grid that I have develop. So here is the problem recap : i want to sort some columns that contains datas coming from dynamic attributes of my model Contact.

Here is the columns of the grid :

{name: "ID_PROJET", hidden:true},
{name: "DT_REEL_DON", align:'center',formatter:'date',sorttype : 'date', datefmt: 'd/m/Y',formatoptions: {srcformat:'Y-m-d',newformat: "d/m/Y"},excel:true, width:90},
{name:"LIBELLE_PROJ", excel:true,width:250},
{name:"contact.full_identite", excel:true},
{name:"MT_DON",formatter:'currency',align:'right',sorttype:'numeric',excel:true, width:60},
{name:"lib_type_don",excel:true, sortable:false},
{name:"lib_moyen_paiement",excel:true,width:60,sortable:false},
{name:"MAIL", excel:true},
{name:"ADRESSE1", excel:true},
{name:"CDPOST", excel:true,width:50},
{name:"COMMUNE", excel:true},
{name:"PAYS", excel:true,width:70},
{name:"SOLLICITE",excel:true,width:30},
{name: "action",template:"action",sortable:false, width: 75, align:"center",excel:false}  

Datas come from this request that i serialize to JSON :

$dons = $dons->with(['projet','contact'])
     ->join('projet','projet.ID_PROJET',"=",'don.ID_PROJET')
     ->join('contact','contact.ID_CONTACT',"=",'don.ID_CONTACT')
     ->orderBy($sidx,$sord)
     ->select('don.*','contact.MAIL','contact.ADRESSE1','contact.CDPOST','contact.COMMUNE','contact.PAYS','contact.SOLLICITE','projet.LIBELLE_PROJ')
     ->offset($start)->limit($limit)->get();

$sidx, $sord, $start and $limit are GET parameters send by JQGrid when the user have done an action on the grid (paging, sorting etc)

It's working great, but the problem is for the column contact.full_identite which is not a field into my contacts table. It's a laravel dynamic attributes define like that :

    public function getFullIdentiteAttribute() {
        // si entreprise 
        if ($this->TYPE_CONTACT_ == 1) {
            return $this->ORGANISME;
        }
        // si particulier
        else if ($this->TYPE_CONTACT_ == 2) {
            return $this->NOM . ' ' . $this->PRENOM;
        }
    }

The idea is to return the full name of a person if this is a particular or the organisation name if this a company. So i'm searching for a way to apply an orderBy clause (in my request above) on this dynamic attribute when the user want to sort this column. For the moment, i sort on the field NOM and it's working good but this is not the result that i expect.

Here is a screenshot of a structure part of my contact table :

Structure table

Thanks in advance for your help, if i wasn't enough clear don't hesitate to ask me some details



via Chebli Mohamed

Allow only numeric and float value with validation in Laravel

I have a field days in my database nopw i want to save only integer or float value in this column

like values can be

1
2 
0.5 
2.5

i tried to use numeric but then it is not allowing me to enter float values

$this->validate($request, [
     'days' => 'required|numeric|min:1|max:50',
]);

Any help is highly appreciated.

Thanks



via Chebli Mohamed

lundi 30 août 2021

Is createApplication() method required for Laravel Dusk test cases?

I am attempting to set up Laravel Dusk in a Laravel 5.4 application. Executing php artisan dusk does not launch a browser window as shown in this guide and I am trying to figure out why. PHPStorm complains that the ExampleTest class created during execution of the php artisan dusk:install command must implement the createApplication() method, but I cannot find any mention of this method in:

  1. The official Laravel guide
  2. This Scotch.io guide
  3. A search of all files within the Laravel application directory using PHPStorm's search function.

ExampleTest class is as follows:

class ExampleTest extends DuskTestCase
{
    /**
     * A basic browser test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->browse(function ($browser) {
            $browser->visit('/')
                    ->assertSee('Laravel');
        });
    }
}


via Chebli Mohamed

Will 'TTY mode is not supported on Windows platform.' error prevent tests from running with Laravel Dusk?

I am in the process of updating an application from Laravel 5.3 to 5.4 and am trying to set up Laravel Dusk for browser testing. I have followed the guide here and am receiving an error message that reads 'TTY mode is not supported on Windows platform.' When I attempt to execute php artisan dusk. Other answers (specifically this one state this is okay, and that it can be ignored. However, the example test does not appear to be running. Is this error preventing tests from running, or is it some other issue?



via Chebli Mohamed

Make Accept Terms and conditions fields required in Laravel

I have a checkbox in vue.js

<input  v-model="form.accept" name="Accept" type="checkbox" value="false">

i have model defined

 data() {
        return {
            form: new Form({
                accept: false,

now i want to make this field required

 'accept' =>'required|true',

but this is not working



via Chebli Mohamed

Getting 429 (Too Many Request) in vue.js laravel

I'm using vue.js and laravel when i open edit page i get this error in my console but Update function is called on button click and bill url is also called multiple times without parameter on mounted function

app.js:1088 GET http://localhost:8000/api/userbackend/bill/undefined 404 (Not Found)

POST http://localhost:8000/api/userbackend/Update 429 (Too Many Requests)

Code Snippet:

async mounted(){
           this.roleid = this.userData.role_id;
           const header = {
                      'Authorization': 'Bearer ' + this.LoginUserData,
                };
            this.editId = this.$route.params.id;

            if(this.$route.params.id !== undefined) { 
             try{    
             
             let response = await axios.get(`/api/userbackend/bill/${this.editId}` ,{headers: header});
             this.form = response.data;
}

            saveRecord(){
                let loader = this.$loading.show();
                let formData = new FormData();
                formData.append('id', this.editId);
                ....
                
                const header = {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': 'Bearer ' + this.LoginUserData,
                  };
           
          axios.post('/api/userbackend/Update', formData ,{headers: header}).then((response) =>{
                   loader.hide(); 
                    if(response.data.status == true){
                      .....
                     }   
                })
                .catch((response) => {
                    loader.hide(); 
                    this.showErrorMsg();
                 });
            },
 validateBeforeSubmit(e) {
              e.preventDefault();
                let app = this;
                this.$validator.validateAll().then((result) => {
                    if (result) {
                        app.saveRecord();
                        return;
                    }
                   this.showWarningMsg();
                });
            }

Any suggestion is highly appreciated



via Chebli Mohamed

show default object from model if table is empty

I have 2 models named setting and settings one controller settingController

following is database table name setting

id key    Value      created_at       updated_at

if this table is empty then I want to show some default values. following my model codes

namespace App;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    protected $fillable = ['key', 'value'];
}

and settings model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Settings extends Model
{
    const options = [
        'key' => 'some_val',
        'value' => 0
    ];

public function __construct()
{

    foreach (self::options as $option => $default_value) {
        $this->{$option} = $default_value;
    }
    
    $settings = Setting::all();
    foreach ($settings as $setting) {
        $this->{$setting->key} = $setting->value;
    }
}

}

Now while model call in controller

public function getEdit()
{
    $settings = Settings::all();
    dd($settings);
    return view::make('admin/settings', compact('settings'));
}

If there is data in the table then it should show the table data. if no data then it should show the default options.

Now I am only getting empty while there is no data in a table. How can i solve above issue?



via Chebli Mohamed

dimanche 29 août 2021

Laravel Nova - whitecube / nova-flexible-content

How to use belongsTo inside FLEXIBLE fields ?

    Flexible::make('Exmaple', 'blocks')
        ->addLayout('Exmaple', 'block', [

                BelongsTo::make('User'),

        ])->button('Add block'),

I am getting error

Call to protected method Whitecube\NovaFlexibleContent\Layouts\Layout::relationLoaded() from scope Laravel\Nova\Fields\BelongsTo



via Chebli Mohamed

samedi 28 août 2021

deploying and running a Laravel with react website on a shared server like Bluehost

I have a laravel with React app running on my local env. I have two folders Backend and Frontend. I use "php artisan serve" to start up the backend and then npm start to call up the page from the front end.

My question is, "How can I deploy this app up to a shared hosting service like bluehost without command access?" Is there some general guidance available to walk me through this?



via Chebli Mohamed

While hitting anchor tag, getting route not defined error

Laravel Route: Route::post('verify-phone', [LoginController::class, 'verifyPhone'])->name('verify-phone');

<a href="" >Resend OTP</a>



via Chebli Mohamed

How to join a "IN" result and check "where" active = 1?

In my query I check if tokens.id exists in dapp_tokens. I want to add that the result in dapp_tokens also has to be active = 1 in the dapps table. So I need to join the dapps table of the row with tokens.id that has been found in dapp_tokens but how can I do that in Raw SQL?

$data['tokens'] = Token::where('active', 1)
            ->whereRaw('tokens.id in (select token_id from dapp_tokens where active = ?)', [1])
            ->sortable('market_cap')->orderby('id','desc')->paginate($page_count);


via Chebli Mohamed

How to deploy separated / decoupled Laravel & Vue Js Project?

Hi I am very new to this platform. I'm stuck on how to deploy my separated projects (Laravel for Back-end & Vue.js(2) for my front-end) into a shared hosting w/cpannel. I search a lot from the internet but still did not found an accurate solution. All tutorials is based on Laravel + Vue js that is built into the Laravel app , not the separated or decoupled one. Can I really deploy it into 1 shared hosting server ? or I need to buy 2 separated server and deploy my front-end and back-end project separately.



via Chebli Mohamed

Laravel 5.3 web.php and api.php: what is proper usage to ensure admin-only access to designated site sections?

I am trying to clean up my Laravel 5.3 route related files (web.php, api.php) in order to ensure certain parts and functions of my site are only accessible by admin user.

I know Laravel 5.3 is a bit dated, but trying to figure out how pros would go about setting up routes to accomplish my goal. The way I have things now seems to work (key word, 'seems'), but before I upload to production side, I just want a sanity check.

Here are the types of access as well as background functionality I have:

1. Guest - unlogged in users who have access to most of the site, so urls such as mysite.test/somecontent

2. Admin - has admin role as user, and can access the admin panel via mysite.test/adminpanel. While in admin panel, has access to api endpoints, since my admin panel CRUD actions are via my API endpoints. That is endpoint urls like mysite.test/api/somecontent. Angular is used for the CRUD functionality and my main concern is to make sure there are no backdoors via the api that allows non authorized visitors to use the api endpoints to delete data, view data.

3. Logged in - these users have access to their profile, etc, so urls like mysite.test/myprofile

4. Webhooks, Queue actions - These are, for instance webhhoks from Mailchimp, Stripe, Zoom.

I read here to get familiar with routing under Laravel 5.3:

https://laravel.com/docs/5.3/routing

There I see mention of route middleware and searched on github.com for example Laravel 5.3 projects, but in looking at example web.php and api.php files I don't see the middleware functionality being implemented.

So I tried my best to set up these 2 route related files, and have some questions:

1. Is this generally the correct approach or am I setting my self up for security issues? 2. Do I truly need to specify api related routes in my web.php, or should I only be doing that in api.php?

Here is my web.php (representative lines)

Auth::routes();
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => 'web'], function () {
    // Auth
    Route::auth();
    Route::get('/register/verify/{token}', 'Auth\\RegisterController@verifyEmail');
    
    // Main
    Route::get('/somecontent', 'SomeController@index');
    Route::post('/somecontent/someaction/{id}', 'SomeController@someaction');

    // Redirects
    Route::get('/home', function () {
        return Redirect::to('/');
    });

    // static pages
    Route::get('somepage', function()
    {
        return View::make('static/somepage');
    });

    Route::get('/pusher', function() {
        event(new App\Events\SomeactionEvent('New Something Posted'));
        return "Event has been sent!";
    });

});

// Authenticated Users
Route::group(['middleware' => ['web', 'auth']], function () {
    // Change Password
    Route::get('/password/change', 'Auth\\PasswordController@showChangePasswordForm');
    Route::post('/password/change', 'Auth\\PasswordController@changePassword');

    // Profile
    Route::get('/myprofile', 'ProfileController@index');

    // Buy
    Route::get('/mybilling', 'BillingController@index');

});

// Admin Only
Route::group(['middleware' => ['web', 'auth', 'admin']], function () {
    // Admin Panel
    Route::get('/adminpanel', 'AdminpanelController@index');

    // API endpoints
    Route::resource('api/somecontent', 'Api\SomecontentController');
});

Route::get('/logout', 'Auth\LoginController@logout');

// webhooks stuff
Route::post(
    'stripewebhook/webhook',
    'StripeWebhookController@handleWebhook'
);

And here is typical line in the api.php:

use Illuminate\Http\Response;

    Route::group(['prefix' => 'api'], function () {
        Route::resource('somecontent', 'Api\SomecontentController');
    });

Regarding my admin panel angular-based CRUD actions, here is a typical function in the controller:

        $scope.delete = function () {
            $scope.busy = true;
            $http.delete('/api/somecontent/' + $scope.somecontent.id).then(function (response) {
                $scope.busy = false;
                $location.path('/somecontent');
            }, function (response) {
                $scope.busy = false;
                $scope.error = 'Unable to delete somecontent...';
            });
        };

And here is typical entry in the angular routes.js file:

angular.module('adminpanel')
.config(function ($routeProvider, $locationProvider) {
    $locationProvider.hashPrefix('');
    $routeProvider
        .when('/somecontent/delete/:id', {
            templateUrl: 'views/adminpanel/somecontent/delete.html',
            controller: 'SomecontentDeleteController'
        })


        // Catch all
        .otherwise({
            redirectTo: '/'
        });
});

Thanks in advance!



via Chebli Mohamed

vendredi 27 août 2021

Invalid IFSC number. The number should be 11 digits in the format ABCD0123456 on stripe

I am using Cartalyst\Stripe\Stripe I have an issue with creating a bank account token for the Indian bank account

here is my code

`

$token = $stripe->tokens()->create([
  'bank_account' => [
    'object'=>'bank_account',
    'country' => 'IN',
    'currency' => 'INR',
    'account_holder_name' => 'Jenny Rosen',
    'account_holder_type' => 'individual',
    'routing_number' => '110000000',
    'account_number' => '000123456789',
    'default_for_currency'=>'false'
    
  ],
]);

`

I am getting this error Invalid IFSC number. The number should be 11 digits in the format ABCD0123456.

Version I am using "laravel/framework": "5.5.", "cartalyst/stripe-laravel": "7.0."



via Chebli Mohamed

What is the meaning the mimes in laravel [duplicate]

I am learning laravel and I have a doubt about the meaning

'required|mimes:pdf'

This part(mimes we use in validations, but I don't understand it's meaning.

Best regards!!



via Chebli Mohamed

How to show bindPopUp() in Leaflet with angularjs

I am trying to use leaflet with angularjs. But I'm having trouble displaying array data table from "sensor" in "bindPopUp" content. Can anyone help me how to display the data?

This is the array I'm using

$scope.oAllMarker = function() {
  $scope.location = [{
    "loc": "Jodhpur",
    "lat": 26.28,
    "long": 73.02,
    "sensor": [{
        "v1": 11
      }, {
        "v2": 12
      }, {
        "v3": 13
      }]
   },
   {
     "loc": "Bikaner",
     "lat": 28.0229,
     "long": 73.3119,
     "sensor": [{
        "v1": 21
      }, {
        "v2": 22
      }, {
        "v3": 23
      }]
    },
    {
      "loc": "Churu",
      "lat": 28.3254,
      "long": 74.4057,
      "sensor": [{
        "v1": 31
      }, {
        "v2": 32
      }, {
        "v3": 33
      }]
    }
  ];

And this is the angularjs and leaflet code i am using

  angular.forEach($scope.location, function(item, key) {
    $scope.dataIcon = L.icon({
      iconUrl: "",
      iconSize: [38, 45]
    });
    $scope.content = String('Table:Array sensor (v1,v2,v3)');
    marker = new L.marker([parseFloat(item.lat), parseFloat(item.long)], {
      icon: $scope.dataIcon
       }).addTo($scope.map).bindPopup($scope.content);
  });
}


via Chebli Mohamed

multiple with with closure in laravel

I'm trying to filter data first closure is for attachment and second closure for AdminAttachment

   $data = UserSalary::with(['userData','Attachments' => function($query) use($id) {
        $query->where('type', 3);
        $query->where('application_id',$id);
      }])->with(['AdminAttachments' => function($queryadminattachement) use($id) {
        $queryadminattachement->where('type', 3);
        $queryadminattachement->where('application_id',$id);
      }])->find($id);

but now i'm getting only Attachment data but AdminAttachment is blank but in my database data is there so it must return datas from both the attachment because search criteria is also same. Any solution please

Thanks



via Chebli Mohamed

jeudi 26 août 2021

Laravel array column stops at 16?

I have a text column in Laravel which is casted as an array, like so:

    protected $casts = [
        'onboarded_enums' => 'array',
    ];

For whatever reason, it maxes out at 16 items. I can push new ones onto it and save the model instance, and another gets removed. There's nothing fancy in the logic or anything, it just seems to bump one off when adding more than 16:

    public function setOnboardingStep(Request $request){
        $user = JWTAuth::parseToken()->authenticate();  

        $onboarded_enums = $user->onboarded_enums ? : [];

        if(!in_array($request->type, $onboarded_enums)){
            $onboarded_enums[] = $request->type;
        }

        $user->onboarded_enums = $onboarded_enums;

        $user->save();

        return $user;
    }

Has anyone experienced this before? I've Googled around relentlessly about it, but I can't see anything useful.



via Chebli Mohamed

When and how do Laravel daily logging files get deleted?

I'm running Laravel 5.8 and using the built-in Laravel Log functionality. And I've created a few custom logs.

I set each of them to store the daily log files for 30 days, like so:

'reconciliation' => [
    'driver' => 'daily',
    'path' => storage_path('logs/reconciliation/reconciliation.log'),
    'days' => 30
]

However, the logs don't stay for 30 days, like I've set them to. They stay for 7. I've heard that there is another configuration called log_max_files, which might be what I'm looking for. But all the references to log_max_files are from Laravel 5.4 and below. And I know that the logging functionality was revamped in 5.6. So I'm not sure if log_max_files even works anymore and I'd like to test it.

I've created a new log file with a date far outside the current 7-day range and I want to confirm that it gets deleted when the logs get cleared.

I'm just not sure when Laravel clears out the old logs. I couldn't find any in-depth information like that in the docs and my Google searching hasn't turned anything up.

I've tried restarting my server, running php artisan config:clear and php artisan cache:clear with no luck.

Does anyone actually know the process by which these log files get deleted and when that process runs?



via Chebli Mohamed

How to Fix: Trying to get property 'passing_grade' of non-object Laravel

I have a data course that has been successfully completed by the learner. Then, I want to display the course data and add a certificate download button.

I have code like this, but I get error "Trying to get property 'passing_grade' of non-object".

Controller

    public function indexListCompetency()
    {
        $user = Auth::user('lms_web');


        $course_case = DB::raw("course.id, course.title, course.cover_image, course.is_published,
            CASE
            WHEN COUNT(classroom.id) AND (
                COUNT(group_discussion.id) OR
                COUNT(competency_file.competency_id) OR
                COUNT(course_activity.id)
            )
            THEN \"Blended\"
            WHEN COUNT(classroom.id)
                THEN \"Offline\"
            ELSE \"Online\"
            END AS course_contain");
        
        if ($user->customer_type_id == 4) {
            $course_learner = CourseLearner::select($course_case, 'course_learner.*', 
                DB::raw('SUM(duration) as total_duration,
                    CASE WHEN course.corporate_id IS NOT NULL THEN "Internal"
                    ELSE "External" END AS course_provider'
                )
            );
        } else {
            $course_learner = CourseLearner::select($course_case, 'course_learner.*', 
                DB::raw('SUM(duration) as total_duration,
                    CASE WHEN course.hotel_id IS NOT NULL THEN "Internal"
                    ELSE "External" END AS course_provider'
                )
            );
        }
            

        $course_taken = $course_learner
            ->where('learner_id', auth('lms_web')->user()->id)
            ->join('course', 'course.id', 'course_learner.course_id')
            ->leftJoin('group_discussion','group_discussion.course_id','course.id')
            ->leftJoin('classroom','classroom.course_id','course.id')
            ->leftJoin('course_activity','course_activity.course_id','course.id')
            ->leftJoin('competency_file','competency_file.competency_id','course.id')
            ->join('file_assignment', 'file_assignment.id', 'competency_file.file_assignment_id')
            ->orderByDesc('course_learner.updated_at')
            ->groupBy('course_learner.id', 'course_learner.course_id', 'course_learner.trainer_id', 
                'course_learner.batch_id', 'course_learner.learner_id', 'course_learner.open_at', 'course_learner.close_at',
                'course_learner.created_at', 'course_learner.updated_at', 'course_learner.is_complete', 
                'course.id', 'course.title', 'course.cover_image', 'course.is_published');
                
            $progress = Progress::select('course_id', DB::raw('SUM(value) as progress'))
            ->where('user_id', auth('lms_web')->user()->id)
            ->groupBy('course_id')
            ->get();
        $user_courses = $course_taken->get();

        $complete = 0;
        
        // dd($user_courses);
        foreach ($user_courses as $key => $item) {
            
            foreach ($progress as $items) {
                if ($item->course_id == $items->course_id) {
                    if ($item->total_duration <= $items->progress) {
                        $complete++;
                    }
                }
            }
            $abc = $progress;
            
            // Certificate of Completion
            $cert_comp      = new CertificateNumber;
            $cert_comp->set_completion($user->id, $item->course_id, $user->def_corporate_id, $user->def_hotel_id);
            $cert_comp_num  = $cert_comp->getID();

            // Certificate of Completion
            $cert_att       = new CertificateNumber;
            $cert_att->set_attainment($user->id, $item->course_id, $user->def_corporate_id, $user->def_hotel_id);
            $cert_att_num   = $cert_att->getID();

            $user_courses[$key]['cert_completion_num'] = $cert_comp_num;
            $user_courses[$key]['cert_attainment_num'] = $cert_att_num;
            $user_courses[$key]['course'] = $cert_comp->course;

            // dd($item->course);
            
        }
        
        switch ($user->customer_type_id) {
            case 4:
                $company = Corporate::find($user->def_corporate_id);
                break;

            default:
                $company = Hotel::find($user->def_hotel_id);
                break;
        }

        

        return view('learning.listcompetency.index', compact('cert_comp_num','user', 'user_courses', 'progress', 'complete', 'company'));
    }

Blade View

@forelse($user_courses as $item) 
                    @if ($item->course_provider == 'External')
                    @foreach ($progress as $items)
                    @if($items->course_id == $item->course_id)
                    @if ($item->total_duration != 0)
                    @if (round(($items->progress/$item->total_duration)*100) >= 100)
                    <li class="list-group-item">
                        <div class="row mycourse-list">
                            <div class="col-2">
                                <img src="" class="img-cover-list">
                                <div class="course-lang type-paragraph2" >
                                    @if($item->course_lang == 1)
                                    <img class="rounded-circle" src="" alt="ID">
                                    @else
                                    <img class="rounded-circle" src="" alt="ENG">
                                    @endif
                                </div>
                                <div class="course-status type-paragraph2 published">FREE</div>
                            </div>
                            <div class="col-6 course-list">
                                <div class="course-detail type-paragraph5">
                                    <div class="course-type">
                                        AJAR <span class="course-mode">&#8226 </span>
                                    </div>
                                    <div class="learner-course-info" style="margin-top: 0px;">
                                        
                                    </div>
                                    <div class="type-paragraph3" style="color: #7cdb4a;">
                                        Completion Date : 
                                    </div>
                                </div>
                            </div>
                            <div class="col-2 course-list">
                                "
                                    data-id=""
                                    data-coursename=""
                                    data-date=""
                                    class="btn btn-secondary-outline certificate">
                                Certificate
                                </a> --}}
                                <div class="dropdown">
                                    <button class="btn btn-secondary-outline dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    Certificate
                                    </button>
                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                        <a href="#" data-toggle="modal" data-target=".completion-cert-modal-"
                                            data-id=""
                                            data-coursename=""
                                            data-date=""
                                            class="dropdown-item certificate">
                                        Certificate of Completion
                                        </a>
                                        @if ($item->course->passing_grade != 'N/A' && $item->course->score >= $item->course->passing_grade) 
                                        <a href="#" data-toggle="modal" data-target=".attainment-cert-modal-"
                                            data-id=""
                                            data-coursename=""
                                            data-date=""
                                            class="dropdown-item certificate-attainment">
                                        Certificate of Attainment
                                        </a>
                                        @endif
                                    </div>
                                    
                                    <div class="modal fade completion-cert-modal-" tabindex="-1" role="dialog" aria-labelledby="completionCertModalLabel" aria-hidden="true">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLongTitle">Certificate of Completion</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body">
                                                    <div class="embed-responsive embed-responsive-16by9">
                                                        <iframe class="cert-preview embed-responsive-item" src=""></iframe>
                                                    </div>
                                                    <label class="pt-4">CERT ID:</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="cert_id_" placeholder="your CERT ID" aria-label="your CERT ID" aria-describedby="basic-addon2" value="" readonly style="background: #fff" onclick="javascript:$(this).select()">
                                                        <div class="input-group-append">
                                                            <button class="btn btn-outline-secondary copy-text" style="border-radius: 0 .25rem .25rem 0; padding: 5px 10px !important;" type="button" onclick="copyText('cert_id_')"> Copy! </button>
                                                        </div>
                                                    </div>
                                                    <label class="pt-2">Validation URL:</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="cert_url_" placeholder="your CERT ID" aria-label="your CERT ID" aria-describedby="basic-addon2" value="" readonly style="background: #fff" onclick="javascript:$(this).select()">
                                                        <div class="input-group-append">
                                                            <button class="btn btn-outline-secondary copy-text" style="border-radius: 0 .25rem .25rem 0; padding: 5px 10px !important;" type="button" onclick="copyText('cert_url_')"> Copy! </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                    <a href="" class="btn btn-primary" target="_blank">Download</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    @if ($item->course->passing_grade != 'N/A' && $item->course->score >= $item->course->passing_grade) 
                                    <!-- Modal Preview Certificate of Attainment -->
                                    <div class="modal fade attainment-cert-modal-" tabindex="-1" role="dialog" aria-labelledby="attainmentCertModalLabel" aria-hidden="true">
                                        <div class="modal-dialog modal-lg">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="exampleModalLongTitle">Certificate of Attainment</h5>
                                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                    <span aria-hidden="true">&times;</span>
                                                    </button>
                                                </div>
                                                <div class="modal-body text-left">
                                                    <div class="embed-responsive embed-responsive-16by9">
                                                        <iframe class="cert-preview embed-responsive-item" src=""></iframe>
                                                    </div>
                                                    <label class="pt-4">CERT ID:</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="cert_id_" placeholder="your CERT ID" aria-label="your CERT ID" aria-describedby="basic-addon2" value="" readonly style="background: #fff" onclick="javascript:$(this).select()">
                                                        <div class="input-group-append">
                                                            <button class="btn btn-outline-secondary copy-text" style="border-radius: 0 .25rem .25rem 0; padding: 5px 10px !important;" type="button" onclick="copyText('cert_id_')"> Copy! </button>
                                                        </div>
                                                    </div>
                                                    <label class="pt-2">Validation URL:</label>
                                                    <div class="input-group">
                                                        <input type="text" class="form-control" id="cert_url_" placeholder="your CERT ID" aria-label="your CERT ID" aria-describedby="basic-addon2" value="" readonly style="background: #fff" onclick="javascript:$(this).select()">
                                                        <div class="input-group-append">
                                                            <button class="btn btn-outline-secondary copy-text" style="border-radius: 0 .25rem .25rem 0; padding: 5px 10px !important;" type="button" onclick="copyText('cert_url_')"> Copy! </button>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                                    <a href="" class="btn btn-primary" target="_blank">Download</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <!-- End Modal Preview Certificate of Attainment -->
                                    @endif
                                </div>
                            </div>
                            <div class="col-2 course-list">
                                <a href=""
                                    class="btn btn-secondary-outline">See Detail</a>
                            </div>
                        </div>
                    </li>
                    @php $completed++; @endphp
                    @endif
                    @endif
                    @endif
                    @endforeach
                    @else
                    <div class="empty-internal-course">
                        <img src="" class="img-responsive" 
                            style="padding:20px;" alt="Empty learning passport">
                        <div class="data-empty">
                            You haven’t completed any courses this time.
                        </div>
                    </div>
                    @break
                    @endif
                    @empty
                    <div class="empty-internal-course">
                        <img src="" class="img-responsive" 
                            style="padding:20px;" alt="Empty learning passport">
                        <div class="data-empty">
                            You haven’t completed any courses this time.
                        </div>
                    </div>
                    @endforelse

FYI. There should be more than one course data displayed and click download certificate.

How to fix it? Thank you 🙏



via Chebli Mohamed

Ajax Post request refresh page after success

I built a small chat app using Laravel. Messages are sent and received perfectly.

I have made 2 functions for chat. One is to fetch chat (update the chat div) and the other saves chat when the 'send' button is clicked. The first function will be called when you load the page and send the message.

The problem occurs when I am calling the saveChat function; it refreshes the page after I click the send button.

my view >> chat will append in chat-data div and a input and a button is added to write and send meessage

Load the chat

save chatcontroller function to save chat



via Chebli Mohamed

laravel-snappy error when creating pdf file ContentOperationNotPermittedError

I'm using Laravel 5.7 and each time I try to generate a pdf file using laravel-snappy package I get this error message: Exit with code 1 due to network error: ContentOperationNotPermittedError

My OS is Windows 10.

On other SO questions and github's issues it's pointed out that this issue may be caused by relative paths on css files but on my blade.php tamplate I do not have any external source, all the css code is written inline.

This is the fullstack trace:

The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[>                                                           ] 0%[======>                                                     ] 10%QNetworkAccessFileBackendFactory: URL has no schema set, use file:// for files ◀
[==========>                                                 ] 18%\rWarning: Failed to load c:/Program Files (x86)/EasyPHP-Devserver-17/eds-www/gestion/public/s ▶
Error: Failed to load c:/Program Files (x86)/EasyPHP-Devserver-17/eds-www/gestion/public, with network status code 202 and http status code 0 - Cannot open c:/P ▶
[============================================================] 100%Counting pages (2/6)                                               
[============================================================] Object 1 of 1Resolving links (4/6)                                                       
[============================================================] Object 1 of 1Loading headers and footers (5/6)                                           
Printing pages (6/6)
[>                                                           ] Preparing[============================================================] Page 1 of 1Done                                                                       ◀
Exit with code 1 due to network error: ContentOperationNotPermittedError
"
stdout: ""
command: "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" --lowquality --orientation "landscape" --page-size "a4" --encoding "UTF-8" --enable-local-file-access "C:\Users\USER\AppData\Local\Temp\knp_snappy61279300ad2dd5.53480707.html" "C:\Users\USER\AppData\Local\Temp\knp_snappy61279300ad71c6.09845744.pdf". ◀
"""


via Chebli Mohamed

Query with empty results laravel eloquent

I´m traying to create statistics from my database. I´m changing application and before statistics was created from call table. But i change this and i was created a new table statistics and have this column:

id, id_ployed, call_id, created_at(nullable), updated_at(nullable)

and data example for example:

52,60,88988,4
53,60,88989,10
54,60,88990,6
62,9,88999,1

i have this function in my controller, but return empty data and it´s imposible:

$estadosLlamadas = EstadoLlamada::orderBy('desc')->get();

        if(isset($request->fromDate) && isset($request->toDate)){
            $fromDate = Carbon::parse($request->get('fromDate'));
            $toDate = Carbon::parse($request->get('toDate'));

            $fromDate = $fromDate->format('Y-m-d');
            $toDate = $toDate->format('Y-m-d');

        }else{
            $fromDate = new Carbon('first day of this month');
            $toDate = new Carbon('last day of this month');

            $fromDate = $fromDate->format('Y-m-d');
            $toDate = $toDate->format('Y-m-d');
        }

        $teleoperadoras = auth()->user()->whereIs('teleoperadora')->activos()->select(['id', 'nombre'])->orderBy('nombre', 'desc')->get();
        
        $array = [
            'toDate'   => $toDate,
            'fromDate' => $fromDate,
            'nombresEstados' => $estadosLlamadas->pluck('desc')->toArray(),
            'coloresEstados' => $estadosLlamadas->pluck('hex')->toArray()
        ];

        $query = Estadisticas::query()
            ->whereDate('estadisticas.created_at', '<=', $toDate)
            ->whereDate('estadisticas.created_at', '>=', $fromDate)
            ->whereIn('estadisticas.id_empleado', $teleoperadoras->pluck('id'))
            ->join('users', 'estadisticas.id_empleado', '=', 'users.id')->latest('estadisticas.updated_at')->get();


        foreach($teleoperadoras as $teleoperadora) {
            $array['teleoperadoras'][] = $teleoperadora->nombre;
            $array['id_teleoperadoras'][] = $teleoperadora->id;
            $array[$teleoperadora->id]['resultados'] = [];
            $array['llamadas'][] = $query->where('id_empleado', $teleoperadora->id)->count();

            $array['llamadasTodo'][$teleoperadora->id] = $query->where('id_empleado', $teleoperadora->id);

            foreach($estadosLlamadas as $estado) {
                $array[$teleoperadora->id]['resultados'][] = $query->where('id_empleado', $teleoperadora->id)
                                                            ->where('id_estado', $estado->id)->count();
            }
        }

        $array['nllamadas'] = $query->count();
        $array['fromDate'] = $fromDate . " 00:00:00";
        $array['toDate'] = $toDate . " 23:59:59";
        $roleUser = auth()->user()->getRoles()->first();

        return [
            'datos' => $array, 'estados' => $estadosLlamadas,
            'teleoperadoras' => $teleoperadoras, 'roleUser' => $roleUser,
        ];

this fill statics with chartJS:

$.ajax({
            type: 'GET',
            url: "",
            data: { 'fromDate': fromDate, 'toDate': toDate },
            success: function(response){
                console.log(response);

                $("#loadMe").modal('hide');

                var totalCall = 0;
                let totalCallByOperator = response["datos"]["llamadas"];

                $("#totalCall").append(response.datos.nllamadas)

                // append all teleoperator in view with calls number
                response["datos"]["teleoperadoras"].forEach(function(teleoperadora, index) {
                    $("#teleoperadoras").append('<b class="teleoperadora">'+teleoperadora + ": " + totalCallByOperator[index] +'</b> <br>');
                });

                // generate general statistics
                var ctx = document.getElementById('canvas1').getContext('2d');

                var myChart = new Chart(ctx, {
                    type: 'bar',
                
                    data: {
                        labels: response["datos"]["teleoperadoras"],
                        datasets: [{
                            label: 'Total de llamadas por operadora',
                            data: totalCallByOperator,
                            backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(255, 159, 64, 0.2)',
                            'rgba(255, 205, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(201, 203, 207, 0.2)'
                            ],
                            borderColor: [
                            'rgb(255, 99, 132)',
                            'rgb(255, 159, 64)',
                            'rgb(255, 205, 86)',
                            'rgb(75, 192, 192)',
                            'rgb(54, 162, 235)',
                            'rgb(153, 102, 255)',
                            'rgb(201, 203, 207)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }// end options

                }); // end chart object
            },
            error: function(xhr){
                alert(xhr.responseText);
            }
        });

and response from my controller its:

{datos: {9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]},…}, estados: [,…],…}
datos: {9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]},…}
9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
11: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
22: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
23: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
24: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
25: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
26: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
49: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
50: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
60: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
coloresEstados: ["#d26a5c", "#f3b760", "#46c37b", "#343a40", "#6c757d", "#d26a5c", "#d26a5c", "#5c80d1", "#70b9eb",…]
fromDate: "2021-08-01 00:00:00"
id_teleoperadoras: [9, 23, 24, 60, 22, 49, 11, 50, 25, 26]
llamadas: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
llamadasTodo: {9: [], 11: [], 22: [], 23: [], 24: [], 25: [], 26: [], 49: [], 50: [], 60: []}
nllamadas: 682
nombresEstados: ["ANULADA", "AUSENTE", "CONFIRMADA", "CONFIRMADA/ANULADA", "CONFIRMADA/AUSENTE", "ERRONEO NO EXISTE",…]
teleoperadoras: ["ARANZAZU SOLIS SANCHEZ", "CRISTINA LOPEZ UBRIC", "CRISTINA MORALES FERNANDEZ",…]
toDate: "2021-08-31 23:59:59"
estados: [,…]
roleUser: "admin"
teleoperadoras: [{id: 9, nombre: "ARANZAZU SOLIS SANCHEZ"}, {id: 23, nombre: "CRISTINA LOPEZ UBRIC"},…]

array "resultados" it´s where should be data to my statistics. This function it was ok before, but now not work.

My model its:

class Estadisticas extends Model
{
    protected $table = 'estadisticas';

    protected $primarykey = 'id';

    public $timestamps = false;

    protected $fillable = [
        'id_empleado', 'id_llamada', 'id_estado', 'created_at', 'updated_at'
    ];


    public function teleoperadora()
    {
        return $this->hasOne('App\User', 'id', 'id_empleado')->withDefault();
    }

    public function estado()
    {
        return $this->hasOne('App\EstadoLlamada', 'id', 'id_estado');
    }   
}

i hope that anybody can help me. thanks for read and sorry for my english



via Chebli Mohamed

Collapse sidebar when in certain pages (PHP) [duplicate]

Hope you are all doing well.

I'm working on a Codeigniter project for example I want when the user enters this page :

http://localhost:8080/admin/clients

I want the sidebar to stay shown but once he enters a sub-page like

http://localhost:8080/admin/clients/add 

I want the sidebar to be Hidden

Here's my code :

if($actual_link == admin_url().'/clients/**'){ ?>
    <body class="hide-sidebar">
<?php } else { ?>
    <body>
<?php } ?>

I tried this Code but it didn't work .



via Chebli Mohamed

laravel can't start first project [closed]

After downloading the latest php and installing composer. then installed laravel using the command composer global require laravel/installer

    Changed current directory to C:/Users/User/AppData/Roaming/Composer
Using version ^4.2 for laravel/installer
./composer.json has been created
Running composer update laravel/installer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 13 installs, 0 updates, 0 removals
  - Locking laravel/installer (v4.2.8)
  - Locking psr/container (1.1.1)
  - Locking symfony/console (v5.3.6)
  - Locking symfony/deprecation-contracts (v2.4.0)
  - Locking symfony/polyfill-ctype (v1.23.0)
  - Locking symfony/polyfill-intl-grapheme (v1.23.1)
  - Locking symfony/polyfill-intl-normalizer (v1.23.0)
  - Locking symfony/polyfill-mbstring (v1.23.1)
  - Locking symfony/polyfill-php73 (v1.23.0)
  - Locking symfony/polyfill-php80 (v1.23.1)
  - Locking symfony/process (v5.3.4)
  - Locking symfony/service-contracts (v2.4.0)
  - Locking symfony/string (v5.3.3)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 13 installs, 0 updates, 0 removals
    0 [>---------------------------]    0 [>---------------------------]
  - Installing symfony/polyfill-php80 (v1.23.1): Extracting archive
  - Installing symfony/process (v5.3.4): Extracting archive
  - Installing symfony/polyfill-mbstring (v1.23.1): Extracting archive
  - Installing symfony/polyfill-intl-normalizer (v1.23.0): Extracting archive
  - Installing symfony/polyfill-intl-grapheme (v1.23.1): Extracting archive
  - Installing symfony/polyfill-ctype (v1.23.0): Extracting archive
  - Installing symfony/string (v5.3.3): Extracting archive
  - Installing psr/container (1.1.1): Extracting archive
  - Installing symfony/service-contracts (v2.4.0): Extracting archive
  - Installing symfony/polyfill-php73 (v1.23.0): Extracting archive
  - Installing symfony/deprecation-contracts (v2.4.0): Extracting archive
  - Installing symfony/console (v5.3.6): Extracting archive
  - Installing laravel/installer (v4.2.8): Extracting archive
  0/13 [>---------------------------]   0%
 10/13 [=====================>------]  76%
 12/13 [=========================>--]  92%
 13/13 [============================] 100%
6 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
11 packages you are using are looking for funding.
Use the `composer fund` command to find out more!`

After installation created a project laravel new example-app

 Creating a "laravel/laravel" project at "./example-app"
    Installing laravel/laravel (v8.6.1)
  - Installing laravel/laravel (v8.6.1): Extracting archive
    Created project in C:\test/example-app
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
    Loading composer repositories with package information
    Updating dependencies
    Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework[v8.54.0, ..., 8.x-dev] require league/flysystem ^1.1 -> satisfiable by league/flysystem[1.1.0, ..., 1.x-dev].
    - league/flysystem[1.1.0, ..., 1.x-dev] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension.
    - Root composer.json requires laravel/framework ^8.54 -> satisfiable by laravel/framework[v8.54.0, v8.55.0, v8.56.0, 8.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
    - C:\php7\php.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Then I performed cd example-app и php artisan serve. После выполнения php artisan serve gives an error message :

PHP Warning:  require(C:\test\example-app/vendor/autoload.php): Failed to open stream: No such file or directory in C:\test\example-app\artisan on line 18
PHP Fatal error:  Uncaught Error: Failed opening required 'C:\test\example-app/vendor/autoload.php' (include_path='.;C:\php\pear') in C:\test\example-app\artisan:18
Stack trace:
#0 {main}
  thrown in C:\test\example-app\artisan on line 18

After walking through the forums, I realized that there was not enough folder vendor in project Project with files

After adding the vendor folder to the project using the command composer dump-autoload.The folder was added but after running the command composer dump-autoload a new error popped up :

Generating optimized autoload files
Class Illuminate\Foundation\ComposerScripts is not autoloadable, can not call post-autoload-dump script
> @php artisan package:discover --ansi
PHP Fatal error:  Uncaught Error: Class "Illuminate\Foundation\Application" not found in C:\test\example-app\bootstrap\app.php:14
Stack trace:
#0 C:\test\example-app\artisan(20): require_once()
#1 {main}
  thrown in C:\test\example-app\bootstrap\app.php on line 14
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255

Then I tried to execute the command php artisan serve .Throws this error :

PHP Fatal error:  Uncaught Error: Class "Illuminate\Foundation\Application" not found in C:\test\example-app\bootstrap\app.php:14
Stack trace:
#0 C:\test\example-app\artisan(20): require_once()
#1 {main}
  thrown in C:\test\example-app\bootstrap\app.php on line 14

Then, walking around the forums, I just did not run to fix this problem I tried: Composer update, Composer install, composer update --no-scripts

composer dump-autoload
composer install --no-scripts

I also tried this :

php artisan clear-compiled
composer dump-autoload

And tried to delete the vendor folder.

And so I tried it, though it says that there is no such file:

composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload

Nothing helped . I do not know what to do. And how to solve this problem.



via Chebli Mohamed

mercredi 25 août 2021

problem with id does not show the correct and repeats

i have a problem with my online shift application

https://i.imgur.com/d1O5Eao.png

the user can view their shift requests. The problem is that clicking view (...) always redirects to shift ID 93 in the two registers

https://i.imgur.com/33hRcLa.png

Controller:

    public function inicio(){
    
        if (Auth::guest()) {
          return redirect()->route("login");
        }
    
        $config = Configuraciones::findOrFail(0);
       
       // Solicitudes = REQUEST 

        $solicitudes = Solicitudes::where('user_id', Auth::User()->id)->orderByDesc('created_at')->take(5)->get();

 GET THE ID OF THE REQUEST FROM THE LOGED USER
        $solicitud = Solicitudes::where('user_id', Auth::User()->id)->first();
    


// GET THE SHIFT 'id' RELATED TO THE 'id' OF THE request
        $eventos = Eventos::where('solicitud_id', $solicitud->id)->first();
       
       
        return view('solicitudes.inicio',compact('solicitudes','config','eventos'))->with($data);
       }

Blade: `

@foreach($solicitudes as $solicitud)
                                        @if(Auth::user()->id == $solicitud->user_id)
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td class="text-center">
                                                @if($solicitud->estado == '0')
                                                <span class="badge badge-primary">Pendiente</span>
                                                @elseif($solicitud->estado == '1')
                                                <span class="badge badge-success">Aceptada</span>
                                                @elseif($solicitud->estado == '2')
                                                <span class="badge badge-danger">Rechazada</span>
                                                @endif
                                            </td>
                                            <td class="text-center">
                                                
                                                <div class="dropdown custom-dropdown">
                                                    <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
                                                    </a>

                                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                        <a class="dropdown-item" href="/turno/">Ver</a>
                                                      
                                                    </div>
                                                </div>

                                            </td>
                                        </tr>
                                        @endif
                                        @endforeach`

Try using: $eventos = Eventos::where('solicitud_id', $solicitud->id)->get();

but it give error: Property [id] does not exist on this collection instance.

What can i do to get the correct shift ID? and that the same thing is not always repeated



via Chebli Mohamed

Laravel Save A Generated Pdf Inside A Queue

I have a blade where i converts Html to a pdf and save it on my local , then i am using a live url to get a pdf and save it on my local Then I am using a laravel library to merge both pdf's and it will generate a single pdf by embeding, It was working fine earlier, now I have a high-quality pdf where it takes much time to merge, due to it, it is takeing mome time and it returns a max limit memory issue,

so i tried to do it on Queue

this is my code

 $ecg_link = 'https://storage.googleapis.com/staging.uk-production.appspot.com/test1111.pdf';
    
 $ecg_pdf = isset($ecg_link) ?  $ecg_link : '';

 if($ecg_pdf){
        $ecg_contents = file_get_contents($ecg_link);
    
        if (!File::exists(storage_path('app/public/screening/pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf'), 0777, true, true);
        }

        \Storage::disk('public')->put('screening/pdf/'.$screening_id.'.pdf', $ecg_contents);
      
        $pdf = PDF::loadView('participants.test', 
         compact('participantdata','Allopurinol','stn_assetreview'));

        if (!File::exists(storage_path('app/public/screening/pdf/temporary-pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf/temporary-pdf'), 0777, 
        true, true);
        }
        $pdf->save(storage_path('app/public/screening/pdf/temporary-pdf/'.$screening_id.'.pdf'));

        $pdfMerger = PDFMerger::init(); //Initialize the merger
        $pdfMerger->addPDF(storage_path('app/public/screening/pdf/temporary-pdf/'.$screening_id.'.pdf'), 'all');
        $pdfMerger->addPDF(storage_path('app/public/screening/pdf/'.$screening_id.'.pdf'), 'all' );
       

        $pdfMerger->merge();

        if (!File::exists(storage_path('app/public/screening/pdf/final-pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf/final-pdf'), 0777, true, true);
        }
        $pdfMerger->save($screening_id.'.pdf', "download");

when i use queue , i am unable to download the excel since its in queue , I sthere any way i can download the excel , else can i send this pdf over a mail ???

thank you



via Chebli Mohamed

how to get users group by roles in laravel query builder

I have three tables 1 users table, 2 roles table and 3 role_users table as pivot table. Each user may have multiple roles such as editor and publisher at the same time maybe

Tables Structure

  1. Users                  id name email
  2. Roles                  id name
  3. Role_users          id role_id user_id

first user has 2 different roles editor & publisher with my query it's repeating the user with new role every time. How can I group them as array of roles in result

Query

        $query = DB::table('users')
       ->select(
        'users.name As name',
        'users.email As email',
        'users.status As status',
        'roles.name As role'
        );

    $query->leftjoin('role_users', 'users.id', '=', 'role_users.user_id');
    $query->leftjoin('roles', 'role_users.role_id', '=', 'roles.id');
    $query->groupBy('roles.name');
    $result = $query->get();

    dd($result->toArray());

Result Required

    "name": "Billyshawn"
    "email": "billy@shawn.com"
    "role": ["editor","publisher"]


via Chebli Mohamed

Cache Management Ubuntu 18.04 LTS

I have a Laravel 5.6 (including NodeJS) application hosted on AWS cloud (Ubuntu 18 LTS) with available RAM of upto 4GB.

But I am observing the available amount of RAM decreasing due to some unknown reasons to me.

I saw the output of free -m command via terminal and the results show more than 1GB of cached data.

Could you guys illuminate me more into that as to why cache is increasing.

Can I browse to that folder if cache is being stored temporarily.

Thank You in anticipation.



via Chebli Mohamed

mardi 24 août 2021

Load model one to many relation eloquent way without primary key but on multiple overlapping fields

I'm working on an older project that I've been tasked to speed up certain parts of while we work on a complete re-write since the code is just badly maintained, poorly written and outdated for what it's suppose to do.

I stumbled into an issue to the core of the project and because of this I can't change it without breaking almost everything else. So I need to load a "relation" the eloquent way () but there isn't a real foreign ID, it rather laps with multiple fields.

Would there be a way to load it all in one query with the overlapping fields rather than have it load separately creating an n+1 problem?

+--------------+-----------------+
| Planning     | Availability    |
+--------------+-----------------+
| planning_id  | availability_id |
| date         | date            |
| startHour    | startHour       |
| stopHour     | stopHour        |
| candidate_id | candidate_id    |
| section_id   | section_id      |
+--------------+-----------------+

From the above example you can see the overlapping fields are date, startHour, stopHour, candidate_id and section_id.

I tried get...attribute but that still loads with n+1, I tried including it with ->with(['availabilities']) but that doesn't work since I ask for the model and not the relation:

return Availability::where('section_id', $this->section_id)
    ->where('candidate_id', $this->candidate_id)
    ->where('planningDate', $this->planningDate)
    ->where('startHour', $this->startHour)
    ->where('stopHour', $this->stopHour)
    ->get();


via Chebli Mohamed

lundi 23 août 2021

Laravel - Displaying json from database to view

I have a column in my database that stores json data as ["Item_1", "Item_2", "Item_3"]. It has a field - ammenities.

I would like to display the json data to my blade view?

The model:

class Property extends Model
{
   protected $casts = [
      'ammenities' => 'array',
   ];
 public function setAmmenityAttribute($value)

 {

    $this->attributes['ammenities'] = json_encode($value);

 }


  public function getAmmenityAttribute($value)

 {

    return $this->attributes['ammenities'] = json_decode($value);

 }
 }

View blade:

 <p> </p>

I get this error:

htmlspecialchars() expects parameter 1 to be string, array given


via Chebli Mohamed

How to use a clear button to clear notification screen in laravel

How to clear pop scroll bar notification using single clear button in laravel 5.5 Notification using jquery and ajax database I have crm project so i got notification like Advance slaray request approved
Live request approved. I want a clear button to clear notifiaction bar



via Chebli Mohamed

Laravel composer error -> root composer.json requires adldap2/adldap2-laravel ^6.0

I remove php 8 and I download php 7 after that I try composer update command. But when I run composer update command I have an error.

Your requirements could not be resolved to an installable set of packages.

Problem 1 - adldap2/adldap2-laravel[v6.0.8, ..., v6.1.5] require adldap2/adldap2 ^10.1 -> satisfiable by adldap2/adldap2[v10.1.0, ..., v10.3.3]. - adldap2/adldap2-laravel[v6.0.0, ..., v6.0.7] require adldap2/adldap2 ^10.0 -> satisfiable by adldap2/adldap2[v10.0.0, ..., v10.3.3]. - adldap2/adldap2[v10.0.0, ..., v10.3.3] require ext-ldap * -> it is missing from your system. Install or enable PHP's ldap extension. - Root composer.json requires adldap2/adldap2-laravel ^6.0 -> satisfiable by adldap2/adldap2-laravel[v6.0.0, ..., v6.1.5].

To enable extensions, verify that they are enabled in your .ini files: - C:\xampp\php\php.ini You can also run php --ini inside terminal to see which files are used by PHP in CLI mode.

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.



via Chebli Mohamed

how to search a file by using file name in google drive using laravel plugin nao-pon/flysystem-google-drive

I'm able to find the file name by using the file id but i need to get the file object data by using the file name in the google drive folder

Code here



via Chebli Mohamed

Google Drive : File Uploading and Accessing the files

Can anyone help me the google drive [long term validity] refresh token,

  1. Refresh token getting expired every week, we wanted to fix and the refresh token permanently.
  2. Google project status is internal,application status
  3. using Laravel package : nao-pon/flysystem-google-drive
  4. Using Laravel Application.

Please Help me through this, Thanks in Advance.



via Chebli Mohamed

dimanche 22 août 2021

Trying to get property 'id_pembelian' of non-object

I want to retrieve data from the database without using foreach, in some articles I read just use first() to get the value from the database, but when I try I always get an error like the following: ErrorException Trying to get property 'id_belian' of non-object

can anyone help me?

this is my controller code :

 /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $isValid = $request->validate([
            'total_bayar' => 'required|integer'
        ]);


        // megambil total yang sudah di bayar
        $terbayar = Pembayaran::select('total_bayar')->where('id',$id)->first();

        // mengambil id pembelian dari tabel pembayaran
        $id_data_bayar = Pembayaran::select('id_pembelian')->where('id',$id)->first();

        // ambil data jumlah yang harus di bayar dari tabel pembelian
        $harga_bayar = Pembelian::select('total_harga')->where('id',$id_data_bayar->id_pembelian)->first();

        $total_akan_terbayar = $terbayar->total_bayar + $request->get('total_bayar');  

        if($isValid){
            if(($harga_bayar->total_harga != $terbayar->total_bayar) && ($harga_bayar->total_harga > $total_akan_terbayar)){
                $data = [
                    'total_bayar'=> $request->get('total_bayar'),
                    'updated_at' => Carbon::now(),
                    'status' => 'cicil'
                ];
                $isSaved = Pembayaran::where('id',$id)->update($data);
                if($isSaved){
                    return Redirect::to('/pembayaran/'.$id.'/edit')->with('warning','Transaksi Anda Sebesar Rp.'.$total_akan_terbayar.' Berhasil dicatat');
                }else{
                    return Redirect::to('/pembayaran/'.$id.'/edit')->with('error','Transaksi Anda Gagal dicatat');
                }
            } elseif(($harga_bayar->total_harga != $terbayar->total_bayar) && ($harga_bayar->total_harga == $total_akan_terbayar)) {
                $data = [
                    'total_bayar'=> $request->get('total_bayar'),
                    'updated_at' => Carbon::now(),
                    'status' => 'lunas'
                ];
                $isSaved = Pembayaran::where('id',$id)->update($data);
                if($isSaved){
                    return Redirect::to('/pembayaran/'.$id.'/edit')->with('warning','Transaksi Anda Sebesar Rp.'.$total_akan_terbayar.' Berhasil dicatat');
                }else{
                    return Redirect::to('/pembayaran/'.$id.'/edit')->with('error','Transaksi Anda Gagal dicatat');
                }
            } elseif(($harga_bayar->total_harga != $terbayar->total_bayar) && ($harga_bayar->total_harga < $total_akan_terbayar)) {
                return Redirect::to('/pembayaran/'.$id.'/edit')->with('warning','Jumlah yang anda masukan berlebih Rp.'.($total_akan_terbayar-$harga_bayar->total_harga));
            } else {
                return Redirect::to('/pembayaran/'.$id.'/edit')->with('error','Transaksi Anda Gagal dicatat');
            }
        }else{
            return Redirect::to('/pembayaran/'.$id.'/edit')->with('error','Transaksi Anda Gagal dicatat');
        }
    }


via Chebli Mohamed

i Faced this problem when i configure Firebase?

step 1: This is my controller code. firebase file and firebase DB are connected properly. but when run in postman i got 500 error but I am new on firebase show I don't know how can I resolved this

 public function ride_confirm(Request $request)
{
    $input = $request->all();
    $validator = Validator::make($input, [
        'km' => 'required',
        'vehicle_type' => 'required',
        'customer_id' => 'required',
        'promo' => 'required',
        'country_id' => 'required',
        'pickup_address' => 'required',
        'pickup_date' => 'required',
        'pickup_lat' => 'required',
        'pickup_lng' => 'required',
        'trip_type' => 'required'
    ]);
    if ($validator->fails()) {
        return $this->sendError($validator->errors());
    }
    
    $input['pickup_date'] = date("Y-m-d H:i:s", strtotime($input['pickup_date']));
    $current_date = $this->get_date($input['country_id']);
    $interval_time = $this->date_difference($input['pickup_date'],$current_date);
    if($interval_time <= 30){
        $input['booking_type'] = 1;
        $input['status'] = 1;
    }else{
        $input['booking_type'] = 2;
        $input['status'] = 2;
    }
    $factory = (new Factory)->withServiceAccount(config_path().'/'.env('FIREBASE_FILE'));
    $factory = (new Factory())->withDatabaseUri(env('FIREBASE_DB'));
    
    $database = $factory->createDatabase();
    
    $drivers = $database->getReference('/vehicles/'.$input['vehicle_type'])
                 ->getSnapshot()->getValue();
}

I faced this error when I run this code ... enter image description here



via Chebli Mohamed

Does Django need more resources of a server than Laravel? If the both are the same kind of application

Suppose I want to build a social Media Platform Website and App with API.

Then which will be less resource-hungry between Django and Laravel ?

Which framework can perform faster for the application in a same config server? and why ?

Thanks in Advance



via Chebli Mohamed

samedi 21 août 2021

add space after the third number except the last four numbers

I'm new to Laravel, and I've a small issue which is that i have column in DB that should store 13 numbers in specific form. The form is to add space after each 3 numbers except the last four numbers.

For Example: 1234567891234 it should stored in the following format: 123 456 789 1234

Thanks



via Chebli Mohamed

How to post lots of data to laravel database

please i am trying to submit this date to a database in laravel...i want to submit all same time, this is just two rows but i want even if it gets to 10 rows i can submit.

0: {item: "Electronics", subitem: "Laptop", subitem2: "Hard D", unit: "Length - meter (m)"}
1: {item: "Electronics", subitem: "Laptop", subitem2: "Hard D", unit: "Length - meter (m)"}

What i have tried

 for ($i = 1; $i < count($request->item); $i++) {
          
        }

I tried to do a for loop using the above code but its not working..got the below error

count(): Parameter must be an array or an object that implements Countable



via Chebli Mohamed

http://localhost:4200 has been blocked by CORS policy: Response to preflight request doesn't pass access control check

I have a laravel and angular app when i run angular app i'm getting following error:

Access to XMLHttpRequest at 'http://localhost/project/public/api/register' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already have CORS middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class CORS
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');
        $response->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Auth-Token,Origin,Authorization,Accept');
        //Access-Control-Allow-Credentials true or false
        return $response;
    }
}

Kernel:

 protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\CORS::class
    ];


via Chebli Mohamed

Call to undefined relationship [relation] on model [App/Model]

Environment:

  • Laravel Version: 5.7.29
  • PHP Version $ php --version: PHP 7.2.24 (cli)
  • Database Driver & Version $ mysql --version: mysql Ver 8.0.23-0ubuntu0.20.04.1
  • Doctrine/Inflector: 1.4.4

composer.json

    "require": {
        "php": ">=7.2.24",
        "fideloper/proxy": "~4.0",
        "laravel/framework": "5.7.*",
        "laravel/tinker": "~1.0",
        "doctrine/inflector": "1.4.4"
    },

Problem Statement:

Below relation is working on localhost but throwing error on Server. This seems like issue is with Doctrine/Inflector package.

$ php artisan tinker
>>> $borrower = Borrower::with('application')->find(2);

PHP Deprecated:  The "Doctrine/Common/Inflector/Inflector::pluralize" method is deprecated and will be dropped in doctrine/inflector 2.0. Please update to the new Inflector API. in /path/vendor/doctrine/inflector/lib/Doctrine/Common/Inflector/Inflector.php on line 264
Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [application] on model [App/Borrower].'

Models

App\Borrower.php

<?php  

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Borrower extends Authenticatable
{

    protected $table = 'borrowers';

    public function application()
    {
        return $this->hasMany('App\Models\Application', 'borrower_id', 'borrower_id');
    }

App\Models\Application.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Application extends Model
{
    
    protected $table = 'applications';

    public function borrower()
    {
        return $this->belongsTo('App\Borrower', 'borrower_id', 'borrower_id');
    }

Table


borrowers

| borrower_id | fname  | email                  |
|-------------|--------|------------------------|
| 1           | John   | john@peakyblinder.com  |
| 2           | Thomas | tommy@peakyblinder.com |

applications

| id | name       | borrower_id |
|----|------------|-------------|
| 1  | Birmingham | 1           |
| 2  | BBC        | 1           |



via Chebli Mohamed

vendredi 20 août 2021

Error trying to get property 'users' of non-object

I have a problem, i am doing a shift history of the user logged in the application.

   @foreach($eventos as $evento)
                        if($evento->solicitud->users->id == (Auth::user()->id))
                            <div class="item-timeline">
                                <div class="t-meta-date">
                                    <p class=""></p>
                                </div>
                                <div class="t-dot">
                                </div>
                                <div class="t-text">
                                    <p></p>
                                    <p></p>
                                </div>
                            </div>
                     @endif
                        @endforeach

I get all shifts with:

 $eventos = Eventos::All();

and then filter with if condition

But it shows me error Trying to get property 'users' of non-object

dd capture: https://i.imgur.com/WUVOaO6.png

data base: https://i.imgur.com/J5YSvxQ.png

i need to get the User_id from the solicitudes table.

the relation is: Eventos table-> solicitud_id with the ID column of the Solicitudes table



via Chebli Mohamed

Laravel upgrade form 5.5 to 5.6

I am trying to upgrade laravel application from 5.5 to 5.6 in the documentation, regarding database modification, in Index Order Of Morph Columns section, it was mentioned that

If the application is in production, you should pass an explicit index name to the morphs method.

What kind of modification should I do there?

Thanks!



via Chebli Mohamed

open PDF in modal with laravel and HTTPS subdomain

I´m traying to open pdf file in modal with laravel, but always return this:

Sorry, the page you are looking for could not be found.

i don´t know that i´m doing bad.

First i´m upload my file with input type file and ajax using formData, in my controller process this file:

/**
     * FUNCTION TO SAVE ORDER WITH DEALER
     */
    public function saveOrderDealerNumber(Request $request)
    {   
        try{

            if($request->file('adjunto') != ""){

                $nombreArchivo = $request->file('adjunto')->getClientOriginalName();
                $file = $request->file('adjunto');

                $path = public_path().'/postventa';
                $uplaod = $file->move($path,$nombreArchivo);
                
                return asset('postventa/'.$nombreArchivo);
            }else{
                return "Error al subir fichero, consulte al administrador del sistema";
            }
    
        }catch(Exception $e){
            return $e->getMessage();
        }
    }

this function upload ok my file in my folder in public_path() i don´t use storage folder.

In javasript response i have this:

success: function(response){
                    var today = new Date();
                    var date = today.getDate()+"/"+"0"+(today.getMonth()+1)+"/"+today.getFullYear()+" "+
                    today.getHours() + ":" + today.getMinutes();

                    //date to insert in db
                    var dateDB = today.getFullYear()+"-"+"0"+(today.getMonth()+1)+"-"+today.getDate()+" "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();

                    $("#adjuntoSend").val(file.name);
                    $("#usuarioSend").val('');
                    $("#fecha_horaSend").val(dateDB);
                    $("#routeAttachedSend").val(file.name);

                    $("#tableFiles tbody").append(`
                        <tr class="text-center">`+
                        `<td>`+file.name+`</td>`
                        +`<td>`+file.type+`</td>`
                        +`<td>`+"{!! auth()->user()->nombre !!}"+`</td>`
                        +`<td>`+date+`</td>`
                        +`<td><button type="button" class="btn" data-toggle="modal" data-target="#myModal"><i class="fas fa-eye text-dark fa-2x"></i></button></td>`
                        +`</tr>`);

                    $(".btn").on('click', function(){
                        $("#document").attr("src", response);
                    })
                },

I´m set src attr to embed tag in my modal bootstrap, this it´s result:

<embed src="https://xxxx/postventa/cliente.pdf" frameborder="0" width="100%" height="400px">

postventa it´s a folder in public.

When i´m editting my order, i have same code and also i have same error.. But in my localhost it´s ok.

my subdomain it´s in VPN in my server.

Any body have idea that i´m doing wrong?

this it´s my file My file uploaded

this it´s my route in my pc My route in my pc

Thanks for help. I´m modifying this app, all system it´s in windows server with xampp.....



via Chebli Mohamed

jeudi 19 août 2021

Array and string offset access syntax with curly braces is deprecated in php-7.4.19-Win32-vc15-x64

I have this old project with importing excel data to db,i am using laragon with latest version with php-7.4.19-Win32-vc15-x64 but the project is run with 7.1 in the server so i have used php-7.1.25-Win32-VC14-x64 this php version,but when i try to upload excel it throws this error I have searched also found using [] instead of {} will fix the issue,but i have tried that, this is line where showed the error but i tried to use [] this but same error throws }); return back()->with('success', 'Your File Is Successfully Uploaded To Database!');

public function importExcel(Request $request)
{
    if ($request->hasFile('import_file')) {

        Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
            foreach ($reader->toArray() as $key => $row) {
                
                $old_customer = Registration::where('customerid', $row['customerid'])->first();
                if(count($old_customer)==0)
                {

                $data['customername'] = $row['customername'];
                $data['chassis'] = $row['chassis'];
                $data['model'] = $row['model'];
                $data['branchcode'] = $row['branchcode'];
                $data['delivery'] = $row['delivery'];
                $data['customerid'] = $row['customerid'];
                $data['phone'] = $row['phone'];
                $data['invoicedate'] = $row['invoicedate'];
                
                $registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();

                if (count($registration_id) > 0) {
                    $regid = $registration_id[0]->registration_id;
                    $regid = $regid + 1;

                } else {
                    $regid = 1;
                }

                $register = new Registration();
                $register->registration_id = $regid;
                $register->customername = $row['customername'];
                $register->chassis = $row['chassis'];
                $register->model = $row['model'];
                $register->branchcode = $row['branchcode'];
                $register->delivery = $row['delivery'];
                $register->customerid = $row['customerid'];
                $register->phone = $row['phone'];
                $register->invoicedate = $row['invoicedate'];
                $register->created_user_id = Session::get('created_id');
                $register->save();

                $regidn = Registration::orderBy('registration_id', 'desc')->get();
                $regidd = $regidn[0]->registration_id;
                $ssitrack = new Ssi_track();
                $ssitrack->registration_id = $regid;
                $ssitrack->ssi_track_id = $regid;
                $ssitrack->save();
                $ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
                $ssitrackk = $ssitrackk[0]->registration_id;

                }
                
            }
        });
      return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
    }
    return back()->with('success', 'File Doesnt Uploaded!');
}


via Chebli Mohamed

How to pass condition in laravel 5 relation model

I am trying to get the data from group model but i am relate the student table new_group_id to group table id if it not null else connect the group_id to group table id.

public function grade(Builder $query){
       
        
        return $query
          ->when($this->new_group_id != 0,function($q){
              return $q->with('new_group_id');
         })
         ->when($this->new_group_id === 0,function($q){
              return $q->with('group_id');
         });
    }

But given the error is Argument 1 passed to App\Students::grade() must be an instance of App\Builder,

please help me to solve these error



via Chebli Mohamed

mercredi 18 août 2021

Access Laravel URL with ID only (Best approach)

My application is made in laravel 5.8, I want to ask about the best approach for a unique scenario where I want to display some of my customer profiles like

https://www.example.com/1234

I know that in laravel I have to give a unique identifier before the URL like https://www.example.com/profile/1234 so that it know which function to look for. But for some reason I have to build the above URL.

I tried it directly like:

Route::get('/{id}', 'ExampleController@myfunction')->name('profiler');

But this only works when I put it in bottom of my Routes file. If I place it somewhere in the middle or top. All other links like https://www.example.com/about-us stops working.

My Question is:

  • What is the best approach to achieve something like this. (Is it fine that I keep it in the bottom of the route file or will it be some kind of threat or any drawbacks to this approach?)
  • Should I use this approach or add a unique identifier instead.

I would really want to use the URL I mentioned in the start of the question.

Thank you all in advance for helping me.

Peace :)



via Chebli Mohamed