mercredi 29 août 2018

SSH connection via PHP - Laravel

Hello everyone

I'm going to try to explain my problem as clear as possible, feel free to ask me more precision if you didn't understand what I meant and forgive my English this is not my mother tongue.


My goal

What I want to do looks simple. Let's say I have 2 servers: S1 and S2.
S1 is the server on which one I have my Laravel 5.5 installed and running.
S2 is a server where I have multiples PHP scripts.
I want to run a PHP script (which is on S2) from a simple click on a button in my Laravel App.
The command I want to run is php theNameOfMyFiles


The things you have to know

  1. In command line, I can connect in SSH to S2 via S1: ssh -tt -p 2222 myRemoteUser@myRemoteIp. This is working properly.
  2. Most of my test will show some tries of folder creation because it is easier to see if a folder has been created instead of checking if a script is running.

My different tries

To reach that goal, I tried a bunch of things. First of all, I am using Laravelcollective SSH 5.2 to be able to use SSH from my Laravel app.
My configuration file config/remote.php, this is where I specify my remote server connections :

return [
    default' => 'S1',
   'connections' => [
    'S1' => [
        'host'      => '127.0.0.1',
        'username'  => 'myUsername',
        'password'  => 'myPassword',
        'key'       => '',
        'keytext'   => '',
        'keyphrase' => '',
        'agent'     => '',
        'timeout'   => 10,
    ],
    'S2' => [
        'host'      => 'myRemoteIP',
        'username'  => 'myRemoteUser',
        'port'      => '2222',
        'password'  => '',
        'key'       => '',
        'keytext'   => '',
        'keyphrase' => '',
        'agent'     => '',
        'timeout'   => 30,
        'directory' => '/home/myRemoteUser/'
    ]

Try 1

SSH::into('S2')->run(['mkdir imAtestDirectory']);

Each time I tried to use SSH::into('S2') I'm getting an Unable to connect to remote server RuntimeException.

I tried without any SSH key, with my private/public SSH key in the keytext field but I'm still getting the same error.

I tried to put the path to my keys in the key field, but it says the file ~/.ssh/mykey doesn't exist.

Moving my keys to another place isn't working either, I'm getting the Unable to connect to remote server again.

Try 2

SSH::into('S1')->run(['ssh -tt -p 2222 myRemoteUser@myRemoteIp', 'mkdir testDir'])

I tried to reproduce exactly what I was doing in command line because I know that can work. I feel like I'm connecting to S2, when I'm looking at what the SSH command is returning I'm getting [...] The programs included with the Debian GNU/Linux system are free software [...] which is the same message I'm getting when I'm doing the command in command line , but it's not creating the folder.


Help me, please

I'm running out of ideas, I've been googling for hours but I can't find how to resolve my problem or any other way of doing what I want to do what I want.

If you need any more precision, feel free to ask.



via Chebli Mohamed

Eloquent group by product, ordering differently based on product

I currently have the following set up:

Category, SubCategory, Business, Enhancement & Product models.

  • A Category has many SubCategorys
  • A SubCategory has many Businesss
  • A Business may have one Enhancement
  • A Enhancement must have one Product

A product could be an enhanced listing, a premium listing, or additional features. If the business has brought either an enhanced or premium listing, it is recorded in the enhancement table.

So, product#1 = Premium Listing. Product#2 = Enhanced listing.

What I am wanting is to return all the businesses for a chosen SubCategory, grouping by the product that the enhancement is attached to. If the business has an enhancement, I'm wanting to randomise the order. If the business does not have a product, I'm wanting to order by name in ASC order.

So the result I'm expecting is to have a complete list of all businesses, with those with a Premium Listing, listed first in a random order. Then all businesses with an enhanced listing in a random order. Then all the other businesses that have no enhancement, in alphabetical order.

I currently have all the businesses listed in name order with the following code:

SubCategory::where('slug', $subCategory)->where('category_id', $category->id)
    ->with(['businesses' => function($query) {
        $query->orderBy('name', 'ASC');
}])->firstOrFail();



via Chebli Mohamed

Laravel 5.2 throws HTTP ERROR 500

I am using laravel 5.2 setup of pre-built project. I am looking to show errors on browser window for any issue happens. I know a simple step to do that which is to modify the APP_DEBUG to true in .env file which is pointed by app.php config file with parameter debug. I did check that.

Additionally,

  1. I added ini_set property in index file to display_errors as true.

  2. Along with this, I commented all the $dontReport exceptions from app/Exceptions/Handler.php file-

    AuthorizationException::class,
    HttpException::class,
    ModelNotFoundException::class,
    ValidationException::class,
    
    
  3. Given 777 permission to my project directory.

At the end, all these crazy methods didn't workout. I tried all I was aware of. Looking for help from you guys.



via Chebli Mohamed

How to access database outside the APP directory

I have a php file that contain in my Laravel public folder called login.php. I want to get all use data from my mySql database.

require_once __DIR__.'/../vendor/autoload.php';
$app = require __DIR__ . '../../bootstrap/app.php';
$app->boot();
$user=new \App\User();
dd(user::all());//get all user details.

When I run this, It return an error message:

Fatal error: Uncaught Error: Call to a member function connection() on null in C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1138 Stack trace: #0 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1104): Illuminate\Database\Eloquent\Model::resolveConnection(NULL) #1 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(936): Illuminate\Database\Eloquent\Model->getConnection() #2 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(847): Illuminate\Database\Eloquent\Model->newBaseQueryBuilder() #3 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(885): Illuminate\Database\Eloquent\Model->newModelQuery() #4 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(836): Illuminate\Database\Eloquent\Model->newQueryWithoutScopes() #5 C:\inetpub\wwwroot\blog2\vendor\laravel\framework\s in C:\inetpub\wwwroot\blog2\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1138

How can I get all user data here.



via Chebli Mohamed

Searching for column name when its stored as an id

I have a table, where users can search data. They enter a search term and if it matches any of the table data results are returned.

This is the controller.

  $query = request('search-term');

      if(!empty($query))
      {
        $user = OnlineCounsellingApplication::where('name', 'like', $query)
                                              ->orWhere('email', 'like', $query)
                                              ->orWhere('country_id', 'like', $query)
                                              ->paginate(25)
                                              ->setPath('');}

If a user search an email, that email record will show up.

My issue is if a user searchers a country, no results are returned as I have countries stored as an id, which relates to a name on another table. It is stored as country_id. The record is initially displayed like so

  @foreach($users as $row)
      <tr>
        <td>{!! $row->id !!}</td>
        <td>{!! $row->name ?: 'No Name Provided'!!}</td>
        <td>{!! $row->email !!}</td>
        <td>{!! $row->country['name'] ?: 'No Country Provided' !!}</td>
</tr>
@endforeach

How to I accept a string as input and search for it based on the id



via Chebli Mohamed

Can I rename Http directory for controller in Laravel? If yes, then how to do that?

I am thinking of renaming app/Http directory name to my custom name. Like rename "Http to MyCustomName".

Default Laravel folder: app/Http/Controllers

After renaming: app/MyName/Controllers

Can we do that in laravel? If yes, then where should I change the namespace and all?



via Chebli Mohamed

laravel same function for send two mail to two user with different view page

In laravel cron i have a function like  given below :

public function booking_mail()
{
  $data_to_mail= DB::table('tbl_booking as book')
                ->select('book.id as book_id','book.*','twd.id as wk_id','twd.*')
                ->join('tbl_workers_details as twd', 'twd.id', '=', 'book.worker_id')
                ->where('book.status','=','0')
                ->get();

            $data['viewpage']='mailtemplates.booking';
            $data['toemail']=$agent[0]->email;
            $data['listing_no']=$data_to_mail[0]->listing_no;
            $data['cv_no']=$data_to_mail[0]->cv_no;


            $mail= Mail::send($data['viewpage'], ['userdata'=>$data], function ($message) 
                use ($data) {
                        $message->to($data['toemail'],'Booking Mail')->subject('Inquiry Mail For Booking');
                if($data['attach']!=''){ 

                    $message->attach($data['attach']);
                }           
            });

            if($data['attach']!=''){ 
                unlink($data_to_mail[0]->civil_id_copy);
            }
            $result=DB::table('tbl_booking')
          ->where('id','=',$data_to_mail[0]->book_id)
          ->update(array(
          'status'=>'1',
          ));

}

This function is working fine but when i added one for mail function at the end of the function its not working returning me the error. i dont know why this happening to me. i want to do this because i want to send the mail for two different user with two different data and view code is given below which is returning me the error.

public function booking_mail()
{
  $data_to_mail= DB::table('tbl_booking as book')
                ->select('book.id as book_id','book.*','twd.id as wk_id','twd.*')
                ->join('tbl_workers_details as twd', 'twd.id', '=', 'book.worker_id')
                ->where('book.status','=','0')
                ->get();

  $data['user_viewpage']='mailtemplates.enduser_booking';
                    $data['toemail']=$agent[0]->email;
                    $data['listing_no']=$data_to_mail[0]->listing_no;
                    $data['cv_no']=$data_to_mail[0]->cv_no;

    //send e-mail to the agent for booking
                    $mail= Mail::send($data['viewpage'], ['userdata'=>$data], function ($message) 
                        use ($data) {
                                $message->to($data['toemail'],'Booking Mail')->subject('Inquiry Mail For Booking');
                        if($data['attach']!=''){ 

                            $message->attach($data['attach']);
                        }           
                    });

                    $mail= Mail::send($data['user_viewpage'], ['userdata'=>$data], function ($message) 
                        use ($data) {
                                $message->to($data['toemail'],'Booking Mail')->subject('Confirmation mail');       
                    });

                    $result=DB::table('tbl_booking')
                  ->where('id','=',$data_to_mail[0]->book_id)
                  ->update(array(
                  'status'=>'1',
                  ));

} 

why this is happening its returning me the error like:

Swift_TransportException in StreamBuffer.php line 268: Connection could not be established with host mail.XXXX.com [Connection timed out #110]



via Chebli Mohamed