lundi 31 octobre 2022

Laravel taking 100% MySQL DB CPU and no jobs visible in php artisan queue:listen, Laravel 5.7

The MySQL DB CPU is running at 95%+ basically at all times, even when there's seemingly no activity in the app. It doesn't happen right away. Only once the app has been running for a while, but then it keeps at 95% CPU even once there's seemingly no activity.

The number of active sessions / connections gradually climbs from dozens to even hundreds. Looking at the MySQL processes on RDS reveals a dozen processes trying to use 8% of the DB CPU each for some reason.

I've checked for Laravel jobs via php artisan queue:listen but nothing appears.

Checked the database and query logs, and there are many DB logs which suggest a job or something occurring in a loop, but no indication as to what the source of those jobs are as the queries being ran are generic queries and could be called from many different places in the application.

We do not believe this is due to user activity, but if it is, it's some kind of user action whicih results in some kind of a server loop.

Checked application and error logs and nothing in particular stands out.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/nlCND8W
via IFTTT

when i upload laravel website form local to live sever this error that i face can any one help me

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from sessions where id = E70KsnO9rKtK9ATW71zmd9AfGW1ek7nAhnD2wQjS limit 1) error that i face

any one help me to solve this



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/XfwyF4N
via IFTTT

dimanche 30 octobre 2022

Dynamic Scopes not working properly when dealing with tags->products() (many to many relationship) Laravel Livewire

its throwing me this error:

Call to a member function products() on null

i want the filter to be changed in real time and it works too just not working properly with many to many relationship:

this doesnt work

$tag1 =  request()->query('tag');  
$tag = Tag::where('name', $tag1)->first();
$products = $tag->products()->SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage);

but when i manually type this

$products = $tag->products()->SortFilterBy('featured')->InStock()->paginate($this->perPage); //
Works But not in real time
$products = Product::SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage); //WORKS IN REAL TIME

i am using livewire for this.

The Scope:


public function scopeSortFilterBy($query,$sortBy = "")
{
switch ($sortBy) {
case 'featured':

                return $query->where('featured','=', -1);
    
                break;
    
            case 'low':
           
                return $query->orderBy('sale_price', 'asc');
               
                break;
            case 'heigh':
                return $query->orderBy('sale_price', 'desc');
                break;
            default:
    
            return $query;
            
            break;
        }
      
    }

it do shows me the value of dd($this->sortBy) whenever i change the dropdown.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LB0a6N7
via IFTTT

samedi 29 octobre 2022

Laravel clearing config causing wierd X to show up

I'm currently using laravel 5.8 in a project and stumbled on a weird problem, after lanching the commande optimize:clear a Wierd Caracheter will show up when executing any other commande and also causing ajax requests to fail here is an example of the problem enter image description here

this happening in all the team machines, not just mine. the second problem reloading a page, every time We load a page we see this screen before it redirected to the actual view
enter image description here

the only found solution is to run the commande Artisan config:cache



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/sykYgXf
via IFTTT

vendredi 28 octobre 2022

how to improve my performance for this complex query | Laravel , Datatabels

Hi everyone i have a very complex query to get Finance data, its like 4 Join and when the data is more than 1000 it getting slow when it loads in datatables how i can make it faster

this is the controller code for ajax :

  $financial_entries = FinanceEntryMod::select([
        DB::raw("ROUND(( 
            select SUM(finance_transaction.equivalent) from finance_transaction  where 
            finance_transaction.entry_id = financial_entries.id and
            finance_transaction.type = 'credit' 
        ), 2) as eqivalent_sum"),
        'financial_entries.id',
        'financial_entries.created_by',
        'financial_entries.branch_id',
        'financial_entries.order_id',
        'financial_entries.number',
        DB::raw('IFNULL(branches.name, IFNULL(v2_branches.name, "main_branch")) AS branch_name'),
        'financial_entries.v2_order_id as v2_order_id',
        'financial_entries.v2_document_id as v2_document_id',
        'financial_entries.date',
        'financial_entries.is_generated',
        'financial_entries.note',
        'financial_entries.created_at',
        'financial_entries.updated_at',
        DB::raw('
            DATE_FORMAT(financial_entries.date, "%Y-%m-%d") AS new_date,
            DATE_FORMAT(financial_entries.created_at, "%Y-%m-%d") AS new_created_at
        ')
    ])
    ->leftJoin('branches', function ($join) {
        $join->on("branches.id", "=", "financial_entries.branch_id");
    })
    ->leftJoin('finance_transaction', function ($join) {
        $join->on("financial_entries.id", "=", "finance_transaction.entry_id");
    })
    ->leftJoin('finance_accounts', function ($join) {
        $join->on("finance_accounts.id", "=", "finance_transaction.account_id");
    })
    ->leftJoin('v2_branches', function ($join) { 
        $join->on("v2_branches.id", "=", "finance_accounts.v2_branch_id"); 
    })
    ->where('financial_entries.is_deleted', '=', '0')
    ->groupBy('financial_entries.id');

and in the script : im using this

   "pageLength": 30,
        "serverSide"   : true,
        "processing"   : true,
        "columns": 

please help me to improve it thanks all



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/i4YJzuX
via IFTTT

jeudi 27 octobre 2022

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

I'm trying to use POST to let user log in with correct email/password. I keep getting this error

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('/', function () {
    return view('login');
});

Route::post("/login",[UserController::class,'login']);

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    //
    function login(request $req)
    {
        return $req->input();
    }
}

login.blade.php

@extends('master')
@section('content')
<div class="container custom-login">
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <form action="/login" method="POST">
            <div class="form-group">
                @csrf
                <labe for="exampleInputEmail">Email address</label>
                <input type="email" name="email" class="form-control" id="exampleInputEmail" placeholder="Email">
            </div>
            <div class="form-group">
                <labe for="exampleInputPassword">Password</label>
                <input type="password" name="password" class="form-control" id="exampleInputPassword" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-default">Login</button>
            </form>
        </div>
    </div>
</div>

@endsection

I tried opening the login page but POST is having issues. I expected the login page to use POST to check credentials in my database.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/IaZGujx
via IFTTT

mercredi 26 octobre 2022

I want to pull mysql export text from laravel

I want to pull mysql export text from laravel

INSERT INTO 'example' ('id', 'name') VALUES (1, 'example'), 
(2, 'example2'),
(3, 'example3'),
(4, 'example4');

Like this

Thank you.

I searched for sql query but couldn't find it



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/gGaOoJT
via IFTTT

dimanche 23 octobre 2022

JWT Token not expiring in Laravel

I have set 'ttl' => env('JWT_TTL',1), to 1 minutes so the token should expire in 1 minute but in my case it is not expiring i have run php artisan serve and cleared the cache also. Because on production server i was getting this error : Token has expired and can no longer be refreshed i was trying to debug it on my system after the token is expired.

JWT config:

<?php

/*
 * This file is part of jwt-auth.
 *
 * (c) Sean Tymon <tymon148@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

return [

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Secret
    |--------------------------------------------------------------------------
    |
    | Don't forget to set this in your .env file, as it will be used to sign
    | your tokens. A helper command is provided for this:
    | `php artisan jwt:secret`
    |
    | Note: This will be used for Symmetric algorithms only (HMAC),
    | since RSA and ECDSA use a private/public key combo (See below).
    |
    */

    'secret' => env('JWT_SECRET'),

    /*
    |--------------------------------------------------------------------------
    | JWT Authentication Keys
    |--------------------------------------------------------------------------
    |
    | The algorithm you are using, will determine whether your tokens are
    | signed with a random string (defined in `JWT_SECRET`) or using the
    | following public & private keys.
    |
    | Symmetric Algorithms:
    | HS256, HS384 & HS512 will use `JWT_SECRET`.
    |
    | Asymmetric Algorithms:
    | RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
    |
    */

    'keys' => [

        /*
        |--------------------------------------------------------------------------
        | Public Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your public key.
        |
        | E.g. 'file://path/to/public/key'
        |
        */

        'public' => env('JWT_PUBLIC_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Private Key
        |--------------------------------------------------------------------------
        |
        | A path or resource to your private key.
        |
        | E.g. 'file://path/to/private/key'
        |
        */

        'private' => env('JWT_PRIVATE_KEY'),

        /*
        |--------------------------------------------------------------------------
        | Passphrase
        |--------------------------------------------------------------------------
        |
        | The passphrase for your private key. Can be null if none set.
        |
        */

        'passphrase' => env('JWT_PASSPHRASE'),

    ],

    /*
    |--------------------------------------------------------------------------
    | JWT time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token will be valid for.
    | Defaults to 1 hour.
    |
    | You can also set this to null, to yield a never expiring token.
    | Some people may want this behaviour for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    | Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
    |
    */

    //'ttl' => env('JWT_TTL',1440),
    'ttl' => env('JWT_TTL',1),
    //'ttl' => null,

    /*
    |--------------------------------------------------------------------------
    | Refresh time to live
    |--------------------------------------------------------------------------
    |
    | Specify the length of time (in minutes) that the token can be refreshed
    | within. I.E. The user can refresh their token within a 2 week window of
    | the original token being created until they must re-authenticate.
    | Defaults to 2 weeks.
    |
    | You can also set this to null, to yield an infinite refresh time.
    | Some may want this instead of never expiring tokens for e.g. a mobile app.
    | This is not particularly recommended, so make sure you have appropriate
    | systems in place to revoke the token if necessary.
    |
    */

    //'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),
    'refresh_ttl' => null,

    /*
    |--------------------------------------------------------------------------
    | JWT hashing algorithm
    |--------------------------------------------------------------------------
    |
    | Specify the hashing algorithm that will be used to sign the token.
    |
    | See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
    | for possible values.
    |
    */

    'algo' => env('JWT_ALGO', 'HS256'),

    /*
    |--------------------------------------------------------------------------
    | Required Claims
    |--------------------------------------------------------------------------
    |
    | Specify the required claims that must exist in any token.
    | A TokenInvalidException will be thrown if any of these claims are not
    | present in the payload.
    |
    */

    'required_claims' => [
        'iss',
        'iat',
        'exp',
        'nbf',
        'sub',
        'jti',
    ],

    /*
    |--------------------------------------------------------------------------
    | Persistent Claims
    |--------------------------------------------------------------------------
    |
    | Specify the claim keys to be persisted when refreshing a token.
    | `sub` and `iat` will automatically be persisted, in
    | addition to the these claims.
    |
    | Note: If a claim does not exist then it will be ignored.
    |
    */

    'persistent_claims' => [
        // 'foo',
        // 'bar',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lock Subject
    |--------------------------------------------------------------------------
    |
    | This will determine whether a `prv` claim is automatically added to
    | the token. The purpose of this is to ensure that if you have multiple
    | authentication models e.g. `App\User` & `App\OtherPerson`, then we
    | should prevent one authentication request from impersonating another,
    | if 2 tokens happen to have the same id across the 2 different models.
    |
    | Under specific circumstances, you may want to disable this behaviour
    | e.g. if you only have one authentication model, then you would save
    | a little on token size.
    |
    */

    'lock_subject' => true,

    /*
    |--------------------------------------------------------------------------
    | Leeway
    |--------------------------------------------------------------------------
    |
    | This property gives the jwt timestamp claims some "leeway".
    | Meaning that if you have any unavoidable slight clock skew on
    | any of your servers then this will afford you some level of cushioning.
    |
    | This applies to the claims `iat`, `nbf` and `exp`.
    |
    | Specify in seconds - only if you know you need it.
    |
    */

    'leeway' => env('JWT_LEEWAY', 0),

    /*
    |--------------------------------------------------------------------------
    | Blacklist Enabled
    |--------------------------------------------------------------------------
    |
    | In order to invalidate tokens, you must have the blacklist enabled.
    | If you do not want or need this functionality, then set this to false.
    |
    */

    'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', false),

    /*
    | -------------------------------------------------------------------------
    | Blacklist Grace Period
    | -------------------------------------------------------------------------
    |
    | When multiple concurrent requests are made with the same JWT,
    | it is possible that some of them fail, due to token regeneration
    | on every request.
    |
    | Set grace period in seconds to prevent parallel request failure.
    |
    */

    'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

    /*
    |--------------------------------------------------------------------------
    | Cookies encryption
    |--------------------------------------------------------------------------
    |
    | By default Laravel encrypt cookies for security reason.
    | If you decide to not decrypt cookies, you will have to configure Laravel
    | to not encrypt your cookie token by adding its name into the $except
    | array available in the middleware "EncryptCookies" provided by Laravel.
    | see https://laravel.com/docs/master/responses#cookies-and-encryption
    | for details.
    |
    | Set it to true if you want to decrypt cookies.
    |
    */

    'decrypt_cookies' => false,

    /*
    |--------------------------------------------------------------------------
    | Providers
    |--------------------------------------------------------------------------
    |
    | Specify the various providers used throughout the package.
    |
    */

    'providers' => [

        /*
        |--------------------------------------------------------------------------
        | JWT Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to create and decode the tokens.
        |
        */

        'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

        /*
        |--------------------------------------------------------------------------
        | Authentication Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to authenticate users.
        |
        */

        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

        /*
        |--------------------------------------------------------------------------
        | Storage Provider
        |--------------------------------------------------------------------------
        |
        | Specify the provider that is used to store tokens in the blacklist.
        |
        */

        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,

    ],

];

and i have middleware also

<?php

namespace App\Http\Middleware;

use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class JwtMiddleware extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
          /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */

    try {
        $user = JWTAuth::parseToken()->authenticate();
    } catch (Exception $e) {
        if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
            return response()->json(['error' => 'Token is Invalid'],401);
        }else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
            try
            {
              $refreshed = JWTAuth::refresh(JWTAuth::getToken());
              $user = JWTAuth::setToken($refreshed)->toUser();
              $request->headers->set('Authorization','Bearer '.$refreshed);
            }catch (JWTException $e){
                return response()->json([
                    'code'   => 103,
                    'message' => 'Token cannot be refreshed, please Login again'
                ]);
            }
           // return response()->json(['error' => 'Token is Expired'],401);
        }else{
            return response()->json(['error' => 'Authorization Token not found'],401);
        }
    }
    return $next($request);
    }
    
}

Angular Auth Interceptors:

export class AuthInterceptor implements HttpInterceptor {
    constructor(private tokenService: TokenService,private _router: Router,private auth: AuthStateService, private toastr: ToastrService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        const accessToken = this.tokenService.getToken();
        req = req.clone({
            setHeaders: {
                Authorization: "Bearer " + accessToken
            }
        });
        //return next.handle(req);

        return next.handle(req).pipe(
            catchError(
              (err, caught) => {
                if (err.status === 401){
                  this.handleAuthError();
                  return of(err);
                }
                throw err;
              }
            )
          );
    }
    private handleAuthError() { 
        this.toastr.error('Warning', 'Unauthorised Access');
        this.auth.setAuthState(false);
        this.tokenService.removeToken();
        this._router.navigate(['/login'])
      }
    
}

I'm not getting 401 error but 500 error i want if the token if invalid or expired it should redirect to login Page.

Please suggest some solution, Thanks



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/0n9LQwo
via IFTTT

Can't seem to find a way to use the route.php from 5.2 from laravel 5.2 to 8.83.25 web.php

I'm pretty new with Laravel, was able to work on finding a tutorial but it uses a 5.2 version.

I'm trying to convert the older version to 8.83.25

This is the route in the tutorial that I'm following. I have created the CategoryController.php manually

Route::group(['middleware' => ['web']], function(){
    Route::get('category', 'CategoryController');
});

enter image description here



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3bsfK1w
via IFTTT

samedi 22 octobre 2022

Laravel Trying to get property of non-object $-> non Object

    public function handle()
    {
        $response = json_decode(file_get_contents(config('app.vatusa_api_base') . '/facility/zdv/roster?apikey=' . config('app.vatusa_api_key')));

        // Create Users

        foreach ($response as $user) {
            if(!User::where('vatsim_id', $user->cid)->whereNull('home_facility')->count()) {
                switch($user->rating) {
                    case 12:
                        $rating = 'ADM';
                        break;

Attempting to Pull from Our API For a Roster though it seems that I have messed something up somewhere.

Any and all help is appreciated.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/unqhKD4
via IFTTT

vendredi 21 octobre 2022

Laravel Update from 4.2 to 5.6

I'm getting the following error when running composer install:

PHP Fatal error: Uncaught ReflectionException: Class App\Console\Kernel does not exist in /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php:788 Stack trace: #0 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(788): ReflectionClass->__construct('App\Console\Ker...') #1 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(667): Illuminate\Container\Container->build('App\Console\Ker...') #2 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(265): Illuminate\Container\Container->resolve('App\Console\Ker...', Array, false) #3 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(785): Illuminate\Container\Container->Illuminate\Container{closure}(Object(Illuminate\Foundation\Application), Array) #4 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(667): Illuminate\Container\Container- in /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 788

This is what I have in my composer.json

    "require": {
            "php": "^7.1.3",
            "fideloper/proxy": "^4.0",
            "laravel/framework": "5.8.*",
            "laravel/tinker": "^1.0"
        },
        "require-dev": {
            "filp/whoops": "^2.0",
            "fzaninotto/faker": "^1.4",
            "mockery/mockery": "^1.0",
            "nunomaduro/collision": "^2.0",
            "phpunit/phpunit": "^7.0"
        }

Thanks!



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/4MCfLjs
via IFTTT

jeudi 20 octobre 2022

Cannot move image/files temp to public directory Laravel 9

I am trying to upload image in Laravel. Getting following error:

enter image description here

My code is given below:

public function uploadImage($image, $image_path)
{
    $path = config('global.' . $image_path . '_image_path');

    file_exists($image) && unlink($image);

    $image_name = 'bvend-' . $image_path . '-' . time() . '.' . $image->getClientOriginalExtension();

    $image->move($path, $image_name); // $path: public_path('uploads/products')
    return $image_name;
}

I understand its a simple issue but still no clue where it causing issue.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/CtvRhU1
via IFTTT

after updating PHP to 7.4 my BarcodeGeneratorHTML crashed | Laravel,PHP

i used to use my Laravel Project with PhP 5.6 and i'm using barcode Gnerator for my project some where and to do this i use this package .

laravel/laravel barcode_blog

now i upgraded my PhP To 7.4 (note: didn't upgrade my laravel yet). everything is working fine just when i search for a spasific barcode i got this error :

ErrorException in BarcodeGenerator.php line 293: 
Array and string offset access syntax with curly braces is deprecated (View:.../.../..)

now this is the code :

<tr>
    <td width="19%">serial NUM</td>
    <td style="width: 1%">:</td>
    <td colspan="2">
     @if (!empty($INSTANCE))
       <?php $generator = new \Picqer\Barcode\BarcodeGeneratorHTML(); ?>
       {!! $generator->getBarcode($INSTANCE->barcode, $generator::TYPE_CODE_128) !!}
    @endif
    </td>
   </tr>

And I know the problem is with $generator = new \Picqer\Barcode\BarcodeGeneratorHTML(); this line when i delete it my code is working fine but i need it in the code how to use it in php 7.4 i belive it get changed



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/JyVZPmc
via IFTTT

mercredi 19 octobre 2022

How to get duplicate records according to name, date range and status exactly?

I am trying to get the duplicate records that match a date range and according to their state field exactly.

I am trying with the following query

$datos = DB::table('especialidades')
                        ->select('id','uuid','nombre','created_at')
                        ->orderBy('nombre')
                        ->whereIn('nombre', function($q){
                            $q->select('nombre')
                              ->from('especialidades')
                              ->groupBy('nombre')
                              ->havingRaw('COUNT(*) > 1');
                        })                       
                        ->where('created_at', '>=', '2022-10-18')
                        ->where('created_at', '<=', '2022-10-20')
                        ->where('estado', 6)
                       ->get();

And it returns the following results enter image description here

I must show exactly when they are:

  1. The record has duplicates
  2. Duplicate records are on the same date
  3. All duplicate records have the same status.

If it does not exactly meet these 3 conditions, it should not be displayed.

As you will see in the image of the records, those in red

  1. They have duplicates
  2. Some duplicates of the record are in different date ranges, so it should not be displayed.
  3. Some duplicates of the record are in different states, so it should not show it.

The correct result should have been the ones highlighted in green, since they meet the 3 conditions exactly.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/vPYcfJK
via IFTTT

Convert Raw Sql to laravel Query buider format

I have a raw query which works correctly.

SELECT a.date_demande,a.row, a.nom,a.prenom,a.timestamp_statut,a.timestamp_statut_fmt,a.dossier_id_rapproche,a.type_enquete,
a.enquete_statut,a.code_couleur,a.code,a.type_demande_libelle, a.type_demande_couleur,a.type_demande_code,a.type_demande_icone,a.type_demande_contester,
a.type_demande_contester,a.date_demande_origin,a.date_demande,a.dossier_id, a.prestataire_equipe, a.ref_client, a.client,a.standalone,a.demandeur,
a.lieu_naissance,a.lieu_deces,a.no_boite_lettre,a.cp,a.ville,b.Phone FROM
(select
  distinct `dossiers`.`id`,
  `dossiers`.`id` as `row`,
  `nom`.`originalValue` as `nom`,
  `prenom`.`originalValue` as `prenom`,
  `dossiers`.`timestamp_statut` as `timestamp_statut`,
  DATE_FORMAT(timestamp_statut, "%d/%m/%Y") AS timestamp_statut_fmt,
  `dossiers`.`dossier_id_rapproche` as `dossier_id_rapproche`,
  CONCAT(t1.type_enquete, ' - ', t1.lib_type_enquete) as type_enquete,
  `enquete_statuts`.`libelle` as `enquete_statut`,
  `enquete_statuts`.`code_couleur` as `code_couleur`,
  `enquete_statuts`.`code` as `code`,
  `type_demande_client`.`libelle` as `type_demande_libelle`,
  `type_demande_client`.`code_couleur` as `type_demande_couleur`,
  `type_demande_client`.`code` as `type_demande_code`,
  `type_demande_client`.`icone` as `type_demande_icone`,
  `type_demande_client`.`contester` as `type_demande_contester`,
  `date_demande` as `date_demande_origin`,
  DATE_FORMAT(date_demande, "%d/%m/%Y") AS date_demande,
  `affectation`.dossier_id AS dossier_id ,
  `affectation`.prestataire_equipe AS prestataire_equipe ,
  `ref_client`,
  `clients`.`nom_raison_sociale` as `client`,
  `clients`.`standalone` as `standalone`,
  `clients`.`demandeur` as `demandeur`,
  CONCAT(t2.type_enquete, ' - ', t2.lib_type_enquete) as `type_enquete_retrouve`,
  (
    CASE
      WHEN date_de_naissance.originalValue not like "%/%/%" THEN DATE_FORMAT(`date_de_naissance`.`originalValue`, "%d/%m/%Y")
      ELSE date_de_naissance.originalValue
    END
  ) AS date_naissance,
  `lieu_de_naissance`.`originalValue` as `lieu_naissance`,
  (
    CASE
      WHEN date_de_deces.originalValue not like "%/%/%" THEN DATE_FORMAT(`date_de_deces`.`originalValue`, "%d/%m/%Y")
      ELSE date_de_deces.originalValue
    END
  ) AS date_deces,
  `lieu_de_deces`.`originalValue` as `lieu_deces`,
   `adresse_bp`.`originalValue` as `no_boite_lettre`,
  (
    CASE
      WHEN code_postal_particulier.originalValue is not null
      AND ville_particulier.originalValue is not null THEN code_postal_particulier.originalValue
      WHEN code_postal_professionnel.originalValue is not null
      AND ville_professionnel.originalValue is not null THEN code_postal_professionnel.originalValue
      ELSE code_postal_particulier.originalValue
    END
  ) as cp,
  (
    CASE
      WHEN code_postal_particulier.originalValue is not null
      AND ville_particulier.originalValue is not null THEN ville_particulier.originalValue
      WHEN code_postal_professionnel.originalValue is not null
      AND ville_professionnel.originalValue is not null THEN ville_professionnel.originalValue
      ELSE ville_particulier.originalValue
    END
  ) as ville
from
  `dossiers`
  left join `index_dossiers` as `nom` on `dossiers`.`id` = `nom`.`dossier_id`
  and `nom`.`zone` = 'etat_civil.nom'
  left join `index_dossiers` as `prenom` on `dossiers`.`id` = `prenom`.`dossier_id`
  and `prenom`.`zone` = 'etat_civil.prenom'
  left join `index_dossiers` as `date_de_naissance` on `dossiers`.`id` = `date_de_naissance`.`dossier_id`
  and `date_de_naissance`.`zone` = 'etat_civil.date_naissance'
  left join `index_dossiers` as `lieu_de_naissance` on `dossiers`.`id` = `lieu_de_naissance`.`dossier_id`
  and `lieu_de_naissance`.`zone` = 'etat_civil.lieu_naissance'
  left join `index_dossiers` as `date_de_deces` on `dossiers`.`id` = `date_de_deces`.`dossier_id`
  and `date_de_deces`.`zone` = 'etat_civil.date_deces'
  left join `index_dossiers` as `lieu_de_deces` on `dossiers`.`id` = `lieu_de_deces`.`dossier_id`
  and `lieu_de_deces`.`zone` = 'etat_civil.lieu_deces'
  left join `index_dossiers` as `code_postal_particulier` on `dossiers`.`id` = `code_postal_particulier`.`dossier_id`
  and `code_postal_particulier`.`zone` = 'adresses.particulier_cp'
  left join `index_dossiers` as `code_postal_professionnel` on `dossiers`.`id` = `code_postal_professionnel`.`dossier_id`
  and `code_postal_professionnel`.`zone` = 'adresses.professionnel_cp'
  left join `index_dossiers` as `ville_particulier` on `dossiers`.`id` = `ville_particulier`.`dossier_id`
  and `ville_particulier`.`zone` = 'adresses.particulier_ville'
  left join `index_dossiers` as `ville_professionnel` on `dossiers`.`id` = `ville_professionnel`.`dossier_id`
  and `ville_professionnel`.`zone` = 'adresses.professionnel_ville'
   left join `index_dossiers` as `adresse_bp` on `dossiers`.`id` = `adresse_bp`.`dossier_id`
  and `adresse_bp`.`zone` = 'adresses.particulier_no_boite_lettre'
   left join `index_dossiers` as `telephone` on `dossiers`.`id` = `telephone`.`dossier_id`
  and `telephone`.`zone` = 'telephones.numtel'
  inner join `entites` as `e1` on `dossiers`.`entite_id` = `e1`.`id`
  inner join `clients` on `clients`.`entite_id` = `e1`.`id`
  left join `enquete_statuts` on `dossiers`.`enquete_statut_id` = `enquete_statuts`.`id`
  left join `type_demande_client` on `dossiers`.`type_demande_client_id` = `type_demande_client`.`id`
  inner join `type_enquetes` as `t1` on `dossiers`.`type_enquete_id` = `t1`.`id`
  left join `type_enquetes` as `t2` on `dossiers`.`type_enquete_id_retrouve` = `t2`.`id`
  left join `sous_enquetes` as `se` on `dossiers`.`id` = `se`.`dossier_id`
  left join `affectation_dossiers` on `se`.`id` = `affectation_dossiers`.`sous_enquete_id`
  left join (
    SELECT
      sous_enquetes.dossier_id,
      GROUP_CONCAT(
        case
          when users.name IS NOT NULL then users.name
          ELSE case
            when equipes.libelle IS NOT NULL then equipes.libelle
            when prestataires.nom_raison_sociale IS NOT NULL then prestataires.nom_raison_sociale
          End
        END
      ) AS prestataire_equipe
    FROM
      affectation_dossiers
      JOIN sous_enquetes ON affectation_dossiers.sous_enquete_id = sous_enquetes.id
      LEFT JOIN users ON affectation_dossiers.user_id = users.id
      LEFT JOIN entites AS e ON affectation_dossiers.entite_id = e.id
      LEFT JOIN equipes ON e.id = equipes.entite_id
      LEFT JOIN prestataires ON e.id = prestataires.entite_id
    GROUP BY
      sous_enquetes.dossier_id
  ) AS affectation on `dossiers`.`id` = `affectation`.`dossier_id`
where
  `date_demande` is not NULL) AS a
  
  INNER JOIN
  
(  SELECT 
    `dossier_id`,
    GROUP_CONCAT(`originalValue`) AS `Phone`
FROM `index_dossiers`
WHERE zone = 'telephones.numtel'
GROUP BY `dossier_id`) AS b

ON a.row = b.dossier_id

I am able to write each part of the query which returns a and b seperately as query builder. I am however unable to get both to work together.

Any help or tips would be appreciated. I have tried using some online tools but to no avail I can run the query with DB::select(DB:raw('query') to get the correct results. However the results are returned as an array. The expected output is an instance of query builder for further filtering.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/NYZc841
via IFTTT

Call to undefined function Collective\Html\is_iterable()

`(2/2) ErrorException Call to undefined function Collective\Html\is_iterable() (View: /home/finocoin/public_html/mocktest/Themes/themeone/views/exams/quiz/update-questions.blade.php)

in FormBuilder.php (line 741) at CompilerEngine->handleViewException(object(FatalThrowableError), 1) in PhpEngine.php (line 47)`



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/vfgGiQE
via IFTTT

lundi 17 octobre 2022

Advise for Laravel multi tenant SSL

I was planning to build a multi tenant (Saas) by using laravel. In my application context, every stores that created from my application will automatically be issued a sub domain with the SSL for that sub domain and users are allowed to user their own domain with their own SSL.

But there’s one issue here, how I am going to generate that sub domain free SSL automatically and also allows users to upload their SSL certificates files. My current tech stack is using NGINX, laravel and NextJS.

I have broken down my Saas platform to become completely isolated frontend and backend. In fact, the sub domain is served by the NextJS.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/UJrc92R
via IFTTT

Validating filename of uploaded file in Laravel 5.4

How can I validate the filename of uploaded image file?

The scenario is:

When a user upload an image the filename must its id, if not then it will throw an message that the filename must the user id.

This is my code:

    $validation = Validator::make($request->all(), [
            'documenttosubmit' => 'required|array',
            'datesubmitted' => 'required|array',
            'file' => 'array',
            'file.*' => 'mimetypes:' . implode(",", $allowedMimes) . '|max:' . (AppDocSubmitted::MAX_FILE_SIZE * 1024), 
        ], [
            'file.*.mimetypes' => 'File must be an image (jpg/jpeg/png) or a document (pdf).',
            'file.*.max' => 'File size must be less than the maximum size of ' . AppDocSubmitted::MAX_FILE_SIZE . 'MB',
        ]);


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/0ZuW63a
via IFTTT

Laravel 9 - How to validate user with sanctum in Request

I have a route with the sanctum middleware, the idea of ​​this route is that only those users with a token can access it.

If I make a call with a correct token, the method works, if I try to make the query with an INVALID token, it returns an error that I can't control.

What I try by code is that if the token is not valid, it returns a 401 (unauthorized)

Route

Route::middleware('auth:sanctum')->post('cars', [CarsController::class, 'videoStore'])
    ->name('api.cars.store');

Request

 /** 
 * @param CarStoreRequest $request
 * @return Application|ResponseFactory|\Illuminate\Http\Response
 */
 public function carStore (CarStoreRequest $request)
 {

     $user = Auth::user();

     if ($user === null) {
         return response('Unauthorized', Response::HTTP_UNAUTHORIZED);
    }
 }

API action

<?php

namespace App\Http\Requests\V1;

use Illuminate\Foundation\Http\FormRequest;

class CarStoreRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'image' => 'required|mimes:jpeg,jpg|max:30000',
        ];
    }
}

This is the error received with 401 http status code.

{
    "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
    "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php",
    "line": 1151,
    "trace": [
        {
            "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\helpers.php",
            "line": 45,
            "function": "abort",
            "class": "Illuminate\\Foundation\\Application",
            "type": "->"
        },
        {
            "file": "C:\\xampp\\htdocs\\test-api\\app\\Exceptions\\Handler.php",
            "line": 56,
            "function": "abort"
        },


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/fslw93U
via IFTTT

why .env file configuration in laravel is not working it can't work

$this->ketnoi = mysqli_connect($_ENV['DB_HOST'], $_ENV['DB_USERNAME'], $_ENV['DB_PASSWORD'], $_ENV['DB_DATABASE']) or die('Error => DATABASE');



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3eXmVcu
via IFTTT

dimanche 16 octobre 2022

Weird error when trying to send MAIL Laravel. Address in mailbox given [] does not comply with RFC 2822, 3.6.2

So i'm trying to send an email to a fixed email address

Here is the code :

        //This piece of code is executed when i press a button inside an HTML form
        $announcement = $request->input("announcement");     //This comes from an HTML text input
        $subject = "Hello this is the title of the email";
        $data = [
                'email_body' => "This is the body of the email where the message is displayed : <br><br>".$announcement
        ];

        Mail::send('emails.email_view', $data, function ($message) use ($subject) {
                $message->from(env("MAIL_FROM_ADDRESS"), 'Some name');
                $message->to("validEmail@gmail.com")->subject($subject);
        });

When this piece of code is executed it shows me the error mentioned in the title :

Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

The thing is when i refresh the page(url) where the error is displayed it obviously prompts me to Confirm Form Resubmission and when i confirm, the code is executed without a problem , sending the email as it is supposed to do in the first place.

I've tried storing the email in a variable and using trim() or str_replace() to clear the string from possible whitespace, i've tried sending it inside the to() function as an array as mentioned in a question about the same problem still no luck.

Also the code 1 out of 40 tries doesn't display the error and works as supposed to work.

Im' using laravel 5.5

I'm so lost what should i do, where should i look ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xr4kEB3
via IFTTT

samedi 15 octobre 2022

Send notification to creator on the basis of post page views in laravel?

I want to send the notification to the post creator on the basis of page views in laravel. Like when the post gets 1000 views, the creator should get a congratulatory notification. Here the problem is I am using cookies(2 hours) to prevent multiple page views. so the creator gets multiple notifications until views are moved to 1001.

if($views == 1000){
        $user = User::find($userid);
        $notificationdetails = [
          'subject' => 'Congratulations, You got your first '.$views. ' views on your new snippet - '.$snippet_title,
          'greeting' => 'Hi, '.$user->name,
          'body' => 'Congratulations, You got your first '.$views. ' views on your new 
     snippet - '.$snippet_title,
          'body1' =>'',
          'thanks' => ' ',
          'actionText' => 'View snippet',
          'actionURL' => url(env('FRONTEND_URL').'/snippets/'.$slug)
                 ];
          Notification::send($user, new BBBnotifications($notificationdetails));

    }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/tQanZPY
via IFTTT

mercredi 12 octobre 2022

composer 1 out of memory - impossible to update to 2

Everytime I try to install a new package on my webserver, I run into composer error (after very long delay). What is the solution? What is the work around?

 pgodard@dedi13:~/public_html$ composer require setasign/fpdf:^1.8
 Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
 Info from https://repo.packagist.org: #StandWithUkraine
 ./composer.json has been updated
 Loading composer repositories with package information
 Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
 Info from https://repo.packagist.org: #StandWithUkraine
 Updating dependencies (including require-dev)
 
 Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 12288 bytes) in phar:///usr/bin/composer/src/Composer/DependencyResolver/RuleSetGenerator.php on line 64
 
 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more infopgpgppgodard@dedi13:~/public_html$ 

If I try to update composer, I get another error...

pgodard@dedi13:~/public_html$ composer selfupdate --2
Updating to version 2.4.2 (2.x channel).
Downloading (100%)                                                
[Composer\Downloader\FilesystemException]                            
Filesystem exception:                                                
Composer update failed: "/usr/bin/composer" could not be written.    
rename(/usr/bin/composer): Failed to open stream: Permission denied  
 

On my local webserver on my mac, it works 100%.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/pFYBaen
via IFTTT

Laravel show pdf file in mobile device

I'm working on Laravel project where I have private url for pdf file like: http://10.10.1.10/dummy.pdf When I am using iframe to show pdf in mobile device, it is showing me download option instead showing pdf. I also checked online their peoples are suggesting google pdf viewer but due to private pdf url I cannot use the same. Please suggest a way that how can I achieve the same.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/Rvu9ECP
via IFTTT

mardi 11 octobre 2022

fill dynamic input with select html

I am trying to make a dynamic form which consists of being able to add rows dynamically and the same with a select I take the values ​​of the select and put them in the inputs of the first row, I would like to know how to fill in the other selects because it only works for me with the first row my select

enter image description here

function cambioOpciones(e) {
  const combo = document.getElementById('opciones'),
    [FECHA, MONEDA, NUMCTA, FAMILIA, CONCEPTO, FACTURA, DENOMINACION_SOCIAL, VENDEDOR] = document.getElementById('opciones').value.split('_');
  document.getElementById('fecha').value = FECHA;
  document.getElementById('moneda').value = MONEDA;
  document.getElementById('numcta').value = NUMCTA;
  document.getElementById('familia').value = FAMILIA;
  document.getElementById('Concepto').value = CONCEPTO;
  document.getElementById('showId').value = FACTURA;
  document.getElementById('denominacion').value = DENOMINACION_SOCIAL;
  document.getElementById('vendedor').value = VENDEDOR;
}

$(document).ready(function() {
  let row_number = 1;
  $("#add_row").click(function(e) {
    e.preventDefault();
    let new_row_number = row_number - 1;
    $('#venta' + row_number).html($('#venta' + new_row_number).html()).find('td:first-child');
    $('#ventas_table').append('<tr id="venta' + (row_number + 1) + '"></tr>');
    row_number++;
  });
  $("#delete_row").click(function(e) {
    e.preventDefault();
    if (row_number > 1) {
      $("#venta" + (row_number - 1)).html('');
      row_number--;
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<td>
  <select name="products[]" class="form-control" id="opciones" onchange='cambioOpciones();'>
    @foreach ($ventas1 as $ventas)
    <option value="_______">
      ---
    </option>
    @endforeach
  </select>
</td>


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/cQVDxb8
via IFTTT

Yajra datatable regenerate issue in Laravel 6

I am using laravel 6 and trying to regenerate yajra datatable by following

    var dataTable = $('#my_list').dataTable();
    dataTable.fnDestroy();
    getMyList();

It's working. But First of all it shows broken table(during data population) after that table become nicely visible. Here is my data-table configuration

DataTable({
       iDisplayLength: 15,
       processing: true,
       serverSide: true,
       lengthChange: false,
       searching: true,
       paging: true,
       ajax: 

How can I overcome this or introduce preloader during fetching data



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/q0B9liF
via IFTTT

lundi 10 octobre 2022

How to Only Show Video in Instagram Embed Code?

I am using Laravel 5 and My client wants me to set and input in his admin page to add embedded Instagram videos code.

But does not want to show title, likes and other information.

Just plain video with autoplay.

I found out that you can just eliminate those pieces in the code Instagram gives you but my client just want to copy-paste.

Is there a way around this?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/uGFmChw
via IFTTT

jeudi 6 octobre 2022

Laravel mailer single authentication

I use Laravel 5.8.
In one of my scripts, a mail might be sent inside a very big loop. I use the following code :

Mail::send("myTemplate", $data, function (Message $m) use ($toAddress, $emailSubject) {
    $m->from(env("MAIL_USERNAME"), env("MAIL_FROM_NAME"));
    $m->to($toAddress, $toAddress)->subject($emailSubject);
});

My problem is that in some moment email server complains about too many authentications, and reject attempt to send mail.

Is there any way to avoid authentication on each delivery, and instead having one single authentication?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/MKYVh8q
via IFTTT

I'm working on frontend and Backend is in php laravel, the string are getting truncate, I don't know why? [closed]

 <div class="overview_content">
     <p class="view_paras">
              {!!ucfirst( str_replace('</p><p>','<br>',$course->overview))!!}
                    
        </p>
  </div>

Code look like this -

This is the structure been followed.

And the result is like in image - enter image description here

For more clear code - enter image description here



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/LQ3logv
via IFTTT

mercredi 5 octobre 2022

How to run Laravel 8 on MAMP?

I have this in my composer.json

"require": {
    "php": "^8",
    "alkhachatryan/laravel-web-console": "^3.3",
    "barryvdh/laravel-dompdf": "^0.9.0",
    "doctrine/dbal": "^2.10",
    "fideloper/proxy": "^4.2",
    "fruitcake/laravel-cors": "^1.0",
    "guzzlehttp/guzzle": "^6.3",
    "intervention/image": "^2.3",
    "laravel/framework": "^8",
    "laravel/tinker": "^2.0",
    "laravelcollective/html": "~6.0",
    "league/flysystem-aws-s3-v3": "~1.0",
    "pusher/pusher-php-server": "^4.1"
},

I'm trying to run my Laravel app via MAMP v6.6

I kept getting

Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.1.0". You are running 8.0.8. in /Users/laravel-app/vendor/composer/platform_check.php on line 24

macOS 12.3

php --version

PHP 8.1.8 (cli) (built: Jul 8 2022 10:46:35) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.8, Copyright (c) Zend Technologies with Zend OPcache v8.1.8, Copyright (c), by Zend Technologie



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/PLrlhsX
via IFTTT

I want to upload word document and view data in a text box using laravel

I created a form that user can enter the data in a text box and generate word document. Now I want to upload a word document and view the data in a text box. how can I do that using php in Laravel?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/yMR3W7Z
via IFTTT

mardi 4 octobre 2022

Wrong date and time showed

With this line:

<td><% district.created_at %></td>

I'm getting this output:

2022-08-06T09:14:58.000000Z

It should be like this:

2021-12-30 13:19:22

The correct printout is from Laravel 5.3 and the wrong from Laravel 9. What could be the problem and how to correct?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/xWsNMFz
via IFTTT

lundi 3 octobre 2022

Disable dropdown in Laravel Blade

I have this dropdown i want to make it read only or disable

 

tried disabled also

 

but i want to disable options only the option that is pre-selected should be saved in database, using readonly i can change the dropdown and using disable i can't get its value.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/6KWyS7m
via IFTTT

dimanche 2 octobre 2022

Laravel modular not routes with module

I am using "artem-schander/l5-modular": "^2.1" in laravel 6 . Package successfully installed. Also created a module name Employee. when I hit url like

<a href="" >Employee</a>

route (App/Modules/Employee/web.php)

Route::group(['module' => 'Employee', 'middleware' => ['auth'], 'namespace' => 'App\Modules\Employee\Http\Controllers'], function () {

     Route::get('employee-list', 'EmployeeController@welcome');
});

It shows 404 Not Found . How can I link it with module route ?



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/yQloDke
via IFTTT

samedi 1 octobre 2022

Searching with multiple tables in laravel

I have this search query

 $products = Product::query()
            ->where('name', 'LIKE', "%{$search}%")
            ->orWhere('slug', 'LIKE', "%{$search_any}%")
            ->where('status', 'Active')
            ->get();

i have user table which stores the user who listed the product and its relation is as follows

Product Model:

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

I have one field type in user table, i want if user enters search string matches type also then also all the products added by them should be returned i was trying this code but how can i combine both the queries

 $products = Product::query()
                ->where('name', 'LIKE', "%{$search}%")
                ->orWhere('slug', 'LIKE', "%{$search_any}%")
                ->where('status', 'Active')
                ->get();
 $productsAddedByUser = User::where('type', 'LIKE', "%{$search_any}%")->get();
// saved $productsAddedByUser result in this array $userIdarray
$productnew = Product::whereIn('user_id', $userIdarray)->get();

I want to combine both the results of $productnew and $products



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/PA7NcQM
via IFTTT