mercredi 30 juin 2021

print results in descending order

I need to print results in a decreasing way

controller:

$servicios = \App\Models\Eventos::All()->sortByDesc('hora');

blade.php

  @foreach ($servicios as $hoy)
                                        <tr>
                                            <td class="checkbox-column text-center"> </td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td class="text-center"><span class="shadow-none ">
                                            @if($hoy->prioridad == 'badge badge-primary') 
                                          Normal
                                            @elseif($hoy->prioridad == 'badge badge-warning') 
                                           Prioridad
                                             @elseif($hoy->prioridad == 'badge badge-success') 
                                          Personal
                                             @elseif ($hoy->prioridad == 'badge badge-danger') 
                                           Urgente
          

                                            @endif
                                            
                                            </span></td>
                                        
                                        @endforeach

enter image description here

the problem is that it does not print with the foreach with the DESC order



via Chebli Mohamed

I am getting wrong assets url using Laravel helper "secure_asset"

I have a website on domain mydomain.space

I include in my blade file some js file in such way:

<script  type="text/javascript" src="{!! secure_asset('js/app.js') !!}"></script>

But then, on production, I see in browser logs, that frontend try to load file by this URL:

http://mydomainspace/js/app.js

Yeah, for some reason it removes dot and as result - it is wrong URL... But when I display APP_URL variable - it shows "mydomain.space" (with dot).

Why I lose dot in URL when use secure_asset helper?



via Chebli Mohamed

it doesn't take my password set in a variable

i need help to know why my static password saved in variable does not work

I'm doing is deleting records, but with a password to confirm the action

enter image description here

Controller:

public function eliminar($id) {
    $registros = \App\Models\Registro::find($id);
    if (! $registros) {
        session()->flash('error_message', 'Model not found with the given id:');
        return back();
    }

    // static password
    $password = ('asdf');

    // $password is the password that you have saved somewhere
    if (request()->password_field_value == $password) {
       
        $registros->delete();
        
        session()->flash('success_message', 'Model deleted successfully.');
        return back();
    }

    session()->flash('error_message', 'Invalid password. Try again');
    return redirect('sistema');
}

blade

@extends('layouts.app')
    
@section('content')
    <h1>Do you want to delete the record?</h1>
    <form action="" class="d-inline" method="POST">
        @method('DELETE')
        @csrf
        <button type="submit" class="btn btn-danger btn-sm">DELETE</button>
        <div class="form-group col-md-6">
            <label for="telefono">Password</label>
            <input name="password" type="password" class="form-control" id="password"  required>
        </div>
    </form> 
@endsection

I need to know why it always throws an error, Invalid password. Try again

help please



via Chebli Mohamed

How to use another table as the login table instead of 'Users'

I have a project that has 2 tables, 1 for users details and one for login, but I want my login table to be 'webusers' instead of 'users' as Laravel uses 'users' as the default table for authentication.

I tried to change my model and auth.php but to no luck. Has anyone tried this before?

My Model:

    <?php

namespace App\Models;

use Illuminate\Auth\Authenticatable as AuthenticableTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    protected $table = "webusers";
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

auth.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'webusers',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'webusers',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'webusers',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'webusers' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'webusers',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];


via Chebli Mohamed

delete if password is correct

i need to create a condition that clears the record but with a password.

if the password is correct execute the delete();

controller:

      public function eliminar($id){

    $registros = \App\Models\Registro::findOrFail($id);
    $registros->delete();
     
    return redirect('sistema')->with('mensaje', 'Registro Borrado con exito');
}

    public function borrar($id){
        // return $request->all();
        $data = [
            'category_name' => 'datatable',
            'page_name' => 'multiple_tables',
        'has_scrollspy' => 0,
        'scrollspy_offset' => '',
        'fechax' => Carbon::now(),
        'borrar' => \App\Models\Registro::findOrFail($id),
        'password' => 'PASSCODE',
      

        ];
       
    

        return view('borrar')->with($data);
    }

blade.php:

  <h1>Do you want to delete the record?</h1>



<form action="" class="d-inline" method="POST">
    @method('DELETE')
    @csrf
    <button type="submit" class="btn btn-danger btn-sm">DELETE</button>


    <div class="form-group col-md-6">
                                                <label for="telefono">Password</label>
                                                <input name="password" type="password" class="form-control" id="telefono"  required>
                                            </div>
</form> 

the password is obtained statically

How can I make it delete without the password is identical?

help please



via Chebli Mohamed

mardi 29 juin 2021

Special Characters and Searches with Laravel elequant

The issue I am having is with Special Characters. Search with the inputs %(Modular), __(_Underscore), O(Number). It will not filter out any result. it will display all the results. Where as searching templates having other special characters and number displaying correct results.

If in the DB I have subject of myname is % user, and the users search input is %, it doesn't find the result. Same with__(_Underscore), O(Number).

($searchkeyword) {
                    $q->where(function($query) use ($searchkeyword) {
                        $query->where('studentname', 'like', "%$searchkeyword%")
                        ->orWhere('subject', 'like', "%$searchkeyword%")
                        ->orWhere('city', 'like', "%$searchkeyword%");
                    });
                })


via Chebli Mohamed

Laravel Sanctum not generating token if user id data type is string

I want to have string data type user's id in laravel and authenticate via sanctum but when i change user's id data type from bigInteger -> String it causes error while generating token but when i'm using bigInteger it works fine.

How to use string data type in user's id and authenticate via sanctum any help!

error:

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value (SQL: insert into `personal_access_tokens` (`name`, `token`, `abilities`, `tokenable_id`, `tokenable_type`, `updated_at`, `created_at`) values (apiToken, 3a8d3965b6af9d8d5b9caaa5ae557f69dc63c70ae1777e4f5509734d605b2fa4, [&quot;*&quot;], 5fa6ab1ef3206dd468a74eaf5a35d2bd, App\Models\User, 2021-06-30 06:47:05, 2021-06-30 06:47:05)) in file C:\Laravel\gleecia\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 692


via Chebli Mohamed

condition hide if it was used on the day

i need create a condition that hides a field if it was already used on the day. the fields to hide are hours i need to create the condition so that the time is not taken twice

enter image description here

that is, if the 10:00 shift has already been used, no one can use it again on the day of the date.

Blade.php:

                        <div class="col-md-6  col-sm-6 col-12">
                                <div class="form-group start-date">
                                    <label for="start-date" class="">Hora:</label>
                                    <div class="d-flex">
                                
                                    <select name="hora" class="form-control form-control-sm">
                                    @foreach($horarios as $dato)
    <option>

    </option>
    @endforeach

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

controller:

     public function index(){
       

          $datax = [
            'category_name' => 'apps',
            'page_name' => 'calendar',
            'has_scrollspy' => 0,
            'scrollspy_offset' => '',
    

        ];


       
       
  
         $month = date("Y-m");
         //
         $data = $this->calendar_month($month);
         $mes = $data['month'];
         // obtener mes en espanol
         $mespanish = $this->spanish_month($mes);
         $mes = $data['month'];
$registros = \App\Models\Horarios::All();
  
         return view("home",[
           'data' => $data,
           'mes' => $mes,
           'mespanish' => $mespanish,
           'horarios' => $registros
         ])->with($datax);
  
     }

help please



via Chebli Mohamed

I want when i update code then its display on top of page

$data = MoviesModel::where('id', $request->id)->update(['title' => $request->title]);


via Chebli Mohamed

Laravel Eloquent how to get relationship self object?

I have tables with below relationship

housing_advertisements->housing_ad_near_places->near_places

And my HousingAdvertisement model has

public function nearPlaces()
{
    return $this->hasMany(HousingAdNearPlace::class);
}

and HousingAdNearPlace

public function nearPlace()
{
    return $this->hasOne(NearPlace::class, 'id');
}

when I make query like this:

HousingAdvertisement::with('nearPlaces.nearPlace')->where('user_id', '=', auth()->user()->id)->get();

I got HousingAdNearPlace object in HousingAdvertisement model:

[...
{
...,
"near_places": [
        {
            "id": 27,
            "housing_advertisement_id": 48,
            "near_place_id": 3,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        },
        {
            "id": 28,
            "housing_advertisement_id": 48,
            "near_place_id": 4,
            "created_at": "2021-06-29T12:23:35.000000Z",
            "updated_at": "2021-06-29T12:23:35.000000Z",
            "near_place": null
        }
    ]
...]

How can I got self NearPlace model like this:

[...
{
...,
"near_places": [
        {
            "id": 3,
            "name": "Park",
            "slug": "park",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        },
        {
            "id": 4,
            "name": "Beach",
            "slug": "beach",
            "created_at": "2021-06-29T06:25:57.000000Z",
            "updated_at": "2021-06-29T06:25:57.000000Z"
        }
    ]
...]


via Chebli Mohamed

Laravel excel add complex headers to an export

I need to export a sheet with a complex heading. I need a main heading and another sub level heading after.

enter image description here

I'm trying like this,

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;

class InvoicesExport implements FromQuery, WithHeadings
{   
    public function headings(): array
    {
        return [
            'Account 1' =>[
                "Account 1 id",
                "Account 1 branch"  
            ],
            'Account 2' =>[
                "Account 2 id",
                "Account 2 branch"  
            ],
        ];
    }
}

But getting header columns like, [ "Account 1 id", "Account 1 branch" ]

is there a way to archive this task?



via Chebli Mohamed

How can you change the table where you users are called from in PHP/Laravel

I'm pretty new to Laravel and PHP but I have made an app that requires a user to log in, now this table is called users and all my users sit in there, but I want to make another table called temUsers and use that table instead... but I don't know where the code points to that user table so I can change it to temUsers. Can anyone please assist in knowing which file would point to this?.



via Chebli Mohamed

lundi 28 juin 2021

Integrate Cloudflare CDN to laravel [closed]

I want to integrate cloudflare cdn into my laravel project and I am new to laravel. Can anyone guide me in achieving this or any document or tutorial from where I can achieve this. Help will be highly appreciated.



via Chebli Mohamed

How can I retrieve data using Eloquent model without accessing the appended fields' function?

I am using Laravel 5.4.

service.php

$results = Coupon::select(...self::SELECTED_FIELDS)->with('user:id,email');
$results = $results
    ->orderBy('created_at', 'DESC')
    ->limit($limit)
    ->offset($offset)
    ->get()
    // Apparently you need to hide the computed fields manually in Laravel?
    ->each(function($row){
        $row->setHidden(
            'coupons',
            'coupons_count',
            'coupon_ids_string',
            'assigned_coupon_ids',
            'used_coupon_ids'
        );
    });

The model codes:

protected $appends = [
    'coupons',
    'coupons_count',
    'coupon_ids_string',
    'assigned_coupon_ids',
    'used_coupon_ids'
];

function getCouponIDsStringAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getCouponsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getCouponsCountAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getAssignedCouponIDsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}
function getUsedCouponIDsAttribute() {
    echo('Hahaha');
    // ... A lot of thing happened here, accessing database, do joins
}

When the codes above executed, the result of $results will execute all the appended fields's function. Output in the browser:

HahahaHahahaHahahaHahahaHahaha

I only want the appended fields to be calculated when I accessed to. I don't need to have the appended fields to be calculated for every time I ask for Coupon . How can I achieve this? Thanks!



via Chebli Mohamed

PHPUnit tests actually runs the code instead of just testing

I am not really sure if I set it up correctly or not as it is my first time working with PHPUnit tests.

I want to test one particular console command which sends emails to users.

Here's my unit test.

     /**
     * @test
     */
    public function test_expiring_assessment_command_success()
    {
        $user = $this->getOrCreateTestUser();
        $assessment = $this->getOrCreateTestOnlineVisit($user, 'cancelled');

        Log::debug($assessment); //this log logs the factory created assessment
        Log::debug(env('APP_ENV')); //testing

        $this->artisan('process:send-visit-emails');
    }

This is the code in my SendVistEmails.php

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $from = Carbon::now()->subDays(7)->startOfDay();
        $to = $from->copy()->endOfDay();

        $assessments = Assessment::query()
            ->whereIn('status', ['pending_pause', 'pending'])
            ->whereNotNull('response_required_from')
            ->whereBetween('response_required_from', [$from, $to])
            ->select('details', 'status')
            ->get();

        foreach ($assessments as $a){
            Log::debug($a); //this logs assessments present in DB instead of the one created in my test.
        }

        $assessments->each->expire();
    }

Now, when I run phpunit tests it just interacts with code and sends emails to all the users present in DB.

I want to run command just for testing and in my SendVistEmails.php code, when I log $a, it should have only the assessment my unit test created and not the ones from DB.

I spent two days on this reading so much documentation but couldn't figure out What am I missing.



via Chebli Mohamed

php artisan queue:flush does not flush the queues

Our log is blowing up due to non-stop retries by the queue workers despite having the retries set to 1 only. This is literally caused by 3 different failed job payloads that are being retried millions of times due to a fatal error.

  1. Why aren't the queued jobs just failed after the 1st one as configured?
  2. Why doesn't php artisan queue:flush actually flush the queues so it will stop retrying all jobs?

Queue is SQS based so I went into SQS and purged there and then restart the queue workers, but I would have expected the flush command and the retry setting to have done their jobs.



via Chebli Mohamed

laravel 5 change mysql password

I have the feeling that my mysql database has been hacked by someone doing minor changes (very strange but very annoying). So I want to change mysql password. I remember that a while ago and I had some issues (I had to delete a cache to finally get it to work but I don't remember which file). So I want to be sure that I do it correctly as the site is live.

1/ I would change the password of the database. 2/ I would edit the .ENV aqnd change it there 3/ From the console, I would run the following commands: php artisan cache:clear php artisan config:clear php artisan config:cache 4/ Then there is that cache file I need to delete but which one is it?

Is this the correct procedure?



via Chebli Mohamed

dimanche 27 juin 2021

"Call to private Instamojo\Instamojo::__construct() from context" in Laravel

public function pay(Request $request){

 $api = new \Instamojo\Instamojo(
   config('services.instamojo.api_key'),
   config('services.instamojo.auth_token'),
   config('services.instamojo.url')
);

try {
$response = $api->paymentRequestCreate(array(
   "purpose" => "FIFA 16",
   "amount" => $request->amount,
   "buyer_name" => "$request->name",
   "send_email" => true,
   "email" => "$request->email",
   "phone" => "$request->mobile_number",
   "redirect_url" => "http://127.0.0.1:8000/pay-success"
   ));
    
   header('Location: ' . $response['longurl']);
   exit();
}catch (Exception $e) {
print('Error: ' . $e->getMessage());
}
}

Error after submitting form on $api = new \Instamojo\Instamojo( line. Error:- Call to private Instamojo\Instamojo::__construct()



via Chebli Mohamed

Laravel Controller update model from different users

In my Laravel application, I have a Model called Project which has, among others, a property called approved_at. There is also a ProjectController, which contains the usual methods *(index, show, create, update, edit...)

Now, the user that created the Project can edit it (modifying its other attributes), but only some "staff" members have the right to approve one.

From what I understand, there can be two ways to handle the approval operation:

  1. Both users, from their respective views (let's call them edit and approve) fire the ProjectController@update method, which will internally distinguish who-can-do-what by means of authorization or policies;
  2. I create a new ProjectApprovalController, with its own update method, and check the authorization at the endpoint (eg, /projects/{id}/approve).

What is the best approach to tackle this behaviour?



via Chebli Mohamed

samedi 26 juin 2021

How to add command to run Laravel cron job in Ovi Panel?

enter image description here

I am trying to add a command to run my cron job. But It showing path is not available.

I added php then file path and command.



via Chebli Mohamed

Where is the notification push code on Laravel

Sorry for asking this question. I'm new to laravel and I'm trying to find out the location of the responsible script of sending the notification on submite button event.

When I go to

http://127.0.0.1:8000/push-notificaiton

You know there you fill the title and message then you submit it to a script or code where you find the targeted auth username.

I want to know the location of that code to edit it in order to do one more things such as inserting title and message in database after sending the push notification to use.



via Chebli Mohamed

vendredi 25 juin 2021

Laravel eloquent query groupBy category with sum and sortBy sum

I have 3 related tables:

Table category :

+-----+---------------+
| id  | nama_kategori |
+-----+---------------+
| 1   | Sayur         |
| 2   | daging        |
| 3   | buah          | 
+-----+---------------+

Table Barang

+-----+-------------+-------------+
| id  | nama_barang | id_kategori |
+-----+-------------+-------------+
| 1   | Sayur 1     | 1           |  
| 2   | Sayur 2     | 1           |   
| 3   | Daging Ayam | 2           |   
| 4   | Apple       | 3           |   
| 5   | Banana      | 3           |      
+-----+-------------+-------------+

Table barang_keluar

+-----+-------------+-----------+---------+
| id  | tgl_keluar  | id_barang | jml_bk  |
+-----+-------------+-----------+---------+
| 1   | 02-03-2021  | 1         |   200   |
| 2   | 04-03-2021  | 2         |   100   |
| 3   | 12-03-2021  | 1         |   100   |
| 4   | 15-03-2021  | 3         |   500   |
| 5   | 20-03-2021  | 2         |   100   |
| 6   | 25-03-2021  | 1         |   100   |
| 6   | 25-03-2021  | 4         |   100   |
| 6   | 25-03-2021  | 5         |   100   |
+-----+-------------+-----------+---------+

The query I'm making now looks like this:

$kategorix='All';
$bulan = '2021-03';
$bulanx=Carbon::parse($bulan)->format('Y-m');
    
$kategoriy=DB::table('barang_keluar')->join('barang','barang.id','=','barang_keluar.id_barang')
            ->join('kategori','kategori.id','=','barang.id_kategori')
            ->select('barang_keluar.id_barang',
                     'barang.id_kategori',
                     'kategori.nama_kategori',
                      DB::raw('sum(jml_bk) as total'))
             ->where(DB::raw("date_format(tgl_keluar,'%Y-%m')"), '=', $bulanx)
             ->groupBy('id_barang','id_kategori','nama_kategori')
             ->orderBy('tgl_keluar')
             ->orderBy('total')
             ->get();
                    
$barang = $kategoriy->groupBy('id_kategori');
$array = collect($barang)->sort($barang->sum('total'))->reverse()->toArray();

and the results I get:

array:5 [▼
  1 => array:1 [▼
    0 => {#939 ▼
      +"id_barang": 1
      +"id_kategori": 1
      +"nama_kategori": "Sayur 1"
      +"total": "400"
    }
  0 => {#939 ▼
      +"id_barang": 2
      +"id_kategori": 1
      +"nama_kategori": "Sayur 2"
      +"total": "200"
    }
  ]
  2 => array:1 [▼
    0 => {#943 ▼
      +"id_barang": 3
      +"id_kategori": 2
      +"nama_kategori": "Daging"
      +"total": "500"
    }
  ]
  3 => array:1 [▼
    0 => {#945 ▼
      +"id_barang": 4
      +"id_kategori": 3
      +"nama_kategori": "Apple"
      +"total": "100"
    }
    0 => {#945 ▼
      +"id_barang": 5
      +"id_kategori": 3
      +"nama_kategori": "Banana"
      +"total": "100"
    }
  ]  
]

How to get the result of sort By('subtotal') from groupBy('category_id'). Please help

I've tried adding query array and sort like this. but the result is still the same as above

$array = collect($barang)->sort($barang->sum('total'))->reverse()->toArray();

Maybe the blade table example that I made would be like this, but sorted by subtotal of the large - small values. Please help

enter image description here



via Chebli Mohamed

Method Illuminate\Database\Eloquent\Collection::save does not exist

i have a problem when updating the database

error: Method Illuminate\Database\Eloquent\Collection::save does not exist.

controller:

 public function actualizar(Request $request){
    
    $nuevoIngreso = \App\Models\Servicio::all();
    $nuevoIngreso->costo = $request->costo;
    $nuevoIngreso->duracion = $request->duracion;
    $nuevoIngreso->mantenimiento = $request->mantenimiento;
    $nuevoIngreso->save();
    return redirect('servicios')->with('mensaje', 'Ficha Actualizada.');

}

blade.php

         <form method="POST" action="">
                
@csrf

                    @foreach ($servicios as $costo)
<h1 class="text-center text-primary">   </h1>
                  <div class="form-group row">
                    <label for="example-text-input" class="col-md-2 col-form-label form-control-label">Costo</label>
                    <div class="col-md-10">
                      <input class="form-control" type="text" value="">
                
                    </div>
                    <label for="example-text-input" class="col-md-2 col-form-label form-control-label">Duración</label>
                    <div class="col-md-10">
                      <input class="form-control" type="text" value="" id="example-text-input">
                    </div>
                    <label for="example-text-input" class="col-md-2 col-form-label form-control-label">Mantenimiento</label>
                    <div class="col-md-10">
                      <input class="form-control" type="text" value="" id="example-text-input">
                    </div>
                  </div>
                 <hr>
               @endforeach

               <button type="submit" class="btn btn-success float-right" float-rightdata-toggle="sweet-alert" data-sweet-alert="success">SAVE</button>
                </form>

help please



via Chebli Mohamed

jeudi 24 juin 2021

foreach prints bad characters

foreach prints bad characters

enter image description here

I am printing a variable but it shows wrong

controller:

$servicios = Registro::where('user_id', $cliente->id)->get('tiposistema');

blade.php:

<div class="row">
    <div class="col">
      <h4>Servicios Contratados:</h4>
    </div>
    <div class="col">
        @foreach($servicios as $ver)
            
        @endforeach
    </div>
</div>

Help please



via Chebli Mohamed

Laravel Model binding resource 404 error on show, edit ,delete parameter

I have a model Category and CategoriesController resource and in my web route I have:

Route::group(['prefix' => 'admin', 'as' => 'admin.', 'namespace' => 'Admin', 'middleware' => ['auth']], function () {

    Route::resource('comments', 'CommentsController');


    // Categories
    Route::delete('categories/destroy', 'CategoriesController@massDestroy')->name('categories.massDestroy');

    Route::resource('categories', 'CategoriesController');

});

but only works with index and create the others edit, delete shows 404 , my routes list is this:

enter image description here

Example,I try to show the category 5 like this:

  public function show(Category $category)
{
   
    dd($category);
    return view('admin.categories.show', compact('category'));
}

but I get 404 error only in show, edit, delete.



via Chebli Mohamed

hide a record according to status

I need to hide a record if the status is == 'Terminado'.

It is done with an if condition, but I don't know how to apply it

enter image description here

blade.php

  <tbody>
                                    @foreach($registros as $registro)
                                       @if($registro->sucursal == Auth::user()->sucursal) 
                                       @if($registro->empleado == Auth::user()->tipo) 
                             
                               
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td>
                                                <div class="progress br-30">

                                                @if($registro->estado == 'Ingresado') 
                                                <div class="progress-bar br-30 bg-primary" role="progressbar" style="width: 20%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>
                                                @elseif($registro->estado == 'Envío de Prespuesto') 
                                                 <div class="progress-bar br-30 bg-secondry" role="progressbar" style="width: 40%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>
                                                 @elseif($registro->estado == 'Anticipo Recibido') 
                                                 <div class="progress-bar br-30 bg-warning" role="progressbar" style="width: 60%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>
                                                 @elseif ($registro->estado == 'En Reparación') 
                                                 <div class="progress-bar br-30 bg-danger" role="progressbar" style="width: 80%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>
                                                 @elseif ($registro->estado == 'Terminado') 
                                                 <div class="progress-bar br-30 bg-success" role="progressbar" style="width: 100%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>
                                                 @elseif ($registro->estado == 'Cancelado') 
                                                 <div class="progress-bar br-30 bg-danger" role="progressbar" style="width: 100%" aria-valuenow="67" aria-valuemin="0" aria-valuemax="100"></div>


                                                @endif

                                                    
                                                </div>
                                            </td>
                                            <td></td>
                                            <td></td>
                                            <td> @if($registro->presupuesto == null) No Aplicado @else $ @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="true">
                                                        <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="">Ver</a>
                                                        <a href="" class="dropdown-item" href="javascript:void(0);">Actualizar</a>
                                                        <a class="dropdown-item" href="javascript:void(0);">Borrar</a>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        @elseif($registro->estado == 'Terminado') 
                                        
                                        @endif
                                        @endif
                                        @endforeach
                                    </tbody>

the foreach should not show if the status field is == Terminado

but if it has no finished status, if it should show record

controller:

 public function registros(){

        if (Auth::guest()) return redirect('/login');

        $data = [
            'category_name' => 'datatable',
            'page_name' => 'multiple_tables',
        'has_scrollspy' => 0,
        'scrollspy_offset' => '',
        'fechax' => Carbon::now(),

        ];

      

        $registros = \App\Models\Registro::All();
       
        return view('pages.tables.table_dt_multiple_tables',compact('registros'))->with($data);
   


    }

attached blade controller attached blade controller help pls



via Chebli Mohamed

I need to update mysql table when someone use my referral code

I need to update mysql table when someone use my referral code which is store in my route using cookie.

i want to check if the cookie ref is available , if it is available two table Wallet and Referral will be updated with the transaction id and the balance on the wallet. I keep getting a success message which means the transaction is working but the table is not update. Below is my code. Thanks

Route


Route::redirect('/', '/index', 301);
Route::get('/index', function() {
    if(!empty($_GET['ref'])) {
        $ref = $_GET['ref'];
        setcookie('ref', $ref, time() + (86400), "/");
        // return redirect()->route('power.index', ['ref' => $ref]);
        // print_r($_COOKIE['ref']);
       return redirect()->route('power.index');
    } else {
        return view('index');
    }
    
})->name('index');

Referral Table

namespace App;

use Illuminate\Database\Eloquent\Model;

class Referral extends Model
{
    //
    protected $fillable = [
        'reftrans', 
        'refuserid', 
        'refamount', 
        'reftype'];
        
        protected $table = 'referrals';
        
        
}


UserTable

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'fname', 'lname', 'email', 'password', 'phone', 'gLocatorID', 'role_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $with = [
        'wallet', 'vendor'
    ];

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    public function wallet()
    {
        return $this->hasOne(Wallet::class);
    }

    public function vendor() {
        return $this->hasOne(Vendor::class);
    }

    // public function getPhoneAttribute() {
    //     return "+234" . $this->phone;
    // }
}

Wallet Table

namespace App;

use Illuminate\Database\Eloquent\Model;

class Wallet extends Model
{
    protected $fillable = [
        'user_id', 'balance'
    ];

    public function owner()
    {
        return $this->belongsTo(User::class);
    }

    public function transactions()
    {
        return $this->hasMany(WalletTransaction::class);
    }
}


Controller


class PowerController extends Controller
{

                 if(\Auth::check()) {
                 $rUserID = \Auth::id();
                     dd(cookie::get['ref']);
                     dd($ref);
                     if (isset($ref)){
                         
                     if ($ref == $rUserID){
                     
                     //define amount n type
                     $amt = 25.00;
                     $type = 'Power';
                     //Updating Wallet
                     $wallet = \App\Wallet::find($user_id)->rUserID;
                     $wallet->balance = $wallet->balance + $amt;  
                     $wallet->save(); 
                     
                     //Updating Referral
                     $referral = new \App\Referral;    
                     $referral->reftrans = $powerTransaction->id; 
                     $referral->refuserid = $rUserID; 
                     $referral->refamount = $amt; 
                     $referral->reftype = $type; 
                     $referral->save(); 
                     }
                 }else {
                 //do nothing
             }else{
                 //do nothing
            }
                   
}
 ``` 


Referral link

<input type="text" class="form-control" value="" id="myInput">


via Chebli Mohamed

Model field mapping with eloquent in laravel using attribute

Hi I have a structure in db like this:

Category id name_pl name_en

Post id title body lang category

Ofcourse Post->category i related to Category->id. What I'm trying to achive is to get posts with category name depending on Post-lang like this:

{
   id: 1,
   title: "Something",
   body: "whatever",
   categoryName: "Category name in correct language"
}

. I've been trying to do that using atrribute in Post model like this:

    public function getCategoryNameAttribute()
    {
        $category = Category::find($this->category)->load('icon');
        return [
            'id' => $category->id,
            'name' => $this->lang === 'pl' ? $category->name_pl : $category->name_en,
        ];
    }

But in this case I have n+1 problem. I've been trying to use with() method but inside attribude method I get only category id. Any ideas?



via Chebli Mohamed

how to show 404 page in laravel 5.2?

I want to show the 404 pages in laravel 5.2 projects. but how is possible and how to handle errors in laravel 5.2? please help me!

  1. how to handle errors in laravel 5.2?
  2. how to return 404 page?
  3. if cannot find URL then return 404 page in laravel 5.2?


via Chebli Mohamed

The query is not working properly. filter in laravel

$data = Orders::join('order_details','order_details.orders_id','=','orders.id')
            ->join('users','users.id','=','orders.user_id') 
            ->select('orders.*','order_details.total_pay','users.first_name','users.last_name') 
            ->where(function($query) use ($user_name,$promotion_code,$status){
                $query->orwhereRaw("concat(first_name, ' ', last_name) like '%$user_name%'")
                ->Where('promotion_code', $promotion_code)
                ->Where('status', $status);             
            }); 

1.When I search all three data at the same time it's ok . But why I input 1/3 data or 2/3 data it doesn't filter?



via Chebli Mohamed

mercredi 23 juin 2021

AJAX data not reaching Laravel Controller method

I am trying to make updates to an app that is using Laravel 5.6. I have the following Laravel set up:

Route

Route::post('getFeedData', 'SurveyController@getFeedData')->name('getFeedData');

Controller

use App\Http\Controllers\Controller;
use App\Classes\FeedRequest;        
class SurveyController extends Controller
{
    public function getFeedData(FeedRequest $request){
        $obj = new FeedRequest();
        
        DebugBar::info($request);
        return response($this->surveyRepository->getNewFeed($obj));
    }
}

My FeedRequest Class

namespace App\Classes;

class FeedRequest {
    public $segments;
    public $locations;
    public $departments;
    public $improvementCats;
    public $search;
    public $waste;
    public $count;
    public $offset;

    public function __construct() {
        $this->segments = array();
        $this->locations = array();
        $this->departments = array();
        $this->improvementCats = 0;
        $this->search = '';
        $this->waste = array();
        $this->count = 20;
        $this->offset = 0;
    }
}

And Lastly My JS

$.ajax({
            url: "/getFeedData",
            type: 'POST',
            contentType: "application/json",
            headers: {
             'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: JSON.stringify(request),
        })
        .done((response, textStatus, xhr) => {
            ...
        })
        .fail(() => {
            ...
        }) 

My Controller method is executing but I always have the default version of my FeedRequest object. When I change the controller to accept the default Laravel Request object all my passed parameters are in the "content" attribute. What am I missing to properly hydrate the FeedRequest parameter?



via Chebli Mohamed

Text extraction from Driving Licence using PHP/Laravel

Are there any standard libraries that can help with text extraction from predefined formats like Driving Licence?

We are looking to integrate it with the laravel application.

Thank you in advance.



via Chebli Mohamed

Laravel Markdown mail logo not working on server

Markdown mail logo not working on server works perfect in local

i have follow below steps.

  1. publish laravel mail files
  2. Changes in resources/views/vendor/mail/html/header.blade.php

Thanks in advance



via Chebli Mohamed

Convert JSON IN LARAVEL

Here is my JSON

[
    {
        "TIMESTAMP": "2021-06-09 13:13:26",
        "COL1": "10",
        "COL2": "20",
        "COL3": "30"
    },
    {
        "TIMESTAMP": "2021-06-22 13:13:26",
        "COL1": "20",
        "COL2": "30",
        "COL3": "40"
    },
    {
        "TIMESTAMP": "2021-06-21 13:13:26",
        "COL1": "1",
        "COL2": "2",
        "COL3": "3"
    },
    {
        "TIMESTAMP": "2021-06-20 13:13:26",
        "COL1": "40",
        "COL2": "50",
        "COL3": "60"
    }
]   

I need to refactor the json According to the Column name like (EXPECTED OUTPUT)

[
    {
      "TITLE":"COL1"
      "DATA":[10,20,1,40]
      
    },
    {
       "TITLE":"COL2"
      "DATA":[20,30,2,50]
      
    },
    {
      "TITLE":"COL3"
      "DATA":[30,40,3,60]
      
    },
]
  

I was tried but it not working

$data = json_decode($result, true); 
$refactored = array_map(function($item) {
    return (object)[
        'TIMESTAMP' => $item['TIMESTAMP'],
        'DATA' => [ $item['COL1'], $item['COL2'], $item['COL3'] ]
    ];
}, $data);
dump($refactored);

Someone help me out with this. The column may be 3 or more and it must be dynamic. Thanks in advance.



via Chebli Mohamed

mardi 22 juin 2021

SQLSTATE[HY000] [1049] Unknown database 'test' (SQL: select * from `users` where `username` = admin123 limit 1)

I am getting this error while trying on laragon

SQLSTATE[HY000] [1049] Unknown database 'test' (SQL: select * from users where username = admin123 limit 1)



via Chebli Mohamed

Call to private Instamojo\Instamojo::__construct() from context

public function pay(Request $request){

$api = new \Instamojo\Instamojo(
       config('services.instamojo.api_key'),
       config('services.instamojo.auth_token'),
       config('services.instamojo.url')
   );

 try {
   $response = $api->paymentRequestCreate(array(
       "purpose" => "FIFA 16",
       "amount" => $request->amount,
       "buyer_name" => "$request->name",
       "send_email" => true,
       "email" => "$request->email",
       "phone" => "$request->mobile_number",
       "redirect_url" => "http://127.0.0.1:8000/pay-success"
       ));
        
       header('Location: ' . $response['longurl']);
       exit();
   }catch (Exception $e) {
    print('Error: ' . $e->getMessage());
  }
}

Error after submitting form on $api = new \Instamojo\Instamojo( line.

Error:- Call to private Instamojo\Instamojo::__construct()



via Chebli Mohamed

PHPUnit in Laravel 5.2 Not Passing When Form Validation is Added

I'm currently trying to add validation to my forms. It works fine when I test it but it fails when I run my unit test on it. Removing the validation code allows it to pass with no problems. I tried rewriting the validation portion of the code to do the check manually but no luck. I'm not sure what else I can try. Any help is appreciated.

The error I get:

Did not land on expected page [http://localhost/dashboard].

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://localhost/dashboard'
+'http://localhost/reset-password'

Here's what the form validator looks like:

 public function submit(Request $request)
    {        
        $validation_errors = [];

        $currentUser = $request->user();

        $currentUser->password = Hash::make($request->input('new_password'));
        $currentUser->reset_password = false;

        $user = User::where('id', $currentUser->id)->first();

        // >>>>>> Validation Code Start <<<<<<<< //
        // >>>>>> Removing this block allows it to pass <<<<<<< //

        $newPassword = $request->input('new_password');
        // Check if password is the same as the one in the database
        if(Hash::check($newPassword, $user->password))
        {
            return back()->withErrors('Your password can not be the same as your old password.');
        }

        // Check for special characters
        if (!preg_match('/[\'\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\\\]/',
        $newPassword))
        {
            array_push($validation_errors, "Please make sure your password contains a special character.");
        }
        
        // Check for numbers
        if (!preg_match('~[0-9]~', $newPassword))
        {
            array_push($validation_errors, "Please make sure your password contains a number.");
        }

        // Check for Upper/Lower case
        if (!preg_match('/[A-Z][a-z]*/', $newPassword))
        {
            array_push($validation_errors, "Please make sure your password contains a combination of uppercase and lowercase letters.");
        }

        // Check for Password length
        if (strlen($newPassword) < 10) 
        {
            array_push($validation_errors, "Please make sure your password length is a minimum than 10 characters.");
        }

        if (count($validation_errors) > 0)
        {
            return back()->withErrors($validation_errors);
        }
        // >>>>>> Validation Code End <<<<<<<< //

        $currentUser->save();

        return redirect()->route('/dashboard');
    }

And this is the unit test code:

public function testResetPasswordSuccess()
    {
        $this->betestUser();
        $this->visit('/reset-password')
            ->type('123', 'password')
            ->type('123', 'password_confirm')
            ->press('Save')
            ->seePageIs('/dashboard');
    }

And for anyone curious, this is how I originally validated the form:

$this->validate($request, [
            'password' => [
                'bail',
                'required',
                'confirmed',
            ],
            'password_confirm' => [
                'bail',
                'required',
            ],
        ]);


via Chebli Mohamed

Laravel get method parameters cannot be fetched

I faced a weird issue in Laravel today, the version am using is Laravel 5.5 and I have defined a route as below in the application.

 Route::get('getplaylist/{playlistid}/{page}', 'Mycontroller@getplaylist');

And in my controller am trying to fetch the parameters, weirdly

dd($request->all()); // results in empty array []

whereas the below one works,

dd($request->playlistid);

Any help would be appreciated on what is happening behind the scenes. The issue am facing is am not able to validate the request since an empty '[]' array is resulted.



via Chebli Mohamed

lundi 21 juin 2021

how to sort data including special characters in laravel in composer

how to sort data including special characters in laravel

like 332-1 , 332-2 , 332-10 , 332-11 , 332-20

when try to sort

got

332-1 , 332-10, 332-11,332-2, 332-20

   $data = GeneralVehicle::with('pricingVehicle', 'watermarkVehicle')
        ->where('save_check', '!=', 2)
        ->where('hidden_check', 0);
    if ($transit != 0)
        $data->where('selection', 2)
            
            ->orderBy('lot_no', 'asc');
    else
        $data->whereIn('selection', [1, 3, 5])
            ->orderBy('lot_no', 'desc');
    if ($location != 0)
        $data->where('location', $location);
    else
        $data->whereIn('location', [1, 2, 3]);
    if ($category != 0)
        $data->where('category', $category);
    $vehicles_total = $data->get();
    $vehicles = $data->paginate(20);


via Chebli Mohamed

I can't find the user and sum

i have a problem, i need to add the debt of a user

controller:

 public function cliente($id){

        // $nota = App\Nota::find($id);
    
        //Aquí valida si existe sino redirije al 404
        $datos = [
            'category_name' => 'datatable',
            'page_name' => 'multiple_tables',
        'registro' => Registro::find($id),

        ];

        $cliente = \App\Models\User::findOrFail($id);
    
    
        return view('cliente', compact('cliente'))->with($datos);
    }

blade.php

<div class="row">
<div class="col">
  <h4>Debt Sum:</h4>
</div>
<div class="col">
 
</div>

Database:

enter image description here

i need to add the field "deuda" of the user, the relationship is in user_id with the users table

the error that I get is: Trying to get property 'user_id' of non-object

help pls



via Chebli Mohamed

Converting complex SQL select to Laravel Eloquent

I am new to Laravel and trying to support an existing application that is in Laravel 5. I am trying to convert the following SQL to eloquent structure

SELECT s.id, 
CONCAT(u.first_name, ' ', u.last_name) AS user_name, 
u.avatar_location AS user_img, 
s.employee_photo, 
d.name AS department, 
seg.name AS segment, 
s.survey_title, 
s.before_action, 
s.before_picture, 
s.action, 
s.action_date, 
s.after_action, 
s.after_picture, 
s.nominated, 
s.awarded, 
s.created_at, 
s.updated_at,
(SELECT COUNT(1) FROM likes l WHERE l.survey_id = s.id) AS likes,
(SELECT COUNT(1) FROM likes l WHERE l.survey_id = s.id AND l.user_id = 5) AS UserLikes,
(SELECT COUNT(1) FROM comments c WHERE c.survey_id = s.id ) AS comments
FROM surveys s 
JOIN departments d 
ON s.department = d.id 
JOIN segments seg 
ON s.segment_id = seg.id 
JOIN users u 
ON s.user_id = u.id 
WHERE s.status = 'Approved' 
ORDER BY s.action_date DESC
LIMIT 20 OFFSET 20

I know enough Laravel to know that my basic start would probably be

$surveys = DB::table('surveys')
    ->join('departments',  'surveys.department', '=', 'departments.id')
    ->join('segments', 'surveys.segment_id', '=', 'segments.id')
    ->join('users', 'surveys.user_id', '=', 'users.id')
    ->where('surveys.status', 'Approved')
    ->orderBy('surveys.action_date')
    ->skip(20)-take(20)
    ->select(...)->get();

However, I am not sure how to do the subqueries. Looking for any suggestions.

Thanks!



via Chebli Mohamed

The query did not execute properly

$data = User::where('inet_id', "like", "%" . $inet . "%")
         ->orWhere('email', "like", "%" . $email . "%")
         ->orWhere('phone', "like", "%" . $phone . "%")
         ->get();
  1. It only executes the query when searching all 3 data once. But I want to search by separate data too.


via Chebli Mohamed

why is my query not working adding like %%

$data = User::WhereRaw("concat(first_name, ' ', last_name) like '%$request->user_name%'")
->orwhere('inet_id',"like", "%" .$request->active_id. "%")
->orwhere('email',"like", "%" . $request->email. "%")
->orwhere('phone',"like", "%" . $request->phone . "%")->get();
  1. Why is my query not working adding like %% .


via Chebli Mohamed

Apple Pay Integration In Laravel

I want to integrate apple pay into my Laravel website but unable to find the proper solution for its integration. Is there any REST API documentation for apple pay integration in PHP.? Like,

  1. create payment API in Apple Pay
  2. refund payment API in Apple Pay


via Chebli Mohamed

dimanche 20 juin 2021

Refactor the JSON object in Laravel

Here's my JSON:

[
    {
        "ID": 1,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-05 07:05:29",
        "VALUE": "30"
    },
    {
        "ID": 4,
        "SOURCEID": 2,
        "TIMESTAMP": "2020-04-05 07:05:17",
        "VALUE": "40"
    },
    {
        "ID": 3,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-06 12:04:59",
        "VALUE": "35"
    },
    {
        "ID": 5,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-06-17 12:01:32",
        "VALUE": "1"
    },
    {
        "ID": 6,
        "SOURCEID": 2,
        "TIMESTAMP": "2021-06-17 13:55:29",
        "VALUE": "2"
    }
]

I need to refactor the JSON like

I need JSON to be refactor based on timestamp and source id and JSON is dynamic like a number of source id present in the given JSON there are two ids that is 1 and 2. Below I gave the expected output.

I need a Unique time stamp in a separate array-like

 [2020-04-05,2020-04-06,2020-06-17,2021-06-17]
    { "sourceid: 1, "data":[30,35,1,0], }, { "sourceid": 2, "data":[40,0,0,2], }

Note: The value fills according to the date. Other it should fill as 0.

I have tried like this :

    `$data=json_decode($result);

    $timestamp=[];
    $dataList=[];
    foreach ($data as $value){

        $date=\Carbon\Carbon::parse($value->TIMESTAMP)->toDateString();

        if(!in_array($date, $timestamp, true)){
            array_push($timestamp, $date);
        }
        
        if(isset($dataList[$value->SOURCEID])){
            array_push($dataList[$value->SOURCEID]['data'],$value->VALUE);
        } else{
            $dataList[$value->SOURCEID]=[
                'SOURCEID'=>$value->SOURCEID,
                'data'=>[$value->VALUE]
            ];
        }
    }
    dump($timestamp);
    dump($dataList);` 

But it produce like

{ "sourceid: 1, "data":[30,35,1], }, { "sourceid": 2, "data":[40,2]}

but I need like

{ "sourceid: 1, "data":[30,35,1,0], }, { "sourceid": 2, "data":[40,0,0,2] }


via Chebli Mohamed

PHP Fatal error: Uncaught PDOException: SQLSTATE[200]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' [closed]

[20-Jun-2021 14:57:53 UTC] PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' in /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:464 Stack trace: #0 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(464): PDOStatement->execute() #1 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(664): Illuminate\Database\Connection->Illuminate\Database{closure}('insert into tr...', Array) #2 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(631): Illuminate\Database\Connection->runQueryCallback('insert into tr...', Array, Object(Closure)) #3 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(465): Illuminate\Database\Connection->run('insert into tr...', Array, Object(Closure)) #4 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(417): in /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671 [20-Jun-2021 14:57:53 UTC] PHP Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY' in /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:464 Stack trace: #0 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(464): PDOStatement->execute() #1 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(664): Illuminate\Database\Connection->Illuminate\Database\{closure}('insert into tr...', Array) #2 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(631): Illuminate\Database\Connection->runQueryCallback('insert into tr...', Array, Object(Closure)) #3 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(465): Illuminate\Database\Connection->run('insert into tr...', Array, Object(Closure)) #4 /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php(417): in /home2/islamage/public_html/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 671



via Chebli Mohamed

samedi 19 juin 2021

error add money from all records - count()

i need to add up all the money in the column "ingresos".

Error: Property [presupuesto] does not exist on this collection instance.

used the variable :


database:

enter image description here

Controller:

public function contador(){

        if (Auth::guest()) return redirect('/login');

      

        $contador = \App\Models\Registro::All();
       
        return view('contador',compact('contador'));
   


    }

I need to add the income



via Chebli Mohamed

Laravel chunkbyid for joins

When i use chunkById on a Query Builder with joins I am not getting the output

 DB::table('cs')
 ->join('hw','hw.p1', '=', 'cs.awb')
 ->where('cs.dv','hw')
 ->chunkById(100, function ($hw_orders) use (&$hwCount) {
 foreach ($hw_orders as $hwd){
  Log::info('Number ' . $hwd->awb);
 });

I want to know how I could chunk this data with joins. Thank you



via Chebli Mohamed

vendredi 18 juin 2021

Trying to get property of non-object - name

i am trying to print the username, but it gives me error

Trying to get property of non-object

Models

User:

<?php

namespace App\Models;
use App\Models\Registro;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
    public function registros(){
      
       
         return $this->belongsTo('\App\Models\Registro', 'user_id');
    }
}

Registro:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use \App\Models\User;

class Registro extends Model
{
    use HasFactory;

    public function user(){
        return $this->hasMany('\App\Models\User');

    }
   
}

database:

enter image description here

in blade.php:

    

maybe I'm doing something wrong with relationships, but I can't figure it out on my own

<tbody class="list">
            @foreach($registros as $registro)
              <tr>
                <th scope="row">
                  <div class="media align-items-center">
                    <a href="#" class="avatar rounded-circle mr-3">
                      <img alt="Image placeholder" src="../../assets/img/theme/bootstrap.jpg">
                    </a>
                    <div class="media-body">
                      <span class="name mb-0 text-sm"></span>
                    </div>
                  </div>
                </th>
            
              </tr>
             @endforeach
            </tbody>

try changed relationships but it doesn't work does not allow me to print the name of user_id, help pls



via Chebli Mohamed

Laravel 8 File Validation

I'm new to laravel and I have been struggling to validate uploaded files.

Below is the code that handles validation:

// (I tried mime, mimes, mimetypes) none of them are validating any of the files correctly.
        $validator = Validator::make($request->all(), [
            'proposal_summary' => 'mimetypes:application/pdf|max:2048',
            'plagiarism_report' => 'mimetypes:pdf,doc,docx,txt|max:2048',
            'final_proposal' => 'mimes:pdf,doc,docx,txt|max:2048',
        ]);

I tested this with PDF, docx and txt files, all without success. I get an error saying the files must be a file of type: pdf, doc, docx, txt. Even though they are. I am sure I am doing something wrong, so any help would be appreciated. Please let me know if you require more code or further explanation.



via Chebli Mohamed

How to merge two rows and get result?

Table Data:

sales_products table data:

product_id quantity sales price
1 4 300
1 5 300
2 3 400
2 2 400
3 3 100

products table

id product_name
1 product_x
2 product_y
3 product_z

Expected Query Output

product_name Quantity Total_Price
product_x 9 2700
product_y 5 2000
product_z 3 300

I was trying with following Query and didn't get expected output

$invoiceDetails = DB::table('products')
    ->join('sales_products', 'sales_products.product_id', '=', 'products.id')
    ->select(
        'products.product_name',
        'sales_products.quantity',
        'sales_products.sales_price',
        DB::raw('(sales_products.quantity * sales_products.sales_price) as total')
    )
    ->where('sales_products.invoice_id', '=', $id)
    ->get();


via Chebli Mohamed

Added relationship to laravel model doesn't exist

I've makde some changes to a laravel model php file and the changes never get picked up.

I've tried clearing the cache, adding errors, renaming/deleting the file and the site just runs as if none of these things have happened.

It also only seems to happen to this one file in particular, the other model files are fine when I add changes

Anyone had this happen before?



via Chebli Mohamed

Why i can't edit image properties on ckeditor after uploading image on laravel

i have trouble editing my image properties after uploading it in ckeditor4, the image properties seems like been disabled? i can't click anything on high and width input box, or hspace ande vspace. the only thing that i can press are the cancel and save button. does anyone have the same issue? and perhaps the solution for it?.

here i attachthe code for my blade for the ckeditor,and my upload image in the controller

//code on my blade

<div class="form-group">
        <label>Deskripsi</label>
          <textarea type="text" name="deskripsi" class="form-control" placeholder="Deskripsi Item"> </textarea>
           <script>
              CKEDITOR.replace( 'deskripsi', {                                     filebrowserUploadUrl: "", filebrowserUploadMethod: 'form',
filebrowserBrowseUrl : " type=2&editor=ckeditor&fldr=",
filebrowserImageBrowseUrl : "?type=1&editor=ckeditor&fldr=",
config.allowedContent = 'a[!href,target];img[src,alt,width,height]; span[*](*)',
                                });
           </script>
</div>
 public function uploadImage(Request $request)
    {
        if($request->hasFile('upload')) {
         
            //get filename with extension
            $fileNameWithExtension = $request->file('upload')->getClientOriginalName();
       
            //get filename without extension
            $fileName = pathinfo($fileNameWithExtension, PATHINFO_FILENAME);
       
            //get file extension
            $extension = $request->file('upload')->getClientOriginalExtension();
       
            //filename to store
            $fileNameToStore = $fileName.'_'.time().'.'.$extension;
       
            //Upload File
            $request->file('upload')->storeAs('public/uploads', $fileNameToStore);
  
             
            $CKEditorFuncNum = $request->input('CKEditorFuncNum') ? $request->input('CKEditorFuncNum') : 0;
             
            if($CKEditorFuncNum > 0){
             
                $url = asset('storage/uploads/'.$fileNameToStore); 
                $msg = 'Image successfully uploaded'; 
                $renderHtml = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
                 
                // Render HTML output 
                @header('Content-type: text/html; charset=utf-8'); 
                echo $renderHtml;
                 
            } else {
             
                $url = asset('storage/uploads/'.$fileNameToStore); 
                $msg = 'Image successfully uploaded'; 
                $renderHtml = "<script>window.parent.CKEDITOR.tools.callFunction($CKEditorFuncNum, '$url', '$msg')</script>";
                return response()->json([
                    'uploaded' => '1',
                    'fileName' => $fileNameToStore,
                    'url' => $url
                ]);
            }
             
        }
    }


via Chebli Mohamed

jeudi 17 juin 2021

Controller method very fast (0.2s) but TTFB is 15 seconds

So I've timed my controller method in Laravel with both microtime(true) and getrusage, and checked the actual data responded - it processes my request in ~0.2s, so quite fast.

The actual TTFB for it to respond back to my app is a massive 12 seconds.

Given the data is obtained and returned so quickly, where could this bottleneck be?

I'm aware it's quite a vague question, but I honestly have no idea what could be doing this. Has anyone encountered similar? Included the controller method below, in case it's handy. Just using a standard Axios get() request to run the query.

enter image description here

public function authenticate(Request $request){
    $credentials = $request->only('email', 'password');

    try {
        if (! $token = JWTAuth::attempt($credentials)) {
            return response()->json(['error' => 'invalid_credentials'], 401);
        }
    } catch (JWTException $e) {
        return response()->json(['error' => 'could_not_create_token'], 500);
    }

    $user = User::where('email',$request->email)->first();

    if($request->invitationIdIfExists){
        $invitation = Invitation::find($request->invitationIdIfExists);

        if($invitation->recipient_email == $user->email){
            $request->headers->set('Authorization', 'Bearer '.$token);
        
            Helper::processInvitation($invitation, $user);
        }
    }

    $user->touch();

    $user->token = $token;

    $user->load(['accounts', 'minTodoDays', 'minNotifications']);

    $user->todo_days = $user->minTodoDays;
    $user->notifications = $user->minNotifications;

    unset($user->minTodoDays);
    unset($user->minNotifications);

    $invitationIfExists = Invitation::where('recipient_email', $user->email)->where('completed', 0)->first();

    if($invitationIfExists){
        $user->invitedAccount = $invitationIfExists->account;
    }

    return $user;
}


via Chebli Mohamed

Refactoring of Json in laravel

Alright, I need some assistance from an expert.

I have attached my Json below[

    {
        "ID": 1,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-05 07:05:29",
        "VALUE": "30"
    },
    {
        "ID": 4,
        "SOURCEID": 2,
        "TIMESTAMP": "2020-04-05 07:05:17",
        "VALUE": "40"
    },
    {
        "ID": 3,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-04-06 12:04:59",
        "VALUE": "35"
    },
    {
        "ID": 5,
        "SOURCEID": 1,
        "TIMESTAMP": "2020-06-17 12:01:32",
        "VALUE": "1"
    },
    {
        "ID": 6,
        "SOURCEID": 2,
        "TIMESTAMP": "2021-06-17 13:55:29",
        "VALUE": "2"
    }
]

I need to refactor the json like

  1. I need Unique time stamp in separate array like [2020-04-05,2020-04-06,2020-06-17,2021-06-17]

  2. I need json to be refactor based on timestamp and source id and json is dynamic like number of source id present in the given json there are two id that is 1 and 2. Below I gave expected output.

    { "sourceid: 1, "data":[30,35,1,0], }, { "sourceid": 2, "data":[40,0,0,2], }

Thanks in advance.



via Chebli Mohamed

first() not working on string with more than one words [closed]

private function getBrandIdFromName($brandName){
        $brand = Brand::query()->where('slug',$brandName)->first();
        if($brand){
            return $brand->id;
        }else{
            $newBrand = [
                'name'=>$brandName,
                'is_active'=>"1",
                'meta'=>[
                    'meta_title'=>null,
                    'meta_description'=>null,
                ]
            ];
            $brand = Brand::create($newBrand);
            return $brand->id;
        }
    }

here 'slug' and 'name' are column in different tables

for one word like "puma" its working fine. but for more than one word like "puma world" it not working well i.e. its importing name again and again. I dont know its reason wheather its causing because of first() or any other mistake. if anyone know please do help.



via Chebli Mohamed

Update pdf which is open in laravel

I'm creating pdf file using DOM pdf, it is working but when i try to recreate it with same name and the pdf file is open then i'm getting this error message:

message: exception: "ErrorException" file: "C:\xampp\htdocs\xxxxxxx\vendor\league\flysystem\src\Adapter\Local.php" line: 199"file_put_contents(C:\xampp\htdocs\XXXX\storage\app\public/pdf/salary/40_file-2021.pdf): failed to open stream: Resource temporarily unavailable" trace: [{function: "handleError", class: "Illuminate\Foundation\Bootstrap\HandleExceptions", type: "->"},…]

             $dompdf = new Dompdf();
             $dompdf->set_option('isHtml5ParserEnabled', true);
             $dompdf->set_option('isRemoteEnabled', true);  
             $html = view('admin/pdf',['data'=>$data_new])->render();
             $dompdf->loadHtml($html);
             $dompdf->setPaper('A4', 'portrait');
             $dompdf->render();
             $fileName = 'pdf/salary/'.$data_new->user_id.'_'.$data_new->application_id.'.pdf';
             Storage::put('public/'.$fileName, $dompdf->output());

Any suggestion is highly appreciated.



via Chebli Mohamed

Cross Authentication between two different Laravel application

enter image description here

Background

The two application is developed in PHP Laravel web application. In the application, App 1 and App 2 are two difference Application and being managed by two different team. App 1 is use to trim video while App 2 is use to showcase their video.

Algorithms:

  1. In the App 1 (Ex. Facebook), user can login to the system and upload video together with some form details.
  2. App 1 then trim and process the video and save inside the FileSystem.
  3. After the process, App 1 then POST the results to App 2 (Ex. Instagram).
  4. In the App 2, the video is then uploaded with the respective user information and showcase to public.

Problem

  • How do APP 1 authenticate the user in APP 2.
  • What is the best approach and most user friendly method while provide a secure authentication

The thing that I concern is the authentication part of App 2. How do we authenticate the user in App 2 before sending the videos to App 1 due to difference user login method?

Some Work that I managed to found on Google

First Way: hash(Master Key + [INFO])

  1. Create a master key that are known by only App 1 and App 2. Then hash the master with some extra information (Ex. time()). Then App 2 can validate the hash information with its own master key and if the result is similar then, user can pass through the authentication process and straight away post the video on App 2.

Second Way: OAUTH Token

  1. User have to login to the App 2 and generate OAUTH token. Then user need to submit their OAUTH token on App 1 to allows for video posting. This method is not really user friendly as this approach is somewhat the approach for developer.

Not really sure about the terminology used for this type of authentication. Feel free to let me know in the comment section. Thank you very much.



via Chebli Mohamed

Console not finding the function even if it was included/imported - Javascript / Laravel

I'm currently working on an old project work which utilizes a function for the dropdown design of the web application running in PHP/Laravel.

It shows me this error on the console:

app.js:121 Uncaught TypeError: $(...).dcDrilldown is not a function
at HTMLDocument.<anonymous> (app.js:121)
at j (jquery.min.js:2)

But when I checked my app.blade.php under resources/views, it is importing the file that contains that specific function:

<script type="text/javascript" src=""></script>

Inside the drilldown.js, the function dcDrilldown is found:

(function($){
//define the new for the plugin ans how to call it
    console.log("Here I am with open arms~");
    $.fn.dcDrilldown = function(options) {
        console.log("Now I come to you~");

On the console logs, the logs "Here I am with open arms~" is being shown but not the console inside the function: Click here for image

Any ideas why the dcDrilldown function is not being found? Thanks!



via Chebli Mohamed

solution for double text in laravel

private function getBrandIdFromName($brandName){
        $brand = Brand::query()->where('slug',$brandName)->first();
        
        if($brand){
            return $brand->id;
        }else{
            $newBrand = [
                'name'=>$brandName,
                'is_active'=>"1",
                'meta'=>[
                    'meta_title'=>null,
                    'meta_description'=>null,
                ]
            ];
            $brand = Brand::create($newBrand);
            return $brand->id;
        }
    }

this is my code when i import one text "nike" its working well. but when i import 2 text like "nike world" its importing text "nike world" again and again when i import text again. please do help if anyone has solution.



via Chebli Mohamed

mercredi 16 juin 2021

Add the user ID on the URL

I'm trying to pass a user id on the URL. Once I click on the icon, it should redirect to a specific page with datatables. enter image description here

and I should see the ID appended on the url enter image description here

Here are my codes, JS, controller and route. But it won't work.

 <a class="btn btn-link btn-success btn-just-icon btn-round" href="" title="SMS History">
                    <i class="material-icons">sms</i>
                    <div class="ripple-container"></div>
                </a>

controller:

public function getView($id)
{


    $smshistory = SmsOutboundsHistory::find($id);

    return view('pages.sms-history')->withSmshistory($smshistory); }

Route: Route::get('/pages/history/{id}', 'HistoryController@getView');



via Chebli Mohamed

Laravel Permissions Always return TRUE

I'm trying to create a condition for a button using permissions, but even though the permission is not assigned to the user, it returns TRUE... always.

This is what I have in my controller:

public function edit($id){
    $permisos = Auth::user()->hasPermissionTo('listaPrecios.utilidadCero');
    dd($permisos);

    return view('panel.lista_precio.lista_precio_edit')
        ->with( 'permisos' , $permisos);
}

The dd is only to check its status.

Could you help me to resolve this issue? I saw different posts where if you use Can it works, unfortunately it did not work for me either.



via Chebli Mohamed

APP_ENV=dev causes A facade root has not been set

so i have updated the APP_ENV=dev the original APP_ENV=local, now it is my assumption that the following change causes me with the following error

A facade root has not been set

laravel.ERROR: A facade root has not been set. {"exception":"[object] (RuntimeException(code: 0): A facade root has not been set. at /var/app/current/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:236) [stacktrace] #0 /var/app/current/app/Exceptions/Handler.php(80): Illuminate\Support\Facades\Facade::__callStatic('check', Array) #1 /var/app/current/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(314): App\Exceptions\Handler->report(Object(GuzzleHttp\Exception\ConnectException)) #2 /var/app/current/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(118): Illuminate\Foundation\Http\Kernel->reportException(Object(GuzzleHttp\Exception\ConnectException)) #3 /var/app/current/public/index.php(55): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request)) #4 {main} "}

Not i already run PHP artisan config:cahce and PHP artisan cache:clear



via Chebli Mohamed

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) - laravel

I am using MAMP in the macOs. I was download the laravel 5 from cpanel. I am getting this error:

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select * from `products` where `pro_status` = 1 and `pro_stock` > 0 order by `pro_id` desc limit 8)

But can't fix it.



via Chebli Mohamed

Laravel Collection Sum by Item Key

I have the following Laravel collection $output. I want to sum total for each value of sex 1 and 2. I have tried $output->sum('total') but it gives overall total .

Illuminate\Support\Collection {#1334 ▼
  #items: array:11 [▼
    0 => {#1348 ▼
      +"total": 1037931027.8459
      +"status": 2
      +"sex": 1
    }
    1 => {#1346 ▼
      +"total": 1091237622.0488
      +"status": 2
      +"sex": 2
    }
    2 => {#1342 ▼
      +"total": 1103340160.4262
      +"status": 1
      +"sex": 1
    }
    3 => {#1349 ▼
      +"total": 6004661.498201
      +"status": 4
      +"sex": 1
    }
   ]
 }    


via Chebli Mohamed

Laravel excel library(Maatwebsite) : How to create a drop down with multiple select for Export

I'm using Laravel Excel to export excel with larvel. I need a dropdown with multiple select.

use App\MyModel;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;

class MyModelExport implements FromArray, WithHeadings
{
    public $rowCount = 0;
    public function array(): array
    {
        $branches = MyModel::get([
            "title",
            "ranks",
        ]);

        $data = [];
        

        foreach ($items $key => $item) {

            $data[$key]['title'] = $item->title;
            $data[$key]['ranks'] = $item->ranks;
        }

        $this->rowCount = count($data);
        return $data;
    }

    public function registerEvents(): array {
        
        return [
            AfterSheet::class => function(AfterSheet $event) {
                /** @var Sheet $sheet */
                $sheet = $event->sheet;

                /**
                 * validation for bulkuploadsheet
                 */
                
                for($i=2; $i<=$this->rowCount+1; $i++){
                    $sheet->setCellValue('B'.$i, $sheet->getCell('B'.$i)->getValue());
                    $configs = "dis1, dis 2, dis 3";
                    $objValidation = $sheet->getCell('B'.$i)->getDataValidation();
                    $objValidation->setType(DataValidation::TYPE_LIST);
                    $objValidation->setErrorStyle(DataValidation::STYLE_INFORMATION);
                    $objValidation->setAllowBlank(false);
                    $objValidation->setShowInputMessage(true);
                    $objValidation->setShowErrorMessage(true);
                    $objValidation->setShowDropDown(true);
                    $objValidation->setErrorTitle('Input error');
                    $objValidation->setError('Value is not in list.');
                    $objValidation->setPromptTitle('Pick from list');
                    $objValidation->setPrompt('Please pick a rank from the drop-down list.');
                    $objValidation->setFormula1('"' . $configs . '"');
                }
            },
        ];
    }

    public function headings(): array
    {
        return [
            'Title',
            'Ranks'
        ];
    }
}

This code gives a dropdown. But what I need a dropdown with multiple selects. Simply I need to select multiple ranks in one cell.



via Chebli Mohamed

mardi 15 juin 2021

API Based Observer in Laravel

I want to make API based observer in laravel . I am using laravel 5.5. Basically I display data from API. My expectation is If there inserts any new data then laravel application fetch that on that time. Here one application is for provide API and another application is for fetch data. Here database only use api application



via Chebli Mohamed

Laravel 8 Cannot Insert Or Update Data In A Certain Table

I'm new to Laravel, and I have been struggling to insert data into a certain table, hods. The table only has two fields, a unique id, and a foreign key called user_id.

Below is the code for the Hod model:

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Hod extends Model
{
    use HasFactory;

    protected $table = 'hods';

    protected $primaryKey = 'id';

    protected $fillable = 'user_id';
}

Below is the code for the method in my controller where I want the query to take place:

    public function createHOD(Request $request)
    {
        // Validate Form Input
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,except,id',
            'password' => 'required|string|min:8|confirmed',
        ]);

        // If Validation Is Successful
        if (!$validator->fails()) {

            // Create User THIS QUERY WORKS FINE    
            $user = User::create([
                'name' => $request->input('name'),
                'email' => $request->input('email'),
                'password' => Hash::make($request->input('password')),
                'user_type' => "HOD"
            ]);

            // Attaching 'HOD' Role To User
            $user->attachRole('HOD');

            // Adding The User To The HOD Table NOT WORKING
            $hod = new Hod();
            $hod->user_id = $user->id;
            $hod->save();

            // TRIED THIS TOO, ALSO NOT WORKING
            DB::table('hods')->insert(
                ['user_id' => $user->id],
            );

            return response()->json(['success' => 'HOD Successfully Created.']);
        } else {
            // Return Error Messages
            return response()->json(['error' => $validator->errors()->all()]);
        }
    }

I'm making use of AJAX, below is the code that handles that aspect:


            $("#hodSubmit").click(function(e) {
                e.preventDefault();

                var _token = $("input[name=_token]").val();
                var name = $("input[name=hod_name]").val();
                var email = $("input[name=hod_email]").val();
                var password = $("input[name=hod_password]").val();
                var password_confirmation = $("input[name=hod_confirmation]").val();

                $.ajax({
                    url: "",
                    type: 'POST',
                    data: {
                        _token: _token,
                        name: name,
                        email: email,
                        password: password,
                        password_confirmation: password_confirmation
                    },
                    success: function(data) {
                        if ($.isEmptyObject(data.error)) {
                            $("#hodForm")[0].reset();
                            printSuccessMsg("hod");
                        } else {
                            printErrorMsg(data.error, "hod");
                        }
                    }
                });
            });

Please let me know if you require additional code or further explanation. Thanks



via Chebli Mohamed