jeudi 30 juin 2022

How to allow websockets through a Laravel 5.8 maintenance page?

I need to allow websockets wss:// through the maintenance mode with Laravel 5.8 as:

php artisan down --allow=xxx.xxx.xx.xx




php artisan down --allow=127.0.0.1

But no luck.

Any clever ideas please? Is there a way to allow on Laravel 5.8 a protocol like wss:// ? I cannot work out why the Laravel maintenance page blocks it. As soon as it is up, the websockets work again.

Thanks



via Chebli Mohamed

Laravel 5.4 - remember me and custom session values issue

I get project that has custom values in sessions. I use Remember me option, and every time when session is expired, new session is created (regenerated).

Now, I have problem because I need to keep all data from main session (first created) and keep values for all time that user is logged in .

Example:

if (Auth::attempt(['email' => $email, 'password' => $password], $rememberMe)) {
    $data = [
        'unread_messages'         => $message->unread_messages,
        'unread_worker_messages'  => $message->unread_worker_messages,
        'unread_poll'             => $message->unread_poll
        ];
        
        session(['num_unread_message' => $data]);
}

Now, when the session is expired after 2 hours, user will be logged, because Remember me is TRUE, but the values in Session get vanished.

I need to keep all of values in the new session that will be created after regeneration.



via Chebli Mohamed

mardi 28 juin 2022

Pusher In Laravel With Apiato

I Try manythinhg but still got error in pusher. This is very Common Error. Pusher/Pusher class not found. I try below i mention.

add class in config/app line 253) code : 'Pusher' => Pusher\Pusher::class

composer dump-autoload -> Output 0

Vendor directory delete -> composer install-> composer update

Accroding blog https://stackoverflow.com/questions/45052853/class-pusher-not-found-> PusherBroadCaster search and rename with Pusher-> output 0

Try to install pusher 7.0 output = error

Add Manually path->composer update-> output 0 and I Am use Laravel '5.5' with apiato core '2.2.6' and my pusher package version is '2.6'



via Chebli Mohamed

lundi 27 juin 2022

real time - browser

i have a problem, my search engine only searches with a particular Model

Model: 'Registro'

 public function search(Request $request){
        
        $results = Registro::where('cliente', 'LIKE', "%{$request->search}%")->get();
        
        return view('posts.results', compact('results'))->with(['search' => $request->search])->render();
        
    }

How can I make the search engine work with more Models?



via Chebli Mohamed

dimanche 26 juin 2022

Laravel RefreshDatabase doesn't work in testing

In order to move my current Laravel 5.5 project to the latest version, I was trying to setup some tests (I've never done that before).

To do so, I added <env name="DB_CONNECTION" value="mysql_testing" /> in the phpunit.xml, under the <php> section, and created a copy of the current mysql configuration under config/database.php naming it mysql_testing, which has 'database' => env('DB_NAME_TESTING', 'forge') .

In the .env file I put DB_NAME_TESTING=testDB. The database exists, is empty and the user has all permissions on it.

I haven't created any Test, yet, just tried the Examples provided by Laravel. If I run the tests as they are, they all pass. If I add the RefreshDatabase trait on them, instead, I get

ErrorException : Trying to access array offset on value of type int
C:\[path to project]\vendor\symfony\console\Input\ArrayInput.php:135

which corresponds to } elseif ('-' === $key[0]) {.

After a bit of tracing, I found out that the $key is 'migrate:fresh', which is the Artisan command that RefreshDatabase is trying to run. In later versions this segment has been replaced with } elseif (str_starts_with($key, '-')) {, but this is only available since PHP 8, and I'm currently stuck with PHP 7.4.

My question now is: what am I doing wrong in setting up my testing database?



via Chebli Mohamed

samedi 25 juin 2022

ErrorException Undefined variable: users (View: resources\views\admin\dashboard.blade.php)

hi I wants to show users list into my dashboard pannel but it shows me this problem :

ErrorException Undefined variable: users (View: resources\views\admin\dashboard.blade.php)

Controller File :

 public function index()
{
    $listuser = User::all();
    return view('admin.dashboard',['users' => $listuser]);
    //return view('admin.dashboard')->with('users', $listuser);
}

blade file :

 <div id="utilisateurs">
                            <table width="100%" cellspacing="0" border="1">
                                    <thead>
                                        <tr>
                                            <th>Id</th>
                                            <th>Nom et Prenom</th>
                                            <th>Email</th>
                                            <th>tele</th>
                                            <th>adresse</th>
                                            <th>date de creation</th>
                                            <th>Statut de compte</th>
                                        </tr>
                                    </thead><br>
                                    <tbody>
                                        
                                        @foreach($users as $user)
                                            @if($user->role_as=='0')
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td>Null</td>
                                        </tr>
                                            @endif
                                        @endforeach
                                    </tbody>
                            </table>
                        </div>

Routes :

  Route::middleware(['auth','isAdmin'])->group(function() {
Route::get('/dashboard','Admin\FrontendController@index');


/*users routes*/
Route::get('/dashboard', 'UserController@index');


via Chebli Mohamed

vendredi 24 juin 2022

I install the flutterwave package in laravel 8 and 9 but facing this issue

i run this command

composer install flutterwavedev/flutterwave-v3

give me this error.

Invalid argument flutterwavedev/flutterwave-v3. Use "composer require flutterwavedev/flutterwave-v3" instead to add packages to your composer.json.

when we run this command "composer require flutterwavedev/flutterwave-v3".

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

Problem 1 - flutterwavedev/flutterwave-v3 1.0.0 requires monolog/monolog 1.* -> found monolog/monolog[1.0.0-RC1, ..., 1.x-dev] but the package is fixed to 2.6.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. - flutterwavedev/flutterwave-v3 1.0.1 requires vlucas/phpdotenv ^2.5 -> found vlucas/phpdotenv[v2.5.0, ..., 2.6.x-dev] but the package is fixed to v5.4.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. - Root composer.json requires flutterwavedev/flutterwave-v3 ^1.0 -> satisfiable by flutterwavedev/flutterwave-v3[1.0.0, 1.0.1].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require flutterwavedev/flutterwave-v3:*" to figure out if any version is installable, or "composer require flutterwavedev/flutterwave-v3:^2.1" if you know which you need.

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



via Chebli Mohamed

Call to a member function links() on array_push in laravel

I'm sending the two different queries resulting in one parameter using the array push method that time laravel pagination is not working. Without pagination queries working fine. I don't know what was the issue please help me how to fix this issue

My Query

public function searchProduct(Request $request)
{
$pro = array();
        foreach ($catePro as $cateProCode)
        {
            //dd($cateProCode);

            $max = DB::table('product')
                ->select(['product.prod_product_code', DB::raw('MAX(quab_quantity) AS qty')])
                ->LeftJoin('quantity_break', 'quab_product_code', '=', 'prod_product_code')
                ->where('prod_product_code', '=', $cateProCode->catpro_prod_code)
                ->paginate(12);


            foreach ($max as $wt)
            {
                $maCode = DB::table('product')
                    ->join('quantity_break', 'quab_product_code', '=', 'prod_product_code')
                    ->join('supplier','supp_code','=','prod_supplier_code')
                    ->select('prod_product_code','prod_supplier_code', 'product_name', 'prod_image1', 'prod_from_price', 'quab_quantity','supp_margin','prod_supp_margin','prod_seo_title')
                    ->where('prod_product_code', '=', $wt->prod_product_code)
                    ->where('quab_quantity', '=', $wt->qty)->where('supp_flag','=','1')
                    ->orderBy('supp_seq_no','ASC')
                    ->paginate(12);

                array_push($pro, $maCode);
                
                //$data = $this->paginate(array_push($pro, $maCode));

            }
        }

        $sysfromPrice = sysmaster::where('sysm_def_id','from_price')->first();

        $subCateList = sub_category_one::where('suco_flag','1')->orderBy('suco_name')->get();

        return view('search_product')->with(['subCateList'=>$subCateList,'pro'=>$pro,'subCate'=>$subCate,'cateInfo'=>$cate,'sysfromPrice'=>$sysfromPrice,'suppList'=>$suppList]);
    }

Frontend

{!! $pro->links() !!}


via Chebli Mohamed

mercredi 22 juin 2022

how to fix Undefined variable: data on laravel view

I am trying to send variable with data from a function to laravel front page view and i get Undefined variable: data (View: C:\xampp\htdocs\laravelproject\resources\views\process-url.blade.php).

This is my code and web.php routes.

web.php

Route::get('/',  [welcomechecker::class, 'getfrontpage']);
Route::post('process-url',  [welcomechecker::class, 'saveformdata']);

welcomechecker.php controller

class welcomechecker extends Controller
{

    function getfrontpage(){
        return view('welcome'); 
    }

function saveformdata(Request $request){

$client = new Client();

$data = [];
    
  $url = $request->url;   //getting value from ajax       $url =   $request->url; 
 
  $wp = $url.'/'.'wp-admin';
 
  $website = $client->request('GET', $url);

 $html = $website->html();

//Check if cms is wordpress
 
$cms  = '';

if($this->isWordPress($wp, $html) == 'WordPress'){

$cms  = 'WordPress';

 $data['cms'] = 'WordPress';
}
return view('process-url', compact('data'));
}

view blade: process-url.blade.php

@foreach($data as $student)
    
@endforeach

front page view blade: welcome.blade.php

<div class="display-content alert-success" >
    @include('process-url')
</div>

application.js having ajax code

jQuery(document).ready(function(){

   $(document).ajaxStart(function(){
  $("#wait").css("display", "block");
  });
  $(document).ajaxComplete(function(){
  $("#wait").css("display", "none");
  });

          jQuery('#ajaxsubmit').click(function(e){
           e.preventDefault();
           
             jQuery('.alert').show();
           
           $.ajaxSetup({
              headers: {
                  'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
              }
          });
           jQuery.ajax({
              url: 'process-url',
             type: 'POST',
              data: {
                 url: jQuery('#enter_url').val()
               
              },
              success: function(result){
                  console.log(result);
                
                   jQuery('.display-content').html(result.success).fadeIn(700);
               
                // jQuery('.display-  content').html(result.success).fadeIn(700).fadeOut(5000);
              }});
           });
        });

Someone please help me to identify what i am doing wrong. I am trying to submit the variable data to the process-url blade view which is routed to the saveformdata() on the web.php. The error occurs in process-url.blade.php at the data variable. The saveformdata function has a whole lot of code than what i actually put here the whole idea is that it returns an array of data from a scraping tool which i want to display on a table on process-url blade



via Chebli Mohamed

Error when trying to install Laravel Via Composer

I already have Composer and XAMPP installed. But when I try to use composer create-project laravel/laravel example-app command to create a new project by using Composer directly I throws some errors

C:\Users\HP>composer create-project laravel/laravel example-app
Creating a "laravel/laravel" project at "./example-app"
Installing laravel/laravel (v9.1.10)
  - Installing laravel/laravel (v9.1.10): Extracting archive
Created project in C:\Users\HP\example-app

In CreateProjectCommand.php line 497:

  chdir(): No such file or directory (errno 2)


create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--repository REPOSITORY] [--repository-url REPOSITORY-URL] [--add-repository] [--dev] [--no-dev] [--no-custom-installers] [--no-scripts] [--no-progress] [--no-secure-http] [--keep-vcs] [--remove-vcs] [--no-install] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--ask] [--] [<package> [<directory> [<version>]]]


C:\Users\HP>

I have tried:

  1. Reinstalling Composer
  2. Changing folder where I want to create my project
  3. Using the composer global require laravel/installer I'm using Composer version 2.3.7 and PHP Version 8.1.6. Im trying to install laravel 9 and my XAMPP is version 3.3.0


via Chebli Mohamed

Is The Possible Laravel Failed job Queue After Restart Not Run Begain

** is the possible laravel failed job queue after restart not run begging ? **

i am facing a problem in my laravel job service when my laravel service will be failed so, i will start again using command "retry default" so, "default" service start again but messages sent again and again from start and duplicate



via Chebli Mohamed

lundi 20 juin 2022

How compare all input values on the Laravel validator rules?

I have 10 selects and I need to check if one of them have different value of 'none'. How I can write this with Laravel Validator?



via Chebli Mohamed

Google Geocoding API error with file_get_contents()

I have a code block that I've cloned from a production environment into a development environment and I'm now getting an error on the dev side that reads:

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

This is happening on the file_get_contents line below.

I'm unsure why this would not be working now


    $cacheKey = 'postalCodeCoordinates' . $zipcode;
    $coordinates = Cache::get($cacheKey);
    if (is_null($coordinates)) {
        $zipcode = urlencode($zipcode);

        // TODO: replace with way to let user pick country
        $country_component = isset(self::$countryZipOverrides[$zipcode]) ?
                '|country:'.self::$countryZipOverrides[$zipcode]         :
                ''                                                       ;
        $url = "https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:{$zipcode}{$country_component}&sensor=false&key=" . config('services.geocoding.google.key');

        /*error is on this file_get_contents line*/
        $data = file_get_contents($url);
        $json = json_decode($data, true);
        if ($json['results']) {
            $coordinates = $json['results'][0]['geometry']['location'];
            Cache::put(
                $cacheKey,
                $coordinates,
                10080); // 1 week in minutes
            return $coordinates;
        }
    }
    return $coordinates;



via Chebli Mohamed

how to set redis laravel cookies for localhost:3338 frontend by domain server

i`m using laravel 5.6 and trying to create react frontend (redis session). my problem is: the cookies and sessions not responding to local host from server(domain) can i set localhost to domain whitelist session or another way to do that.

i changed config/session.php

[
   'lifetime' => env('SESSION_LIFETIME', 120),

   'expire_on_close' => false,

   'encrypt' => false,

   'files' => storage_path('framework/sessions'),

   'connection' => null,

   'table' => 'sessions',

   'store' => null,

   'lottery' => [2, 100],

   'cookie' => env(
       'SESSION_COOKIE',
       str_slug(env('APP_NAME', 'laravel'), '_') . '_session'
   ),

   'path' => '/',

   'domain' => env('SESSION_DOMAIN', 'localhost:3338'),

   'secure' => env('SESSION_SECURE_COOKIE', false),
   
   'http_only' => true,
   
   'same_site' => null,
]


via Chebli Mohamed

vendredi 17 juin 2022

laravel method post action route is shown in red

enter image description here

The route save.appointment is shown in red I have made as per the instructions



via Chebli Mohamed

Laravel controller query

I have a laravel project with Laravel Framework 5.8.38 I try to convert mysql query:

SELECT b.name as business_location_name , u.first_name as cashier_first_name , u.last_name as cashier_last_name , cr.location_id , SUM(CASE WHEN tp.is_return = '0' AND tp.method = 'cash' THEN tp.amount ELSE 0 END) totalCash, SUM(CASE WHEN tp.is_return = '1' AND tp.method = 'cash' THEN tp.amount ELSE 0 END) totalReturn , SUM(CASE WHEN tp.is_return = '0' AND tp.method = 'card' THEN tp.amount ELSE 0 END) totalCard , cr.created_at , cr.closed_at
FROM cash_registers as cr
LEFT JOIN transaction_payments as tp ON cr.user_id = tp.created_by
LEFT JOIN users as u ON u.id = cr.user_id
LEFT JOIN business_locations as b ON b.id = cr.location_id
WHERE (tp.paid_on BETWEEN cr.created_at AND cr.closed_at) AND cr.status = "close" AND cr.created_at LIKE "2022-06-01%"
GROUP BY cr.location_id , cr.user_id
ORDER BY cr.location_id ASC, cr.user_id ASC

To lavravel query

$startDate = "2022-06-01";
   $results3 = DB::table('cash_registers as cr')
           ->select(DB::raw('b.name as business_location_name , u.first_name as cashier_first_name , u.last_name as cashier_last_name , cr.location_id , SUM(CASE WHEN tp.is_return = "0" AND tp.method = "cash" THEN tp.amount ELSE 0 END) totalCash, SUM(CASE WHEN tp.is_return = "1" AND tp.method = "cash" THEN tp.amount ELSE 0 END) totalReturn , SUM(CASE WHEN tp.is_return = "0" AND tp.method = "card" THEN tp.amount ELSE 0 END) totalCard , cr.created_at , cr.closed_at'))
           ->leftjoin('transaction_payments as tp','tp.created_by', '=', 'cr.user_id')
           ->leftjoin('users as u','u.id', '=', 'cr.user_id')
           ->leftjoin('business_locations as b','b.id', '=', 'cr.location_id')
           ->whereBetween('tp.paid_on',['cr.created_at', 'cr.closed_at'])
           ->where('cr.status', '=' , 'close')
           ->where("cr.created_at", "like", $startDate.'%')
           ->groupBy('cr.location_id')
           ->groupBy('cr.user_id')
           ->orderBy('cr.location_id', 'asc')
           ->orderBy('cr.user_id', 'asc')
           ->get();

But when I run the query on phpmyadmin ,it returns correct result , but when fire the laravel query , it returns empty array []

What's the problem ?

Thanks in advance



via Chebli Mohamed

jeudi 16 juin 2022

how to pass one data view and others view page in laravel

i have two pages file in my view first is my home blade then second is category blade and both of them using extends asidenav my problem is when im redirecting to category file it gives me a error Undefined variable: categories but in my home file when im redirecting it's working fine . i will describe my code.

in my controller HomeController i pass one data categories to home.blade.php

class HomeController extends Controller
{
    public function home()
    {
        $categories = Category::select('id','name')->get();

        return view('home', compact('categories'));
     }

     public function category(){
        return view('category');
     }
}

the output of my home.blade.php

@extends('asidenav')
@section('section')
<main>
    this is homepage
</main>
@endsection

you can see in my home blade there is a extends asidenav . inside of my asidenav extends the data categories i passed is inside of that asidenav to make a list of categories

the output of my extends asidenav where the data i pass categories

<ul>    
    @foreach($categories as $category)
        <li><a href=""><span></a>
    @endforeach
</ul>

when i click the ahref to redirect the category blade it gives the error undefined variable categories. but when im redirecting to home blade it's working the output of my category.blade.php

@extends('asidenav')
@section('section')
<main>
    this is category
</main>
@endsection

but when i tried this code in my category controller it's working fine the error of undefined variable categories not showing

   public function category()
        {
          $categories = Category::select('id','name')->get();

             return view('category', compact('categories'));
        }

my point here is i want to pass only single data categories in my home blade and others file blade like a props but i don't have a idea how to do that



via Chebli Mohamed

mercredi 15 juin 2022

$request->route() returns null in laravel

I have this code:

class TotersProviderLoginController extends Controller
{

    private $oauthService;

    public function __construct(Request $request)
    {
        $provider = $request->route()->parameter('provider'); // error here
        if($provider == 'google')
            $this->oauthService = new GoogleOauthService();
        else
            throw new \Exception('Provider '.($provider ?? '').' not supported!');
    }

I have the following routes defined:

Route::get('login/toters/{provider}', 'Accounts\TotersProviderLoginController@redirectToProvider');
Route::get('login/toters/{provider}/redirect', 'Accounts\TotersProviderLoginController@handleProviderCallback');
Route::get('login/toters/{provider}/csrf', 'Accounts\TotersProviderLoginController@getCsrf');
Route::post('login/toters/{provider}/oauth', 'Accounts\TotersProviderLoginController@requestToken');
    

for some reason when I run

php artisan route:list --verbose

I get this error

In TotersProviderLoginController.php line 38:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function parameter() on null

so it's clear that $request->route() is returning null. Why is that? note: I'm using Laravel 5.8



via Chebli Mohamed

How to fix when I update composer on laravel

I trying to run my laravel 5 project on laravel 8. When I am trying to update my laravel composer. I am fetching this kind of problem.

Here the problem is



via Chebli Mohamed

lundi 13 juin 2022

Laravel Undefined variable $

I'm getting this error:

Undefined variable $nilais

This is the code from my main.blade.php

<tbody>
            @foreach ($nilais as $nilai)
            <tr>
                <td class="text-center" scope="row"></td>
                <td></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center">Lulus</td>
                <td class="text-center">
                    <button type="button" class="btn btn-warning"> Edit </button>
                    <button type="button" class="btn btn-danger"> Hapus </button>
                </td>
            </tr>
            @endforeach

my Controller

class MainController extends Controller
{
    public function index(){
        $nilais = Nilai::get();
        return view('main', compact('nilais'));
    }}

and this is the route

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

I don't know what is wrong, please help.

I'm aware there are other questions like this, but I already tried the solutions, and nothings work.

Thank you so much.



via Chebli Mohamed

dimanche 12 juin 2022

How can i Redirect Laravel 7 Bulk Old URL to New URL ? 4000+ Old URLs to New

I want to redirect my Old URL to New URL

OLD URL : http://example.com/productsite-reviews

New URL : http://example.com/reviews/productsite.com

The problem is i have more than 4000+ URLS. Can we redirect the old URL to New URL without .htaccess file ?

this is my home route

Route::get('/', 'HomeController')->name( 'home' );

Is there any way to redirect these URL in bulk without writing htaccess code?



via Chebli Mohamed

Laravel force http to https redirect but caused "too many redirects"

I have a Saas product which allows my end-user to bind their own domain to manage their products but I encountered an issue when I try to redirect those requests that is originally not requested by "http" to "https", the site will return "too many request redirection". Meanwhile, I do not want to configure port 443 into my nginx configuration as some of scenario, some of the request path might not need to neccessary to have "https". If I configured the force redirection in nginx which means all the request must served under "https" which might leads all of the request path is served via "https" but what I want to achieve is only some of the request path served under https only.

Below is the code that used to achieve the force redirection from http to https

 if (!$request->secure()) {
            return redirect()->secure($request->path());
        }


via Chebli Mohamed

jeudi 9 juin 2022

Can not access a image file in controller using jquery in laravel

I am trying to catch all data to controller using jquery in laravel. Except image file, i caught all the data in controller and i tried lots of code but did not success. In the below i gave controller and view code of laravel.

View:

<form action="" method="post" enctype="multipart/form-data" id="forms">
@csrf
<div class="row">
    <div class="col-md-4"> 
        <label>Profile Picture</label>
        <input class="form-control" type="file" name="file" id="file">
    </div>
</div>
<div>
    <button type="submit" id="submit">Submit</button>
</div>
</form>
<script>
    $(function(){        
    $("#forms").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url:$(this).attr('action'),
            method:$(this).attr('method'),
            data:new FormData(this),
            processData:false,
            dataType:'json',
            contentType:false,
            success:function(data){
                console.log(data);
                
            }
        });
    });
});
</script>

Controller:

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

and also i tried this code:

public function store(Request $request){
    return $request->file('file');  
}

i failed to catch the image file in my controller using javascript. please help if anyone can. Thank you



via Chebli Mohamed

How to use laravel group concat

I have a pivot table for property, client and agent

...

public static function client_property_list($id)
{
    $client_property_list = DB::table('agent_client_property as acp')
        ->leftJoin('clients as c', 'acp.client_id', '=', 'c.id')
        ->leftJoin('properties as p', 'p.id', '=', 'acp.property_id')
        ->leftJoin('agents as a', 'a.id', '=', 'acp.agent_id')
        ->select(DB::raw('p.*'))
        ->where('c.id','=',$id)
        ->get();

    return $client_property_list;
} 

...

one property can have multiple agents, i want to group those agents to show only 1 on the list

tried this didnt worked

public static function client_property_list($id)
    {
        $client_property_list = DB::table('agent_client_property as acp')
            ->leftJoin('clients as c', 'acp.client_id', '=', 'c.id')
            ->leftJoin('properties as p', 'p.id', '=', 'acp.property_id')
            ->leftJoin('agents as a', 'a.id', '=', 'acp.agent_id')
            ->select(DB::raw('p.*,a.first_name as name'))('group_concat(name) as names')
            ->where('c.id','=',$id)
            ->whereNull('c.deleted_at')
            ->whereNull('p.deleted_at')
            ->whereNull('a.deleted_at')
            ->get();

        return $client_property_list;
    } 


via Chebli Mohamed

mercredi 8 juin 2022

View [views.create] not found [closed]

I do not even know what should I do more?

this is my web.php

use App\Http\Controllers\HomeController;

 Route::get('/home', [HomeController::class,'index']); // have another version no worry

This is controller:

class HomeController extends Controller
{

    public function index()
{
    //
    return view('views.create');
}

this is view:

create.blade.php  // in views folder

sdhfbskdfnkds

What did I miss? Why does appear this error? I did lots of things:

composer update
php artisan config:cache
php artisan cache:clear
checked folders - views, sessions,cache in storage
re installed laravel 


via Chebli Mohamed

Unable to fetch results from hasManyJson Using staudenmeir / eloquent-json-relations

I have been working on two tables Category & Product. In Category Model I have a relationship like

class Category extends Model
{
  use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
  public function products(){

    return $this->hasManyJson(Product::class,'category_ids[]->id');
  }
}

In Products Model I have a relationship like

class Product extends Model
    {
      use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
      protected $casts = [
          'category_ids'=>'json', 
      ];
      public function products(){

        return $this->belongsToJson(Category::class,'category_ids[]->id');
      }
    }

Now in my controller when I'm doing trying to get count of each categories product, it is giving me Empty results, below is my controller code.

public function two_category()
{
    $list = Category::where('home_status', true)->get();
    foreach($list as $ls){
        echo $ls->name.'    '.count($ls->products).'<br>';
    }
    dd('ended');
   }

This is giving -

Category1 0

Category2 0

And finally this is how my column in product table looks like. Category id column in json



via Chebli Mohamed

lundi 6 juin 2022

Laravel Job Withcount Parameter not Accessible in job Laravel 5.6

Hii I created a job to send mail. I execute a query in the controller using withCount() and am able to get the count parameter inside the controller but while I am parsing the same data to the job and assign to a local variable in constructer then I use a local variable inside the handle method count parameter was missing in my local.

I am using SYNC as QUEUE_DRIVER and code files below mention

Controller

 $confernceIterationData = ConferenceIteration::with('AbstractNews')->withCount('AbstractNews')->where('id', $unserializeData['confid'])->first();
              
 $this->dispatch(new SendtronAutomatedEmailJob($confernceIterationData, $unserializeData, $attachments));

Controller Output of dd($confereceIterationData)

array:42 [
    "id" => 9085
    "conference_iteration_id" => "e3f65fda-7776-4e64-82d8-b5f1289141e2"
    "conference_id" => 259
    "name" => "American Association of Cancer Research Annual Meeting 2022"
    "acronym" => "AACR 2022"
    "abstract_news_count" => 8339
  ]

Job

<?php

namespace App\Jobs;

use App\Mail\SendTronAutomatedMail;
use App\TeamConferences;
use App\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

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

    /**
     * conference Iteration data
     *
     * @var object
     */
    protected $confrenceData;

    /**
     * Planner Form Data
     *
     * @var array
     */
    private $formData;

    /**
     * attchement files
     *
     * @var array
     */
    private $files;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($confrenceData, $formData, $files)
    {
        $this->confrenceData = $confrenceData;
        $this->confrenceData->abcount = $confrenceData->abstract_news_count;
        $this->formData = $formData;
        $this->files = $files;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        dd($this->confrenceData);

        $request = $this->formData;
        $i = 0;
        $users = User::select('email')->distinct()->wherehas('teams', function ($q) use ($request) {
            $q->whereIn('id', $request['teams']);
        })->pluck('email')->toarray();

        $subject = $this->confrenceData->acronym . " Conference Planner (" . $this->confrenceData->data_status . ")";

        

        $this->extractConfenceData($this->confrenceData);

      
 
        // dd($this->confrenceData->AbstractNews_count);

        $count = count($users);
        foreach ($users as $user) {
            Log::channel('sendtron_email')->info('Authomated Mail Send To .', ['id' => $user]);

            Mail::to($user)->send(new SendTronAutomatedMail($request['content'], $subject, $this->files));
            if (++$i === $count) {
                unset($users);
                TeamConferences::where('conference_iteration_id', $request['confid'])->whereIn('team_id', $request['teams'])->update(['last_mail_sent' => Carbon::now()->toDateTimeString()]);
                Storage::disk('s3SendTron')->delete(array_column($this->files, 's3path'));
            }
        }

    }
}

If we dd($confrenceData) in constructor we get the attribute abstract_news_count as mention in controller output.

but at the same time if we dd($this->confrenceData) we unable to get abstract_news_count



via Chebli Mohamed

laravel old env file is downloading while mywebsite/.env in shared hosting in laravel 5.6 in production mode

I am using laravel 5.6 in my shared hosting website. my project .env file is downloading while mywebsite/.env in production mode. The old env file is downloading means I was changed the env file content but downloading the old env file which is not available in my project. I have use the below code in .htacceses but still downloading <Files .env> order allow,deny Deny from all



via Chebli Mohamed

dimanche 5 juin 2022

image not display in admin panel

Image not display why in laravel, what is the issue controller nd blade is added Controller code

 try{

      $file=$request->file('image');
      $filename=$file->getClientOriginalName();
      $imgname = uniqid().$filename;

      $input['image']= $imgname;
      $destinationPath=public_path('upload/image/');
      $request->file('image')->move($destinationPath, $imgname);

  
        Auth::user();
        $article =  new Article();
        $article -> user_id=Auth::user()->id;
        $article -> title=$request->get('title');
        $article -> description=$request->get('description');
        $article-> image = $filename;
        $article -> status=$request->get('status');
        $article->save();
    $request->session()->flash('alert-success','article has been sucessfully created.');
    return back()->with('success', 'Article created successfully.');   
    }
catch(ModelNotFoundException $exception){
   // do task when error
    return back()->withError($exception->getMessage())->withInput();    }

}

in blade file print this code

 <td><img src=""
                                            width="500px"></td>


via Chebli Mohamed

jeudi 2 juin 2022

Laravel how to count each rows ID on tables relationship

so i have a 5 tables in my database with pivot, Countries, Cities, Shops, Users, shop_employee their relationship is this

Countries  | Cities      | Shops     | shop_employees| Users 
 id        | country_id  | city_id   |  shop_id      | id
                                        employee_id

my goal is i want to count each City, shop, employees in Country

this is my controller

class CountryController extends Controller
{
    public function country(){
       $countries = Country::with(['cities.shops.employees'])->get();
       return view('country',['countries'=>$countries]);
    }
}

this is my model Country

class Country extends Model
{
    public function cities(){
        return $this->hasMany(City::class);
    }
}

this is my model City

class City extends Model
{
    public function shops(){
        return $this->hasMany(Shop::class);
    }
}

this is my model Shops

class Shop extends Model
{
    public function employees(){
        return $this->belongsToMany(User::class,'shop_employees','shop_id','employee_id');
    }
}

this is my view

        <table class="table-fixed">
                <thead>
                  <tr>
                    <th class="py-2 px-2 border border-gray-300">Country</th>
                    <th class="py-2 px-2 border border-gray-300">City</th>
                    <th class="py-2 px-2 border border-gray-300">Shop</th>
                  </tr>
                </thead>
                <tbody>
                @foreach ($countries as $country)
                <tr >
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                  </tr>
                @endforeach
                </tbody>
              </table>

i tried this code its working fine the City is counting


the output, in this output i want to display the count of shops and employee

enter image description here

but when im trying this code it gives me a error

  $country->cities->shops->count() or
  $country->cities->shops->employees->count() 

error: Property [shops] does not exist on this collection instance



via Chebli Mohamed

mercredi 1 juin 2022

cant seem to change my url to tally with my lavarel app

So what I am trying in my mac hosts file is:

127.0.0.1 firstproject.test

But when I run the local server and hit firstproject.test nothing happens. I was expecting that URL to resolve to 127.0.0.1?

using php artisan serve



via Chebli Mohamed