vendredi 30 avril 2021

Laravel Get Value From json_encode

I can't get value of id from json string.

$photoIdObj = DB::table('images')->select('id')->whereJsonContains('name', ['path' => $photoPath])->get(); 
    $jsonString = json_encode($photoIdObj, true); //object to json string conversion. Result: "[{"id":7}]"
    $jsonArr = json_decode($jsonString); // json string to array
    $photoId = $jsonArr->id;
    
    //$selectedImages = \App\Image::where('id', $jsonString);
    $selectedImages = \App\Image::findOrFail($photoId);
    $selectedImages->forceDelete();

Error message:

"Trying to get property 'id' of non-object"


via Chebli Mohamed

How to return values in array of json using laravel query?

$search='m';
$data = Product::select("product_name")
        ->where('product_name','LIKE', '%' . $search . '%')
        ->get();
    
 return response()->json($data);

It returns [{"product_name":"MyProduct"},{"product_name":"MAC"}] ..... But I want [{"MyProduct"},{"MAC"}]



via Chebli Mohamed

Laravel Broadcast on demand

on documentation laravel about notification on demand it's only have example for mail,slack and nexmo so how to send notification via broadcast use on demand. https://laravel.com/docs/5.8/notifications

that example for mail

Notification::route('mail', 'taylor@example.com')
        ->route('nexmo', '5555555555')
        ->route('slack', 'https://hooks.slack.com/services/...')
        ->notify(new InvoicePaid($invoice));

or how to send notification broadcast without Eloquent.



via Chebli Mohamed

Get Departmenr name from department id using eloquent laravel

I have this user table

id | name |      email     | department_id

1    user 1  xyz@gmail.com        2

and this is department table

id |  department_name 

1      Admin 
2      Account

there is salary table :

id |  user_id |  basic_pay

1        1          5000

I have this employee relation in salary model

class Salary extends Model
{
   public function employee(){
      return $this->belongsTo('App\User','user_id','id');
   }
}

I want to get department name also to which user is associated

  $Data =  Salary::where('id',$id)->with('employee')->first();

but presently i can only get department_id with the help of employee relation.

Any help is highly appreciated.



via Chebli Mohamed

Laravel Coinpayment Issue "HMAC signature does not match"

Hello guys please i need help with this issue,i used coinpaymentHosted Lib ,i have set the creditiate correct but i am having this error message when i try to proccess transaction here is my code,

    $cps = new CoinPaymentHosted();
    $cps->Setup($gate->val2,$gate->val1);
    $callbackUrl = route('user.callback.coinpayment');

    $req = array(
        'amount' => (FLOAT) $Amountcharge,
        'currency1' => 'USD',
        'currency2' => $request->selectcrypto,
        'custom' => $transactionRecord->uuid,
        'ipn_url' => $callbackUrl,
        'cancel_url' => route('home'),
        );
    $result = $cps->CreateTransaction($req);
     dd($result);

i dont know if i am getting anything wrong or it coming from coinpayment, i have also install this package https://github.com/hexters/CoinPayment and set it according to usage but i still get the same error "HMAC signature does not match"



via Chebli Mohamed

jeudi 29 avril 2021

I am trying to switching from gulp to webpack

This is my code below can anyone help

var elixir = require('laravel-elixir');

var paths = { 'default': './resources/assets/', 'jquery': './vendor/bower/jquery/', 'bootstrap': './vendor/bower/bootstrap-sass/assets/', 'bootstrapFile': './vendor/bower/bootstrap-fileinput/', 'bootstrapSwitch': './vendor/bower/bootstrap-switch/dist/', 'admin': './vendor/bower/startbootstrap-sb-admin-2-sass/', 'social': './vendor/bower/bootstrap-social/', 'fonts': './vendor/bower/font-awesome/', 'tables': './vendor/bower/datatables/media/', 'tablesPlugins': './vendor/bower/datatables-plugins/', 'tablesResponsive': './vendor/bower/datatables-responsive/', 'metisMenu': './vendor/bower/metisMenu/', 'raphael': './vendor/bower/raphael/', 'morris': './vendor/bower/morrisjs/', 'redactor': './vendor/bower/redactor/', 'select2': './vendor/bower/select2/dist/', 'sortable': './vendor/bower/jquery-sortable/source/', 'validation': './vendor/bower/jquery-validation/dist/', 'waypoints': './vendor/bower/waypoints/lib/', 'scrollTo': './vendor/bower/jquery.scrollTo/', 'usMap': './vendor/bower/us-map/', 'tipso': './vendor/bower/tipso/src/', 'owlCarousel': './vendor/bower/owl.carousel/dist/' };

elixir(function(mix) {

/* Admin */

 mix.sass( "admin/app.scss", 'public/assets/admin/css/', {
   includePaths: [
     paths.bootstrap        + 'stylesheets/',
     paths.bootstrapFile    + 'css/',
     paths.admin            + 'sass/',
     paths.fonts            + 'scss/',
     paths.tables           + 'css/',
     paths.tablesResponsive + 'css/',
     paths.metisMenu        + 'dist/',
     paths.morris,
     paths.social,
     paths.redactor         + 'redactor/',
     paths.select2          + 'css/'
   ]
 })

 .copy( paths.fonts         + 'fonts',           'public/assets/admin/fonts'           )
 .copy( paths.bootstrap     + 'fonts/bootstrap', 'public/assets/admin/fonts/bootstrap' )
 .copy( paths.tables        + 'images',          'public/assets/admin/images'          )
 .copy( paths.bootstrapFile + 'img',             'public/assets/admin/images'          )

 .scripts([
         paths.jquery           + 'jquery.js',
         paths.bootstrap        + 'javascripts/bootstrap.js',
         paths.bootstrapFile    + 'js/fileinput.min.js',
         paths.bootstrapSwitch  + 'js/bootstrap-switch.min.js',
         paths.tables           + 'js/jquery.dataTables.js',
         paths.tablesResponsive + 'js/dataTables.responsive.js',
         paths.metisMenu        + 'dist/metisMenu.js',
         paths.raphael          + 'raphael.js',
         paths.morris           + 'morris.js',
         paths.admin            + 'dist/js/sb-admin-2.js',
         paths.redactor         + 'redactor/redactor.js',
         paths.redactor         + 'redactor/redactor-plugins/counter.js',
         paths.redactor         + 'redactor/redactor-plugins/definedlinks.js',
         paths.redactor         + 'redactor/redactor-plugins/editormode.js',
         paths.redactor         + 'redactor/redactor-plugins/filemanager.js',
         paths.redactor         + 'redactor/redactor-plugins/fontcolor.js',
         paths.redactor         + 'redactor/redactor-plugins/fontfamily.js',
         paths.redactor         + 'redactor/redactor-plugins/fontsize.js',
         paths.redactor         + 'redactor/redactor-plugins/imagemanager.js',
         paths.redactor         + 'redactor/redactor-plugins/limiter.js',
         paths.redactor         + 'redactor/redactor-plugins/table.js',
         paths.redactor         + 'redactor/redactor-plugins/textdirection.js',
         paths.redactor         + 'redactor/redactor-plugins/textexpander.js',
         paths.redactor         + 'redactor/redactor-plugins/video.js',
         paths.select2          + 'js/select2.js',
         paths.sortable         + 'js/jquery-sortable.js',
         paths.default          + 'js/admin/file-input.module.js',
         paths.default          + 'js/admin/postal-target.module.js',
         paths.default          + 'js/admin/spend.module.js',
         paths.default          + 'js/admin/custom.js'
     ],
     'public/assets/admin/js/admin.js',
     './'
 );

/* Front */

mix.sass('front/app.scss', 'public/assets/css/', {
    includePaths: [
        paths.bootstrap        + 'stylesheets/'
    ]
})
.scripts([

        paths.jquery           + 'jquery.js',
        paths.validation       + "jquery.validate.min.js",
        paths.waypoints        + "jquery.waypoints.min.js",
        paths.scrollTo         + "jquery.scrollTo.min.js",
        paths.tipso            + "tipso.js",
        paths.owlCarousel      + "owl.carousel.js",
        paths.default          + 'js/front/validation.module.js',
        paths.default          + "js/front/job-filter.js",
        paths.default          + "js/front/distance-picker.js",
        paths.default          + "js/front/apply-validation.js",
        paths.default          + "js/front/contact-validation.js",
        paths.default          + "js/front/profile-tabs.js",
        paths.default          + "js/front/state-hover.js",
        paths.default          + "js/front/main.js"

    ],
    'public/assets/js/app.js',
    './'
)
.scripts([

        paths.default          + "js/front/vendor/raphael.js",
        paths.default          + "js/front/vendor/jquery.usmap.js",
        paths.default          + "js/front/map.js"
    ],
    'public/assets/js/map.js',
    './'
);
//.version([ 'assets/css/app.css', 'assets/js/app.js' ]);

// iFrame
mix.sass([

        'iframe/truckingTruth.scss'

    ],
    'public/assets/css/truckingTruth.css' )
    .scripts([

            paths.jquery           + 'jquery.js',
            paths.validation       + "jquery.validate.min.js",
            paths.default          + "js/front/apply-validation.js"

        ],
        'public/assets/js/truckingTruth.js',
        './'
    );
    //.version([ 'assets/css/truckingTruth.css' ]);

mix.version([ 'assets/css/app.css', 'assets/js/app.js', 'assets/css/truckingTruth.css', 'assets/js/truckingTruth.js' ])

});



via Chebli Mohamed

how to loop through data from many to many relationship laravel?

i am trying to get the name of the supplier of each product but when i do this

 @foreach ($products as $product )
    <tr>
      <th scope="row"></th>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
@endforeach

it says Property [name] does not exist on this collection instance however when i do this

<td></td>

this is what is what it shows me [{"id":1,"name":"test","address":"test","created_at":null,"updated_at":null,"pivot":{"product_id":1,"supplier_id":1}}]

so i think the relationship exists i just cant figure out how to loop through it

side note : i did indeed insert data through phpmyadmin and not seed ,



via Chebli Mohamed

Facing issue while implementing JWT Auth Laravel

Not Found The requested URL was not found on this server. Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.Apache Server at xphenoconnect.com Port 80



via Chebli Mohamed

Node js socket.io broadcast only for particular events subscription

Now I have a small program in Laravel to serve the stock market rates via events. When ever the rates gets update it will update the rates to redis and broadcast from node js application to clients.

Here I have created 3 events like ounce rate, MCX rates and comex rates. My socket.io program as like,

redis.subscribe('mcxratesupdate', function(err, count) {
    
});

redis.subscribe('ounceratesupdate', function(err, count) {
    
});

redis.subscribe('comexratesupdate', function(err, count) {
    
});

redis.on('message', function(channel, message) {
    message = JSON.parse(message);
    io.emit(channel + ':' + message.event, message.data);
});

server.listen(3002, function(){
    console.log('Listening on Port 3002');
});

In my client having the code like,

$(function () {
    var socket = io.connect('http://myhost:3002/', { secure: true, transports: ['websocket'], rejectUnauthorized: false, reconnect: true });
    socket.on("mcxratesupdate:App\\Events\\MCXRateUpdates", function(data){
        console.log(data);
    });
});

This is working fine, But if the event ounceratesupdate get fires that response also broadcast to this client. So all the events in this single server data getting broadcast to client. How to avoid all the events data sharing and only share particular event data.



via Chebli Mohamed

mercredi 28 avril 2021

LdapRecord Laravel - Active Directory - does not see any users

I am using the ready package as a base, I have done all steps in the readme.md file and was able to login as "einstein" user. So all seems to be configured correctly.

Later I have changed the credentials for the ldap server, which is using Active Directory.

While runing command php artisan ldap:test i receive message that i was able to connect correctly. Laravel logs says the same, but I cannot log in to laravel app. While running the command php artisan ldap:import ldap get message that no users where find

In the log file i see something like this:

[2021-04-28 23:04:08] local.INFO: LDAP (ldap://domain.pl:389) - Operation: Search - Base DN: cn=username@domain.pl,ou=Users,dc=domain,dc=pl - Filter: (&(objectclass=top)(objectclass=person)(objectclass=organizationalperson)(objectclass=inetorgperson)(uid=username)) - Selected: (entryuuid,*) - Time Elapsed: 737.37  

Have anyone had the same issue with the ldaprecord that he was able to connect to domain but wasn't able to authenticate to an app ? And was able to solve that ?



via Chebli Mohamed

Obtain customer collection with filtered addresses in Eloquent

I have this two models:

   customers(id,firstname,lastname,phone)
   addresses(id,province_id,address,customer_id)

With relation:

 class Customer extends Model
 {

     public function addresses()
     {
         return $this->hasMany(Address::class);
     }
 }


 public function customer()
     {
         return $this->belongsTo(Customer::class,'customer_id');
     }

And I'm trying to obtain customers with address in certain city

  return new CustomerCollection(Customer::has('addresses')
                       ->with(array('addresses' => function($q) use ($field)
                        {
                          $q->where('province_id','like',$field)->get();

                        }))->orderBy('id','DESC')->paginate(100));

Result is fine, I obtain correct customers collection, but addresses array is empty. What's wrong?



via Chebli Mohamed

Laravel Run on virtual host domain then validation not working

Hello i have run laravel created virtual host abc.dev and post form then validation not working

After i have run using ip address 127.0.0.1 then validation working

Any body face this issue?



via Chebli Mohamed

Show Specific Array Images in Modal Using Laravel & jQuery AJAX

I need to show specific image from array images, but I can't do it. Below what I've tried!

Array Images

Controller

public function edit($id)
{
    $product = \App\Product::find($id);

    $picts = [];
    foreach (json_decode($product->product_photo) as $picture) {
        $picts[] = $picture->path;
    }

    $pix = [];
    for ($i = 0; $i < count($picts); $i++) {
        $pix[$i] =
            '<input type="hidden" name="photo_id" id="photo_id' . $i . '">
            <div class="array-images-forEdit" style="position:relative;float:left;margin-right:5px;"><button type="submit" style="position:absolute;top:0;left:0;top:2px;left:5px;margin-left:80px;" class="close-forEdit" aria-label="Close"><span>&times;</span></button><a href="javascript:void(0)" data-toggle="tooltip"  data-id="' . $product->id . '"  data-filter="/reference/eureka/storage/app/' . $picts[$i] . '" data-original-title="Edit" class="showModalPhoto" id="showModalPhoto"><img id="myImage" src="/reference/eureka/storage/app/' . $picts[$i] . '" style="height:120px;width:105px;margin-bottom:10px;top:0;right:0;"/></a></div>
            ';
    }
    $pix = implode(' ', $pix);

    $html =
        '
    <div class="row">
    <div class="col-md-12">
    ' . $pix . '
    </div>
    </div> <!-- row-->';

    return response()->json(['html' => $html, 'product' => $product->category]);
}

Array Images Preview enter image description here

Now, when I click one of image above, it should display specific image in modal. But I can't do it. It show all images. Below the result!

Controller

 public function showPhoto($id)
    {
    $product = \App\Product::find($id);
    $picts = [];
    foreach (json_decode($product->product_photo) as $picture) {
        $picts[] = $picture->path;
    }

    $html = [];
    for ($i = 0; $i < count($picts); $i++) {
        $html[$i] =
            '<div class="row">
        <div class="col-md-4">
        <img src="/reference/eureka/storage/app/' . $picts[$i] . '" style="height:500px;width:465px;margin-bottom:10px;top:0;right:0;"/>
        </div>
     </div>';
    }

    return response()->json(['html' => $html]);
} 

View

$('body').on('click', '#showModalPhoto', function(e) { // .editUser exist in usercontroller.php

        e.preventDefault();
        $('.alert-danger').html('');
        $('.alert-danger').hide();

        id = $(this).data('id');

        $.ajax({
            url: "product/" + id + "/show-photo",
            method: 'GET',
            dataType: 'json',
            success: function(data) {
                $('#dataPhotoElement').html(data.html);

                $('#photo_id').val('');
                $('#productForm').trigger("reset");
                $('#modelHeading').html("Show Photo");
                $('#ajaxModelForPhoto').modal('show');
            }
        });
    });

Modal View enter image description here



via Chebli Mohamed

Laravel Eloquent Model can't sync with pivot data in Many-to-Many relationship

I would like to sync the data instead of attach the data to the particular relationship.

Pivot relation UserModel code

public function carts(){
        return $this->belongsToMany(Product::class,'user_carts')->withPivot('quantity');
    }

The attach code is

User::find(1)->carts()->attach($s,["quantity"=>1]);

The sync code is

User::find(1)->carts()->sync($s,["quantity"=>1]);

When I try to compile the sync, those pivot relation that matched user_id = 1 does not have the "1" in its respective quantity column.

If I would like to achieve the sync function without using attach, how can I do it because the attach() will create multiple redundant data in my database.



via Chebli Mohamed

mardi 27 avril 2021

Return 404 in Laravel RouteServiceProvider

I want to give a 404 response if index.php is found in the url. example url is domain.com/index.php/about

expected : return blade 404

I've tried this code but can't get the 404 display

class RouteServiceProvider extends ServiceProvider
{
    protected $namespace = 'App\Http\Controllers';

    public function boot()
    {
        parent::boot();
    }

    public function map()
    {
        $this->removeIndexPhpFromUrl();
    }

    protected function removeIndexPhpFromUrl()
    {
        $currentUrl = url()->current();
        if(strpos($currentUrl, 'index.php') !== false){
            return view('errors.404');
        }
    }
}



via Chebli Mohamed

method injection in laravel

hi guys i am new in laravel i have been reading about service container but i have one question about method injection laravel has its limits regarding method injection as far as i know we can only use method injection inside 3 methods (places) first , all public methods inside constructor second , boot method inside any service provide , third , handle method inside queue jobs is there any other methods we can use method injection inside ?

namespace App\Http\Controllers ;

public function store(request $request,User $user) {

   dd($user) //it works 
}

and also works inside boot method inside service provider and inside laravel queue jobs is there any methods?



via Chebli Mohamed

How to fetch the data from the server in jquery? [closed]

I use laravel and jquery.

I have 4 divs in my view. I need to fetch the time() from the server and to display it in each div's.

View:

<div id="div1"> </div>
<div id="div2"> </div>
<div id="div3"> </div>
<div id="div4"> </div>

Controller:

class SampleController extends Controller
{
    public function getcurrentTime($divId = null)
    {
     $result = time();
     return view('welcome');
    }
}

In Sample.js:

$(document).ready(function(){
  function myFunction() {
  document.querySelectorAll('*').forEach(function(node) {
    ajax = $.ajax({
      url: '/SampleController/getCurrentTime/' . node,
      method: 'post',
      dataType: 'json',
      success: function(data) {
         if (data === true) {
            trueFunction(data);
         } else {
            falseFunction(data);
         }
         ajax = null;
      }
    });

    node.innerHTML = ajax.data;

  });
}
  function trueFunction(data) {
      element.html('Success: ' + data);
   }

   function falseFunction(data) {
      element.html('Failed: ' + data);
   }

    });

In web.php

Route::post('SampleController/getcurrentTime', 'SampleController@getcurrentTime');

Getting an error

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.

Could someone please help.

Thanks



via Chebli Mohamed

Laravel 8 return blank page

In controller;

 public function list_of_approved_policies(){
    
      dd("I am here");
      die(); 
    } 

In route

Route::get('/listofapprovedpolicies','MerchantDashboardController@list_of_approved_policies');

When I calling /listofapprovepolicies Laravel return just white blank page. How can i solve this problem ?



via Chebli Mohamed

500 Whoops, something went wrong on our servers [closed]

PLEASE HELP ME HOW TO SOLVE THIS ERROR



via Chebli Mohamed

lundi 26 avril 2021

Need to get data with laravel when query

I am trying to filter data using when query in Laravel, where it should filter data using the filter $sortBy or $categoryId. Please note the all 3 fields like $id $sortBy $categoryId are optional and will not be presented in all queries

public function Products(Request $request)
{
    $page     = $request->has('page') ? $request->get('page') : 1;
    $limit    = $request->has('itemsPerPage') ? $request->get('itemsPerPage') : 10;
    $sortBy = (($request->sortBy == "popularity")  ? "viewCount" : "created_at");
    $categoryId=  $request->get('categoryId');

    $sellerId = $request->header('id')?SellersBranding::findOrFail($request->header('id')):"Null";
    
    $productLive = ProductsLive::select('productTitle', 'product_id', 'brand_id', 'category_id')
        ->when($sellerId=="Null", function($query)  use ($page, $limit){
            return $query->where('status', 'active')
            ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($sortBy, function ($query) use ($sortBy, $sellerId, $page, $limit){
            return $query->orderBy($sortBy, 'DESC')
                ->where('Sid', $sellerId->id)
                ->where('status','active')
                ->limit($limit)->offset(($page - 1) * $limit);
        })
        ->when($categoryId, function ($query) use ($categoryId, $sellerId, $page, $limit) {
            ->where('Sid', $sellerId->id)
                ->where(['category_id' => $categoryId, 'status' => 'active'])
                ->limit($limit)->offset(($page - 1) * $limit)
                ->inRandomOrder();
        })->get();
}

i am new in php and also in laravel please help how to get filtered data



via Chebli Mohamed

How to create a test for a pivot table?

I want to create a test for the controller. There are three tables, Roles, Categories and Categories_roles, the connection is many to many.

Controller:

/**
 * Update connections.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function update(Request $request) {

    $input = $request->get('category', []);
    foreach (Category::all() as $category) {
        $category->roles()->sync(Arr::get($input, $category->id, []));
    }
    return view('home');
}

I can not figure out how to write a test, there is a view in my head but I don't know how to implement. How I started to do.

Test:

/** @test */
public function test_admin_user_can_edit_categories_roles()
{
    $this->actingAs(\App\Models\User::factory()->create(['role_id' => 1]));
    $input = [
        "1" => [
            "1" => "1"
        ],
        "2" => [
            "1" => "1"
       ],
    ];
    $this->post('/admin/connections', $input);
}


via Chebli Mohamed

Larave BelongsTo relationship returns null

I have two Eloquent models:

1) Project :

class Project extends Model
{
    protected $table = 'projects';
    protected $fillable = ['id', 'user_id', 'account_id'];

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

    public function account()
    {
        return $this->belongsTo(Account::class, "account_id");
    }

2) Account :

class Account extends Model
{
    // ...

    public function projects(){
        return $this->hasMany(Project::class);
    }

The goal is to have returned the account of the project :

Project::with("account")->get()->pluck("account");

Result :

null


via Chebli Mohamed

Issue with Laravel casting Int to string when fetching from server?

I have my web application running on server. I tested the code in local and it works fine. I'm getting id as int from local server but string in hosted server.

Using PHP 7.3

$data = DB::table('users')
->select('id')
->get();

$data = $data->pluck(id);

(Local) output => [1,2,3]

(Hosted) output => ["1","2","3"]

Can any one help to resolve this issue? I can do loop to type cast but there are 100's for function in my controller. It is not possible to type cast each query.



via Chebli Mohamed

How to use bunnycdn laravel module?

I found BunnyCDN Module on GitHub, I want to use the module for my laravel application. Anyone, please tell me how can I do that?

Github Link: https://github.com/PlatformCommunity/flysystem-bunnycdn

Thank you.



via Chebli Mohamed

dimanche 25 avril 2021

Laravel DB facade nested array for relatioships

I work with huge database, with many tables, so I prefered working with DB facade instead of Eloquent models.

I have two tables with one-to-many relationship (although foreign key is not declared):

                     +-------------+
+-----------+        | orders      |
| clients   |        +-------------+
+-----------+        | order_id    |
| client_id |<-------| client_id   |
| name      |        | details     | 
+-----------+        +-------------+

I would like to achieve the same result as I would do using with() function:

[
   [
      'client_id' => 1,
      'name' => 'Alfonso',
      'orders' => [
         [
            'order_id' => 32,
            'details' => 'Loren Ipsum'
         ],
         [
            'order_id' => 34,
            'details' => 'Loren Ipsum'
         ]
      ]
   ],
   [
      'client_id' => 2,
      'name' => 'Beatriz',
      'orders' => [
         [
            'order_id' => 15,
            'details' => 'Loren Ipsum',
         ],
         [
            'order_id' => 19,
            'details' => 'Loren Ipsum',
         ],
      ]
   ]
];

I can do it with simple foreach function, I wonder whether there is some way to use something similar to with() function although I don't use models.

The basic query looks like this:

$res = DB::table('clientes')
    ->leftJoin('orders', 'orders.client_id', '=', 'cliends.client_id')
    ->get()->toArray();


via Chebli Mohamed

Display Multiple Images in Laravel Datatables

I am trying many times to show multiple images in datatables, but it always failed. It's only display single image.

Images in database

[{"name":"_MG_2288 (1).jpg","path":"public\/product_images\/\/mKBWAFw7ZYgVqvz1lrxrEA5PYbal1EqqKm9jEx0F.jpg"},{"name":"555dca050423bda8418b4567.jpeg","path":"public\/product_images\/\/QnYnO9SfA9JJIu7wm0rxJOIJog6txmED8pdiZ4nM.jpg"}]

Controller

$data = \App\Product::latest()->get();

        return Datatables::of($data)
            ->addIndexColumn()
            ->addColumn('photo', function ($product) {
                foreach (json_decode($product->product_photo) as $picture) {
                    $pict = '<img src="/reference/eureka/storage/app/' . $picture->path . '" style="height:120px; width:200px"/>';
                    return $pict;
                }
            })
            ->rawColumns(['photo'])
            ->make(true);


via Chebli Mohamed

Controller returning null on eloquent query in laravel 5.8 phpunit test

I am trying to create a mock for model ProjectRating where I want to return a specific value based on whatever the query for the model is. With select and first I am receiving the set result value but I am getting null when I have a where in the query.

My Query in the controller looks like this

$projectRating = ProjectRating::select('rating')
                ->where('project_id', $projectId)
                ->where('country_id', $countryId)
                ->where('language_id', $languageId)
                ->first() ;

and my test code looks like this

$fakeProjectRating = \Mockery::mock(ProjectRating::class);

$fakeProjectRating->shouldReceive('select->where->where->where->first')->andReturn(['rating'=>'c']);

app()->instance(ProjectRating::class, $fakeProjectRating);

Thanks in advance



via Chebli Mohamed

Cant Upload Multiple Images In Laravel jQuery AJAX

I've stuck many days when I am trying to upload image files. I can't upload multiple images files with code below:

Controller

if ($request->TotalImages > 0) {

            for ($x = 0; $x < $request->TotalImages; $x++) {

                if ($request->hasFile('images' . $x)) {
                    $file      = $request->file('images' . $x);

                    $path = $file->store('public/product_images/');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
            }
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $insert
            ]
        );

View

<input id="images" name="images[]" type="file" multiple
                            class="form-control "
                            data-iconName="fa fa-upload" data-overwrite-initial="false">
                        <br>
var formData = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
        let images = $('#images')[0];
        for (let i = 0; i < TotalImages; i++) {
            formData.append('images' + i, images.files[i]);
        }
        formData.append('TotalImages', TotalImages);

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function() {
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            
        }); //ajax

It always show me an error:

The images field is required.

But with single upload it works!



via Chebli Mohamed

samedi 24 avril 2021

Laravel 5.6 - add extra input to login

In my users table I have a memorable_info column that contains a bcrypt value. I also have this as a field on my login form. So my login form fields in total are...

  • email
  • password
  • memorable_info

Obviously, I only want users to be logged in if they enter all 3 fields successfully. However, I cannot get it to check the memorable_info field. In my LoginController.php file, I have included the Auth facade and added the following functions...

protected function credentials(Request $request)
{
    return $request->only('email', 'password', 'memorable_info');
}

public function authenticate(Request $request)
{
    if (Auth::attempt(['email' => $request->email, 'password' => bcrypt($request->password), 'memorable_info' => bcrypt($request->memorable_info)])) {
        return redirect()->intended('dashboard');
    }
}

...however, this does not work and I constantly get the "These credentials do match our records." error.

Hoping someone has the answer on this please?



via Chebli Mohamed

How to pass the date within an array to the database in laravel

I have made the following migration in Laravel:

public function up()
{
    Schema::create('attendances', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('student_id');
        $table->date('att_date')();
        $table->string('status');
        $table->timestamps();
    });
}

My Form in Blade look like this

<form method="post" action="" enctype="multipart/form-data">
  @csrf 
  <div class="row">
    <div class="col-md-4"></div>
    <div class="form-group col-md-4">
      <strong>Date : </strong>
      <input class="date form-control"  type="text" id="datepicker" name="att_date[]">
    </div>
  </div>
  <div class="mb-3">
    <table>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Level</th>
        <th>Status</th>
      </tr>
      @foreach($students_att as $student)
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td>
            <input type="hidden" id="custId" name="student_id[]" value="">
          </td>
          <td>
            <select name="status[]">
              <option value="0">No</option>
              <option value="1">Yes</option>
            </select>
          </td>
        </tr>
      @endforeach
    </table>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>

<script type="text/javascript">
  $('#datepicker').datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd'
  });
</script>

and I have made my Controller like this:

public function sumbit(Request $request)
{
    /* $submit = new Attendance;
    $submit->student_id = $request->get('student_id');
    // $submit->att_date = $request->get('att_date');
    // $submit->status = $request->get('status');
    $submit->save();
    return redirect('att'); */

    $studentID = $request->input('student_id', []);
    $studentDate = $request->input('att_date', []);
    $studentStatus = $request->input('status', []);
    
    $students = [];
    
    foreach ($studentID as $index => $student) {
        $students[] = [
            "student_id" => $studentID[$index],
            "att_date" => $studentDate[$index],
            "status" => $studentStatus[$index],
        ];
    }
    
    $create = Attendance::insert($students);
}

so I want when i submit my form, it must be record the same date that i used by date picker to every input that show in the following image to my database image

but when i did this procedure, i got this error (ErrorException Undefined offset: 1) the error in this line in my controller line

"att_date" => $studentDate[$index],

How can Ii fix this error please help



via Chebli Mohamed

laravel orm : sort by id but put 0 values of another column at the end

I have a Products table

products: id, title, stock, price

I want new products to be at top of the list (first page), but I also want products with 0 stock to be at the end of the list (last page)

obviously, this doesn't work the way I want it, a new product with 0 stock still will show up first

Product::orderBy('id' , 'desc')->orderBy('stock' , 'desc')->paginate(20)

there are lots of similar questions but all seem to be about null values which don't work for me .. also I tried

->orderByRaw('stock = 0', 'ASC', 'id' , 'desc' )->paginate(20)

as was suggested but I get an empty collection

it's a pagination query, sort has to happen in the database, and sorting the collection after reading them from DB won't work

------------------------------------ EDIT ------------------------------------

i tried this code

Product::orderByRaw('stock = 0', 'ASC')
            ->orderBy('id' , 'desc')
            ->get()

which will generate this query in debugger

select * from `products` order by stat_view = 0, `id` desc

this code will work when i try it directly in database , but for some reason in laravel i get an empty collection .... this is an old website which is using laravel 5.2 not sure if that has anything to do with the problem

enter image description here



via Chebli Mohamed

Call to a member function subjects() on null

i'm facing an error Call to a member function subjects() on null . My project is by php and laravel. My project is on live server. Its works fine normally but when i click to edit something or click update button then it shows Call to a member function subjects() on null . Only my current browser facing this error but if i hit from another browser to my server its seems ok.

public function index()

{

    $featured_packages = Package::where('featured_package', 1)

        ->with('reviews', 'user')

        ->get();

    $popular_packages = Package::where('popular_package', 1)

        ->with(['class' => function ($query) {

            $query->pluck('name');

        }, 'reviews', 'user'])

        ->withCount('mcqs')->get();

    $class_id  = StudentClass::all()->random()->id;

    if (Auth::check()) {

        $class_id = auth()->user()->grad != '' ? auth()->user()->grad : $class_id;

    }

    $subjects = StudentClass::find($class_id)->subjects()->withCount('packages')->get();

    return view('frontend.index', compact('featured_packages', 'popular_packages', 'subjects', 'class_id'));

}

public function about()

{

    $about = About::orderBy('id', 'desc')->first();

    return view('frontend.about', compact('about'));

}

public function contact()

{

    return view('frontend.contact');

}

public function faqs()

{

    $faqs = Faq::orderBy('id', 'asc')->where('status', 1)->get()->groupBy('tab');

    return view('frontend.faqs', compact('faqs'));


via Chebli Mohamed

vendredi 23 avril 2021

Get Start and end date of Week according to string

I want to display the start date and end date of the week. I have One date and a string like 1W4 and,in 1W4 consider 4 weeks and 1 visit so, my string like this 2W4,1W2,3W3,1W1,2W4.

I want to make start date and end date of week array according to string and week start from Sunday to Saturday.

Please post me if anyone has solution.Please ignoring if mistake in asking Question.

Thank you.



via Chebli Mohamed

how can some one hack into deployed public_html directory with laravel 5.4 deployed project

i've server ubuntu with laravel 5.4 and it works fine for some time, it has cpanel and deployed on siteground, after few days, i find weird files been uploaded to the public_html directory and server stop handling requests? here's a screenshot with files been uploaded, how can i identify the problem? that can't be a code problem right? i've no idea where to look? shall i change the host? i changed the password and everything i could.

enter image description here



via Chebli Mohamed

i have problem to run laravel 5 project on local

i cloned a Laravel 5 project and try to run it . i got some errors in composer install composer update php artisan migrate

(actually all of "php aritsan" commands)

i got this error :

In Connector.php line 70:

  SQLSTATE[HY000] [2006] MySQL server has gone away  


In Connector.php line 70:

  PDO::__construct(): Error while reading greeting packet. PID=21464

i tried " php artisan clear " but i got same error .

i am trying to run this project on local . i use php 7.4 i use wamp.



via Chebli Mohamed

jeudi 22 avril 2021

How to all array inputs in laravel and displaying the validation error below of the fields

My goal here is when I hit the submit button, all fields will validate and will automatically display a validation error below of each input fields, for now when I try submitting the form without putting any data to the fields, only the first input field has an error message displaying below of the input field and the other fields does not have only after I submit the form and then I click the input fields the message will show.

I tried to look the solution here but unfortunately it doesn't work for me.

I have a form that looks like this

<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div
<div class="form-group">
  <input type="text" name="ref_name[]"> 
</div>

This is the rule/code on my request class

 'ref_name' => 'array',
 'ref_name.*' => 'required|distinct'

I'm using this https://packagist.org/packages/proengsoft/laravel-jsvalidation as my validation plugin on my laravel project.

The laravel version project im working on is 5.2



via Chebli Mohamed

How to fetch data from database if one model has relation with two models in Laravel

I'm trying to fetch data from database using Laravel eloquent but it returns no data. Here is the database structure

  • Region

    • id
    • name
  • District

    • id
    • name
    • region_id
  • Ward

    • id
    • name
    • region_id

So the ward doesn't relate with district it relates with Region. How can I get ward(data)? This is how I fetch data

Region::with('district.ward')->get();

Models

Region.php

public function district()
    {
        return $this->hasMany(District::class);
    }

public function ward()
   {
    return $this->hasMany(Ward::class);
   }

District.php

public function region()
    {
        return $this->belongsTo(Region::class);
    }

Ward.php

public function regions()
    {
        return $this->belongsTo(Region::class);
    }


via Chebli Mohamed

When i run commande composer require laravel/ui="1.*" --dev these error appears .I'm using laravel 5.4

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

Problem 1 - laravel/ui[v1.0.0, ..., v1.3.0] require illuminate/console ~5.8|^6.0 -> found illuminate/console[v5.8.0, ..., v5.8.36, v6.0.0, ..., v6.20.24] but these were not loaded, likely because it conflicts with another require. - Root composer.json requires laravel/ui 1.* -> satisfiable by laravel/ui[v1.0.0, ..., v1.3.0].

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



via Chebli Mohamed

Issue with N+1 queries with accessors when using Lighthouse GraphQL and Laravel

I'm having a bit of an issue with the old N+1 problem. I'm running Lighthouse 4.8, Laravel 5.8, and have batched_queries and batchload_relations set to true in my config. I have the hasMany and hasOne set in my schema (anonymised a little):

type Team {
    id: Int!
    Y_resource_id: Int
    X_resource_id: Int
    name: String
    description: String
    start_date: Date
    cost: Float
    Y: Resource @hasOne
    X: Resource @hasOne
    members(
        where: _ @whereConditions
        hasDepartmentMember: _ @whereHasConditions(columns: ["z_id","start_date"])
        orderBy: [OrderByClause!] @orderBy
    ): [TeamMember] @hasMany @is_logged_in
    options: [TeamResourceOption] @hasMany
    optionIds: [Int!]
}

I'm using multiple accessor functions which utilise these relationships, as well as some custom resolvers and local scopes. These seem to be the ones that are causing the N+1 issues, for example when I am loading in a Team, one of the php queries that is having the N+1 issue is this (on the Team model after trying to load a team in and populate information):

public function getHasTeamLeaderAttribute(): bool
{
    return $this->members()->teamLeaders()->count() > 0;
}

this is the members() function:

public function members(): HasMany

{
    return $this->hasMany(TeamMember::class);
}

and the on the TeamMember class:

public function scopeTeamLeaders($query)
{
    return $query->where('team_members.group_role', '=', TeamMember::ROLE_TEAM_LEADER);
}

Clockwork is showing this as 2 N+1 issues (I'm calling it twice):

N+1 queries: App\Models\Teams\Team::App\Models\Teams\TeamMember loaded 4 times.
Team.php:254
N+1 queries: App\Models\Teams\Team::App\Models\Teams\TeamMember loaded 2 times.
Team.php:254

I have tried using loadMissing in the accessor to load in the teamLeaders but this seems to increase the N+1 queries, and I have also tried loading the model with $with the relationships I need, however this makes the entire application slower (I assume because it's now autoloading it in where it's not needed).

This is an inherited project, and I'm not completely au fait with GraphQL so any pointers in the right direction would be great. Thanks!



via Chebli Mohamed

Laravel get paramater from url in blade

I want to write in blade second parameter of URL


I using this but it is not showing parameter in blade.

IN Route: Route::get('/{id}/policydetail/{urlNumber}','MerchantDashboardController@policydetail');

Exam Url:: http://127.0.0.1:8001/backoffice/5896/policydetail/2



via Chebli Mohamed

How to implement Gate/Policy @can method in laravel blade to a view component

I had implemented a Review policy using @can method in my blade.

DisplayProduct.blade

@extends('layouts.app')
@section('content')

<display-product :product="">
</display-product>

@endsection

But now I wanted to convert my blade component to vue component, so exactly how can I implement My review policy in the vue component

DisplayProduct.vue Component Snippet

            <div class="row">
                <div class="review-content ml-3 my-3"></div>
       <!-- @can method from laravel -->
                @can('delete',$review)
                some code .........
                @endcan
            </div>


via Chebli Mohamed

mercredi 21 avril 2021

Laravel + React project not working without php artisan serve command

I am working on Laravel React project on localhost when I run a command

PHP artisan serve

It is working fine on http://127.0.0.1:8000/ But when I am trying to run it without php artisan serve command and trying to access with

http://localhost/project_name

It is not working. I follow all necessary changes like

  1. Move .htaccess to root folder
  2. server.php to index.php

Not any error just blank page



via Chebli Mohamed

How to export excel data in chunk using Laravel?

Excel::create($file_name, function($excel) use ($app_data,$permit_type) {
    $excel->sheet('Sheet 1', function($sheet) use ($app_data,$permit_type) {
        $sheet->loadView('/reports/_export')->with([
            'vehicle' => $app_data,
        ]);
    });
})->export();

In above code I am simply export data in excel sheet which is working fine but due to large amount of data I am unable to export. So, I want to export this data in chunks but I don't have any idea that how to setup chunk in my code? Please help me.

Thank You



via Chebli Mohamed

Remove unmatched criteria records from Eloquent collection

I have some problems with Eloquent Eager Loading. I have added whereHas to remove the blog don't meet the comment criteria but the comment stills return empty array. My intention is to completely remove it from the json record.

How can I completely remove the json data chain that does not meet my condition?

My current code:

User::select("id", "name", "email")
    ->with(['blog', 'blog.author', 'blog.comments' => function ($query) {
        $query->where('comment', 'John is here');
    }, 'blog.comments.owner'])
    ->whereHas('blog.comments', function ($query) {
        $query->where('comment', 'John is Here');
    })
    ->get();

My current json output is:

{
    "id": 1,
    "name": "John Smith",
    "email": "john.smith@hotmail.com",
    "blog": [
        {
            "id": 1,
            "created_at": "2021-04-09T18:08:06.000000Z",
            "updated_at": "2021-04-09T10:33:03.000000Z",
            "title": "First Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": null,
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": [
                {
                    "id": 1,
                    "comment": "John is here",
                    "blog_id": 1,
                    "user_id": 1,
                    "created_at": null,
                    "updated_at": null,
                    "owner": {
                        "id": 1,
                        "name": "John Smith",
                        "email": "john.smith@hotmail.com",
                        "email_verified_at": null,
                        "created_at": "2021-04-08T13:29:13.000000Z",
                        "updated_at": "2021-04-08T13:29:13.000000Z",
                        "role": 0
                    }
                }
            ]
        },
        {
            "id": 6,
            "created_at": "2021-04-12T07:41:43.000000Z",
            "updated_at": "2021-04-12T08:01:18.000000Z",
            "title": "Second Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": "images/json_1618213303.png",
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": []
        }
    ]
}

My expected output would be:

{
    "id": 1,
    "name": "John Smith",
    "email": "john.smith@hotmail.com",
    "blog": [
        {
            "id": 1,
            "created_at": "2021-04-09T18:08:06.000000Z",
            "updated_at": "2021-04-09T10:33:03.000000Z",
            "title": "First Blog",
            "description": "Awesome",
            "users_id": 1,
            "cover": null,
            "author": {
                "id": 1,
                "name": "John Smith",
                "email": "john.smith@hotmail.com",
                "email_verified_at": null,
                "created_at": "2021-04-08T13:29:13.000000Z",
                "updated_at": "2021-04-08T13:29:13.000000Z",
                "role": 0
            },
            "comments": [
                {
                    "id": 1,
                    "comment": "John is here",
                    "blog_id": 1,
                    "user_id": 1,
                    "created_at": null,
                    "updated_at": null,
                    "owner": {
                        "id": 1,
                        "name": "John Smith",
                        "email": "john.smith@hotmail.com",
                        "email_verified_at": null,
                        "created_at": "2021-04-08T13:29:13.000000Z",
                        "updated_at": "2021-04-08T13:29:13.000000Z",
                        "role": 0
                    }
                }
            ]
        }
    ]
}


via Chebli Mohamed

mardi 20 avril 2021

Problem on show numbers : Undefined property: stdClass::$contact_id

enter image description here

enter image description here

In my address book application, a contact can have one or more phone numbers. I created a contacts table and a numbers table with the contact_id field in numbers. now i want to display all numbers of each contact in my page, but i get this error. Why?



via Chebli Mohamed

laravel sqlsrv db connection works but db::select not working

i want to connect database with sqlsrv, it works connection but query is not working , i tried this command

if(DB::connection()->getDatabaseName())
            {
               echo "Yes! successfully connected to the DB: " . DB::connection()->getDatabaseName();
            } else {
                echo "not connected";
            }


$loginData = DB::select("exec appLogin @userName = '".$request->email."', @password  = '".$request->password."'");
        $loginData = DB::select("select * from [User]");
        echo '<pre>';
        print_r($loginData);
        die;

for that i am getting success response for database connection, but when i tried DB:select command i am getting this error

[Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: No connection could be made because the target machine actively refused it.


    


via Chebli Mohamed

Get Current date time instead of local m/c date time

I want to view date and time and i am using date carbon getdate function but i am getting local machine date and time. Suppose my local machine date is 2020-03-19 then i am getting this as output from above three functions so how can i get current time and date instead of local machine date and time.` From both three linesstrong text i am getting my local machine date and time.

date_default_timezone_set('Asia/Kolkata');
    echo date('Y-m-d');
    print_r(Carbon::now());
    echo '<br/>';
    print_r(getdate());

So how can i get current date-time according to timezone instead of local machine date time?



via Chebli Mohamed

Font-awesome + core web vitals + Laravel

Pagespeed Insights is complaining about fonts loading on our website:

Preload key requests

…fontawesome-pro/webfa-brands-400.woff2?167c3d4… …fontawesome-pro/webfa-solid-900.woff2?43df9d1… …fontawesome-pro/webfa-light-300.woff2?f39d4ae…

So I looked at our app.scss and I see this:

@import '~@fortawesome/fontawesome-pro/css/all.css';

and then in the app.css it is expanded to include all of those files.

How do I tell app.scss to preload these and do I really need to load ALL of the fontawesome-pro fonts on every single page? that seems really stupid.



via Chebli Mohamed

How to join Product filter query in Laravel Controller?

   $maincategory=Maincategory::find($id);
   if (isset($_GET['brands'])) {
        $brandarray = implode(",", $_GET['brands']);
        $q->whereIn('products.brand',[$brandarray]);
    }
    if (isset($_GET['discount'])) {
        $from=min($_GET['discount']);
            if(in_array("0",$request->discount) && count($request->discount)==1){
                $to='10';
            }else{
                $to='100';
            }
        $q->whereBetween('products.discount',[$from,$to]);
    }
    if (isset($_GET['sortby'])) {
        if($_GET['sortby']=='discount'){
            $q->orderBy('products.discount', 'DESC');
        }elseif($_GET['sortby']=='hightolow'){
            $q->orderBy('products.actual_price', 'DESC');
        }elseif($_GET['sortby']=='lowtohigh'){
            $q->orderBy('products.actual_price', 'ASC');
        }else{
            $q->orderBy('products.id', 'DESC');
        }
        
    }
    if (isset($_GET['minprice'])) {
        $q->whereBetween('products.actual_price',array($_GET['minprice'],$_GET['maxprice']));
    }
    if (isset($_GET['color'])) {
        $colors = implode(",", $_GET['color']);
        $q->whereIn('products.color',[$colors]);
    }
    
    $productdata= Product::leftjoin('maincategories', 'maincategories.id', '=', 'products.main_category')
    ->leftjoin('secondcategories', 'secondcategories.id', '=', 'products.second_category')
    ->leftjoin('thirdcategories', 'thirdcategories.id', '=', 'products.third_category')
    ->leftjoin('brands', 'brands.id', '=', 'products.brand')->select('products.*', 'maincategories.id as main_category_id', 'maincategories.url as main_category_url', 'maincategories.name as main_category_name', 'secondcategories.id as second_category_id', 'secondcategories.url as second_category_url', 'secondcategories.name as second_category_name', 'thirdcategories.id as third_category_id', 'thirdcategories.url as third_category_url', 'maincategories.name as third_category_name', 'brands.id as brand_id', 'brands.name as brand_name')
    ->where('products.main_category',$maincategory->id)->$q->paginate(6);

This is my method code from the controller. It gives Error: Undefined variable: q How to solve this Error with Laravel Controller? How to join Product filter query in Laravel Controller?



via Chebli Mohamed

Upload Image In Laravel With jQuery AJAX

I am trying to upload photo in Laravel using jQuery AJAX. But it's always failed many times with error message

The photo must be an image. The photo must be a file of type: jpeg, png, jpg, gif, svg.

I have no idea why. What's wrong with my code below?

Controller

$validator = \Validator::make($request->all(), [
        'photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);
    
    if ($files = $request->file('image')) {
            //insert new file
            $destinationPath = 'public/product_images/'; // upload path
            $image_path = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $image_path);
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $image_path
            ]
        );

View

    $("#photo").fileinput({
        theme: 'fa',
        uploadUrl: '',
        uploadExtraData: function() {
            return {
                _token: $("input[name='_token']").val(),
            };
        },
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        overwriteInitial: false,
        maxFileSize: 2000,
        maxFilesNum: 5,
        slugCallback: function(filename) {
            return filename.replace('(', '_').replace(']', '_');
        }
    });
                        
    $('#saveBtnForCreate').click(function(e) {
        e.preventDefault();
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $.ajax({
            url: "",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            dataType: 'JSON',
            data: {
                photo: $('#photo').val()
            },
            success: function(result) {
                if (result.errors) {
                    $('.alert-danger').html(
                        'An error in your input!'
                    );
                    $.each(result.errors, function(key, value) {
                        $('.alert-danger').show();
                        $('.alert-danger').append('<strong><li>' + value +
                            '</li></strong>');
                    });
                } 
            }
        });
    });


via Chebli Mohamed

lundi 19 avril 2021

why EB throw me Not Found The requested URL was not found on this server?

I upload the laravel project in a zip file, and the configuration software are enter image description here

the estructure of the project is enter image description here

and the endpoint home of laravel response succesfully but if i want to call the api's throw the error Not Found The requested URL was not found on this server. i dind't have this error before but one the day start with this issue.



via Chebli Mohamed

Laravel 5.7 validation works still not

I have already asked question about Laravel 5.7 validation, however it still does not work quite right. the validation is not executed at all when sending the content.

 public function update(Request $request, Player $player)
    {
        if(Auth::check()){
                       
            $playerUpdate = Player::where('id', $player->id)
                                ->update([
                                       'first_name' => $request->input('fist_name'),
                                       'last_name' => $request->input('last_name')
                                ]);
 
            if($playerUpdate){
                return redirect()->route('players.show', ['player'=> $player->id])
                ->with('success' , 'player foo');
            }
            
 
        }
         
        return back()->withInput()->with('errors', 'Foo error');
        
        
        
    }

enter image description here

Thanks in advance



via Chebli Mohamed

Laravel 5.7 validation shows nothing

my function works by itself but the validation is not executed. Does anyone know what I forgot to add?

This is a snippet of my code:

namespace App\Http\Controllers;

use App\Player;
use App\Tournament;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


    public function store(Request $request)
    {
      $request->validate([
    'first_name' => 'alpha|min:2|max:30',
]);
        
        
        if(Auth::check()){
        
        
        
            $foo = Foo::create([
                'first_name' => $request->input('fist_name'),
                'last_name' => $request->input('last_name'),
            ]);
 
            if($foo){
                return redirect()->route('foo.show', ['foo'=> $foo->id])
                ->with('success' , 'Foo created!');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Error when creating the foo');
    }

Thanks in advance



via Chebli Mohamed

i try to show details from intermediate table through id rapport but the result is empty

public function show(RapportMP $rapportMP){
       $ligne = DB::table('ligne_rapport_m_p_s')
        ->join('rapport_m_p_s', 'ligne_rapport_m_p_s.rapportMP_id', '=', 'rapport_m_p_s.id')
        ->get()
        ->toArray();
        echo'<pre>';
        print_r($ligne) ;
       
       
}

i tried to join but nothing work the result is empty .can somoene be able to explain how can i show details of ligne_rapport through id rapport?




via Chebli Mohamed

laravel manually login works, but after redirection to home page session is not working

i am using laravel version 8, i did single signon, i created EventServiceProvider , in this provide i did login by email data, i can see by Auth::check command login is working, but when it redirected to home page Auth::check doesn't work, can anyone please help me why i am getting this issue ? here i uploaded my code, can anyone please help me how to resolve this issue ?

class EventServiceProvider extends ServiceProvider
{
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];
    public function boot()
    {
        try{
            Event::listen('Aacotroneo\Saml2\Events\Saml2LoginEvent', function (Saml2LoginEvent $event) {
                $messageId = $event->getSaml2Auth()->getLastMessageId();
                $user = $event->getSaml2User();
                $userData = [
                    'id' => $user->getUserId(),
                    'attributes' => $user->getAttributes(),
                    'assertion' => $user->getRawSamlAssertion()
                ];
                $userInfo = User::where('email',$userData['id'])->first();
                if($userInfo) {
                    //$loggedInUser = Auth::loginUsingId($userInfo->id);
                    $loggedInUser = Auth::login($userInfo);
                }
            });
        } catch (\Throwable $e) {
            echo $e->getMessage(); die;
            report($e);
        }
    }
}


via Chebli Mohamed

How to move laravel projevt from Wamp to lamp centoS 7

I need to move existing laravel 5 project to linux centos 7. I'm going to install lamp, copy source files and database backup and move them to new centos 7 server. Is there anything I should take into account? I moved a lot of pure PHP webpages but never laravel projects. Help appreciated :)



via Chebli Mohamed

Laravel 5.5 Redis - NOAUTH Authentication required

I have project in Laravel(5.5) with Redis (3.2.12). It's life project and everything is work properly. But when i am opened the logs file I found there some errors.(In .env file I alreday have REDIS_PASSWORD, FCM_SENDER_ID, FCM_SERVER_KEY) Any idea why I am getting them?

production.ERROR: `SELECT` failed: NOAUTH Authentication required. [tcp://127.0.0.1:6379] {"exception":"[object] (Predis\\Connection\\ConnectionException(code: 0): `SELECT` failed: NOAUTH Authentication required. [tcp://127.0.0.1:6379] at /var/www/html/MyProject/vendor/predis/predis/src/Connection/AbstractConnection.php:155)
[stacktrace]
#0 /var/www/html/MyProject/vendor/predis/predis/src/Connection/StreamConnection.php(263): Predis\\Connection\\AbstractConnection->onConnectionError('`SELECT` failed...', 0)
#1 /var/www/html/MyProject/vendor/predis/predis/src/Connection/AbstractConnection.php(180): Predis\\Connection\\StreamConnection->connect()
#2 /var/www/html/MyProject/vendor/predis/predis/src/Connection/StreamConnection.php(288): Predis\\Connection\\AbstractConnection->getResource()
#3 /var/www/html/MyProject/vendor/predis/predis/src/Connection/StreamConnection.php(394): Predis\\Connection\\StreamConnection->write('*2\
\
$3\
\
GET\
\
$1...')
#4 /var/www/html/MyProject/vendor/predis/predis/src/Connection/AbstractConnection.php(110): Predis\\Connection\\StreamConnection->writeRequest(Object(Predis\\Command\\StringGet))
#5 /var/www/html/MyProject/vendor/predis/predis/src/Client.php(331): Predis\\Connection\\AbstractConnection->executeCommand(Object(Predis\\Command\\StringGet))
#6 /var/www/html/MyProject/vendor/predis/predis/src/Client.php(314): Predis\\Client->executeCommand(Object(Predis\\Command\\StringGet))
#7 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(96): Predis\\Client->__call('get', Array)
#8 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(108): Illuminate\\Redis\\Connections\\Connection->command('get', Array)
#9 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Redis/RedisManager.php(140): Illuminate\\Redis\\Connections\\Connection->__call('get', Array)
#10 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(221): Illuminate\\Redis\\RedisManager->__call('get', Array)
#11 /var/www/html/MyProject/app/Http/Middleware/OperatorPhoneMiddleware.php(23): Illuminate\\Support\\Facades\\Facade::__callStatic('get', Array)
#12 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\OperatorPhoneMiddleware->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#13 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#14 /var/www/html/MyProject/app/Http/Middleware/BlockedAuth.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\BlockedAuth->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#16 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/MyProject/app/Http/Middleware/AdminLocale.php(31): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\AdminLocale->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#19 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#22 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(68): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#24 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#27 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))

FCM works correctly too, but in log i found this

production.ERROR: FCM_SENDER_ID or FCM_SERVER_KEY are invalid {"exception":"[object] (LaravelFCM\\Response\\Exceptions\\UnauthorizedRequestException(code: 401): FCM_SENDER_ID or FCM_SERVER_KEY are invalid at /var/www/html/MyProject/vendor/brozot/laravel-fcm/src/Response/BaseResponse.php:58)
[stacktrace]
#0 /var/www/html/MyProject/vendor/brozot/laravel-fcm/src/Response/BaseResponse.php(32): LaravelFCM\\Response\\BaseResponse->isJsonResponse(Object(GuzzleHttp\\Psr7\\Response))
#1 /var/www/html/MyProject/vendor/brozot/laravel-fcm/src/Response/DownstreamResponse.php(106): LaravelFCM\\Response\\BaseResponse->__construct(Object(GuzzleHttp\\Psr7\\Response))
#2 /var/www/html/MyProject/vendor/brozot/laravel-fcm/src/Sender/FCMSender.php(46): LaravelFCM\\Response\\DownstreamResponse->__construct(Object(GuzzleHttp\\Psr7\\Response), Array)
#3 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php(221): LaravelFCM\\Sender\\FCMSender->sendTo(Array, Object(LaravelFCM\\Message\\Options), Object(LaravelFCM\\Message\\PayloadNotification), Object(LaravelFCM\\Message\\PayloadData))
#4 /var/www/html/MyProject/app/Services/FcmService.php(71): Illuminate\\Support\\Facades\\Facade::__callStatic('sendTo', Array)
#5 /var/www/html/MyProject/app/Helpers/SystemHelper.php(610): App\\Services\\FcmService->notify()
#6 /var/www/html/MyProject/app/Http/Controllers/Admin/OfficeController.php(251): App\\Helpers\\SystemHelper::assignJobToDriverRedis(193, Object(App\\JobDriver), Object(App\\ServiceOrder), NULL)
#7 [internal function]: App\\Http\\Controllers\\Admin\\OfficeController->assignJobDriver(Object(Illuminate\\Http\\Request))
#8 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array(Array, Array)
#9 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction('assignJobDriver', Array)
#10 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Route.php(212): Illuminate\\Routing\\ControllerDispatcher->dispatch(Object(Illuminate\\Routing\\Route), Object(App\\Http\\Controllers\\Admin\\OfficeController), 'assignJobDriver')
#11 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Route.php(169): Illuminate\\Routing\\Route->runController()
#12 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Route->run()
#13 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#14 /var/www/html/MyProject/app/Http/Middleware/EntrustRole.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#15 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\EntrustRole->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'package_manager...')
#16 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#17 /var/www/html/MyProject/app/Http/Middleware/OperatorPhoneMiddleware.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#18 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\OperatorPhoneMiddleware->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#19 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#20 /var/www/html/MyProject/app/Http/Middleware/BlockedAuth.php(34): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#21 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\BlockedAuth->handle(Object(Illuminate\\Http\\Request), Object(Closure), 'admin')
#22 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#23 /var/www/html/MyProject/app/Http/Middleware/AdminLocale.php(31): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#24 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): App\\Http\\Middleware\\AdminLocale->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#25 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#26 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Middleware/SubstituteBindings.php(41): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#27 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Routing\\Middleware\\SubstituteBindings->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#28 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#29 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(68): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#30 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#31 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#32 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#33 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#34 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#35 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(63): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#36 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Session\\Middleware\\StartSession->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#37 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#38 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#39 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#40 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#41 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#42 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#43 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#44 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#45 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Router.php(660): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#46 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Router.php(635): Illuminate\\Routing\\Router->runRouteWithinStack(Object(Illuminate\\Routing\\Route), Object(Illuminate\\Http\\Request))
#47 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Router.php(601): Illuminate\\Routing\\Router->runRoute(Object(Illuminate\\Http\\Request), Object(Illuminate\\Routing\\Route))
#48 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Router.php(590): Illuminate\\Routing\\Router->dispatchToRoute(Object(Illuminate\\Http\\Request))
#49 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(176): Illuminate\\Routing\\Router->dispatch(Object(Illuminate\\Http\\Request))
#50 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}(Object(Illuminate\\Http\\Request))
#51 /var/www/html/MyProject/vendor/barryvdh/laravel-debugbar/src/Middleware/InjectDebugbar.php(58): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#52 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Barryvdh\\Debugbar\\Middleware\\InjectDebugbar->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#53 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#54 /var/www/html/MyProject/vendor/fideloper/proxy/src/TrustProxies.php(56): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#55 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Fideloper\\Proxy\\TrustProxies->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#56 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#57 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(30): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#58 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#59 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#60 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/TransformsRequest.php(30): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#61 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\TransformsRequest->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#62 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#63 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/ValidatePostSize.php(27): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#64 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\ValidatePostSize->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#65 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#66 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(46): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#67 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(149): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle(Object(Illuminate\\Http\\Request), Object(Closure))
#68 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}(Object(Illuminate\\Http\\Request))
#69 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}(Object(Illuminate\\Http\\Request))
#70 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(151): Illuminate\\Pipeline\\Pipeline->then(Object(Closure))
#71 /var/www/html/MyProject/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(116): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter(Object(Illuminate\\Http\\Request))
#72 /var/www/html/MyProject/public/index.php(56): Illuminate\\Foundation\\Http\\Kernel->handle(Object(Illuminate\\Http\\Request))
#73 {main}
"} 


via Chebli Mohamed

How to call program classes of one project in another project

I have a project which is divided in two different larvel project. I wanted to use the programs classes of one larvel project to another and vice versa. What is the best approch to do this ? {for simplicity our project = application-a +application-b & we wanted to make call to programs of application-a from application-b and vice versa.)

The folder structure looks like

www/
├─ application-a/
│  └─ composer.json
   └─ custom-classes/
       └─ MyClassA.php
│
├─ application-b/
│  └─ composer.json
   └─ custom-classes/
          └─ MyClassB.php

Trying to call MyClassA.php from application-b/ & MyClassB.php from application-a/(Both have similar folder naming convention and namespaces). Im trying to use psr-4 but the problem is both the projects have same namespaces prefix, So how to use psr-4 in that case. Or any other beter solution.

Thanks in advance !



via Chebli Mohamed

dimanche 18 avril 2021

How to fetch huge data in datatable using laravel?

views:

<script type="text/javascript">
    $(document).ready(function(){
        $.ajaxSetup ({
            headers: {
                'X-CSRF-TOKEN': $ ('meta[name="csrf-token"]').attr ('content')
            }
        });

        var postsTable = $ ('#example1').dataTable ({
            "ordering": true,
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": "",
                "dataType": "json",
                "type": "POST"
            },
            "columns": [
                { "data": "sn" },
                { "data": "name" },
                { "data": "username" },
                { "data": "mobile_number" },
                { "data": "designation" },
                { "data": "create_at" },
                { "data": "action" }
            ],
            stateSave: false,
        });

        $ ('.data-table-search-input-text').on ('keyup change', function () {
            var inputElement = $ (this);

            ojoDelay (function () {

                var i = inputElement.attr ('data-column');
                var v = inputElement.val ();
                postsTable.api ().columns (i).search (v).draw ();
                //usersTable.api ().ajax.reload ();
            }, 1000, this);
        });
    });  
</script>
<script>
    ojoDelay = (function () {
        var timer = 0;
        return function (callback, ms, that) {
            clearTimeout (timer);
            timer = setTimeout (callback.bind (that), ms);
        };
    }) ();
</script>

route:

Route::post('/admin/user/search', ['as' => 'admin.user.search', 'uses' => 'admin\UserController@search', 'middleware' => 'AuthPortalKas:'.serialize(['ADMIN']), 'allow' => ['ADMIN']]);

Controllers:

public function search(Request $request) 
{
    $posts = DB::table('users')
            ->select('*')
            ->leftjoin('roles', 'users.user_id', '=', 'roles.user_id')
            ->where('users.status', '!=', 'Delete')
            ->where('roles.role_id', '!=', 1)
            ->get();
    $totalData = count($posts);
    $totalFiltered = $totalData;
    $data = array();
    if(!empty($posts))
    {
        $i = 1;
        foreach ($posts as $post)
        {
            $nestedData['sn'] = $i;
            $nestedData['name'] = $post->name;
            $nestedData['username'] = $post->first_name." ".$post->last_name;
            $nestedData['mobile_number'] = $post->mobile_number;
            $nestedData['designation'] = $post->designation;
            $nestedData['create_at'] = $post->created_at;

            $buttons = '<a class="btn btn-success" href=""><i class="fa fa-search-plus"></i></a>
            <a class="btn btn-info" href=""><i class="fa fa-edit"></i></a><a class="btn btn-danger" onclick="delete_record(, )"><i class="fa fa-trash-o"></i></a>';

            $nestedData['action'] = $buttons;
            $data[] = $nestedData;
            $i++;
        }
    }

    $json_data = array(
                    "draw"            => intval($request->get('draw')),  
                    "recordsTotal"    => $totalData,  
                    "recordsFiltered" => $totalFiltered, 
                    "data"            => $data   
                );

    echo json_encode($json_data);
}

In the above question I have approx 1 million data where I want to fetch and show data in datatable but what happen here when I simply run http://localhost/project/admin/user/search then it show error. I was thinking that I have problem with my route file but I don't have any idea where am I doing wrong? Please help me to solve this.

Thank You



via Chebli Mohamed

one-time API call that triggers Larvel queue, to update the single column in the blade file

I need a progress bar for the each grid column with the Values from the query, Where the tableA contains data such as Name, goal. The Value is determined from the Table C, where the col in the TableC is not NULL. All the NON- NULL fields will be counted until the Goal is achieved.

Query:

$value = SELECT count(*) FROM tableA->Name(Table C) WHERE tableB->question != null;

I have a grid columns with the static progress widget, with the mock value.

-<div class="container">
        <div class="row justify-content-center" v-for = "TableAdata in  tableA">
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header"></div>

                    <div class="card-body">
                       <progress-widget>  </progress-widget>
                    </div>

                   <div class="card-goal">
                      <div>   </div> 
                    </div>
                  <div class="card-value">
                      <div>   </div> 
                    </div>
                </div>
            </div>
        </div>
    </div>

In the script

<script>
export default {

      data: function() {
            return {
               tableA:[],
               value: 30
            }
        },

    mounted() {
       this.loadContents();


    },
    methods: {
      loadContents: function() {
           //load Api
           axios.get('/api/tableA')
           .then((response) => {
               this.tableA = response.data;
             }}}

I have just mocked the value for all the goals. The value should be dynamic, based on the value the progress widget should be updated for the single card.

How can I do this? API call should be for individual project Name, each card. No bulk requests.

How can I make a controller to get the Value for each project? How to trigger a laravel queue to do a push ? Could anyone please help? Since I am new to laravel.

Thanks.



via Chebli Mohamed

Laravel 5.2 - Can You Create A Relationship Between A Pivot Table And A Table It's Not Pivoting For?

I have a pivot table called user_store. It's used to establish a many to many relationship between the users table and the stores table and looks something like this:

user_id - int
store_id - int
user_age_range - string

I have another table called user_memberships. It's columns look like:

user_id - int
store_id - int
membership_cost - decimal
membership_expiration - date

I need to establish a relationship between the user_memberships table and the user_store pivot table using the user_id and store_id columns present in both tables.

How would I do this when the user_store table does not have its own model (since it's a pivot table)?



via Chebli Mohamed