vendredi 24 avril 2020

How to adjust column Width in Laravel form-group

Here is simple contact form. Left side column display question that is "x1-question" and Right side is text field that User type answer.

I would like to controll Left side width size by changing like ...type class="col-sm-5" or sm- 4. but I couldn't adjust what I want width size and it become big slip and view become really ugly.

Could you teach me right col-xx-x code in Laravel form-group please?

Currently when I type long texst question Left side(question part) this is really narrow. i would like to it to more wide.

my Laravel Framework is 6.18.8

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="" rel="stylesheet">
<body>
    <div id="app">
        <nav class="navbar navbar-default navbar-static-top">
            <div class="container">
                <div class="navbar-header">

<div class="container">
    <div class="row">
        <div class="col-xl-12">
            <div class="panel panel-default">

         <div class="form-group">
     <p>   {!! Form::label('x1', 'x1-question', ['class' => 'col-sm-2 control-label']) !!} </p>

        <div class="col-sm-10">
            {!! Form::text('x1', null, ['class' => 'form-control']) !!}

            @if ($errors->has('x1'))
                <span class="help-block">
                    <strong></strong>
                </span>
            @endif
        </div>
    </div>  


via Chebli Mohamed

Which Laravel Passport Grant Type is perfect for 3rd Party server accessing my application resources using an API?

Basically, I would like to give 3rd Party (few X companies) access to my resources using an API and I would like to know which Grant Type would be best suitable and why?

I have already implemented "Client Credential Grant Type" which seemed perfect as it is best used for Machine to Machine interaction and that's what I wanted to do, that is, give 3rd Party Company access using an API to fetch and send data, but the problem with this Grant Type is that, I am unable to make a link with Users Table because there is no user_id. so, It is not possible for me to keep track of which X company is sending or fetching data. Which makes me question if I am using the right Grant Type?

I have already followed first few steps from Laravel Passport Documentation (https://laravel.com/docs/7.x/passport) to setup Passport in my application and everything seems to be good.

Steps Followed

1. composer require laravel/passport
2. php artisan migrate
3. php artisan passport:install
4. add the Laravel\Passport\HasApiTokens trait to your App\User model.
5. call the Passport::routes method within the boot method of your AuthServiceProvider
6. Finally, in your config/auth.php configuration file, you should set the driver option of the api authentication guard to passport.

There are 4 types of clients:

1. php artisan passport:client --public   (for SPA or JS application)
2. php artisan passport:client --client   (for machine to machine)
3. php artisan passport:client --personal (for mobile applications)
4. php artisan passport:client --password (outdated)

Which is the right passport:client? and how to implement it?



via Chebli Mohamed

Laravel auth nothing happen when trying to login with default laravel auth page

I have previously transferred laravel from server to another by copying the laravel project folder, now when i try to login using default laravel auth page , if i enter wrong auth value i get error auth.failed but when i enter a valid auth value the page refresh but nothing happen. I notice from browser view source the value of CSRF token is changing one i enter the valid auth value

I tried to delete the session files /storage/framework/sessions and tried

php artisan view:clear

php aritsan cache:clear

but nothing happen. How can i fix this issue.



via Chebli Mohamed

Verify User Token in Laravel

I have an ionic 3 application that is using laravel as backend . For auth I am using JWT and everything is working fine from registration , login and posting data within the app.

Problem starts when the user closes the mobile app and opens it again, I want the app to auto login the user using the saved token in storage.

The code below is for checking if the user has a token in storage, if there is then the token needs to be sent to laravel backend for verification.

verifyToken() {
    return new Promise((resolve, reject) => {
      this.storage.get("token").then((value) => {
        let headers = new Headers();
        headers.append("Accept", "application/json");
        headers.append("Content-Type", "application/json");
        headers.append("Authorization", "Bearer " + value);
        this.http.post(ApiUrl + "/verifyToken", { headers: headers }).subscribe(
          (res) => {
            let data = res.json();
            console.log("Valid token results:", data);
            resolve(data);
          },
          (error: any) => {
            console.log("Token was invalid", error);
            reject(JSON.parse(error._body));
          }
        );
      });
    });
  }


On Laravel backend I have this code for verification

 public function verifyToken()
    {
        try {

            if (! $user = JWTAuth::parseToken()->authenticate()) {
                return response()->json(['success' => false, 'error' => 'User not found.',$e->getStatusCode()], 404);
            }

        } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token expired.',$e->getStatusCode()], 401);

        } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token invalid.',$e->getStatusCode()], 401);

        } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

            return response()->json(['success' => false, 'error' => 'Login Token not supplied.',$e->getStatusCode()], 401);

        }

        // the token is valid and we have found the user
        return response()->json(['success' => true, 'message' => 'Token is valid.'], 200);

    }

When I test this via postman and provide valid user token, I get status 200 but when I do the same on the mobile app I get an error 500

"message": "The token could not be parsed from the request",
"exception": "Tymon\JWTAuth\Exceptions\JWTException",.

enter image description here



via Chebli Mohamed

Laravel filter array based on element value

I have the following array that I need to filter it and get just the elements which have type = 1

array:5 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
  2 => array:3 [
    "id" => 3
    "name" => "Gas Natural"
    "type" => 2
  ]
  3 => array:3 [
    "id" => 4
    "name" => "Internet"
    "type" => 3
  ]
  4 => array:3 [
    "id" => 5
    "name" => "Electricidad"
    "type" => 3
  ]
]

This is the expected result:

array:2 [
  0 => array:3 [
    "id" => 1
    "name" => "Agua Corriente"
    "type" => 1
  ]
  1 => array:3 [
    "id" => 2
    "name" => "Cloaca"
    "type" => 1
  ]
]

I'm trying to solve it with Arr::where helper but I'm not getting the expected result. Does anyone can help me?

Regards



via Chebli Mohamed

how i can use like query in aes_encryption in laravel

How i can use like search query in Aes_encryption data in laravel .my data in tables is in AES Encryption form . i try this code but its not work well. please help me. Thanks in Advance.

     public static function search($type, $value, $limit = 12){
        $key = self::encryption_key;
        if($type == "name"){
           $valuess =  DB::raw("AES_ENCRYPT('$value',$key)");
            $values = Crypt::encrypt($valuess);
        }elseif($type == "phone"){
            $valuess =  DB::raw("AES_ENCRYPT('$value',$key)");
            $values = Crypt::encrypt($valuess);
        }elseif($type == "email"){
            $valuess =  DB::raw("AES_ENCRYPT('$value',$key)");
            $values = Crypt::encrypt($valuess);
        }elseif($type == "tag"){
            $values = $value;
        }else{
            $valuess =  DB::raw("AES_ENCRYPT('$value',$key)");
            $values = Crypt::encrypt($valuess);
        }
        $types = Customer::getTranslatedType($type);
        $user_id = Auth::user()->id;
        $data = DB::table("user_customers")->select(DB::raw("customers.status, customers.id, user_customers.tag as tag, SUM(CASE WHEN uploads.views=0 AND folders.isPrivate = 0 THEN 1 ELSE 0 END) as unread, 
        SUM(CASE WHEN uploads.status=1 AND folders.isPrivate = 0 THEN 1 ELSE 0 END) as unprocessed, companies.id as company_id ," .(new static)->columnsToAESDecryptHelper(array("companies.name" => "name",  "companies.email" => "email", "companies.phone" => "phone", "companies.address" => "address"))))
            ->join("customers", "customers.id", "user_customers.customer_id")
            ->join("users", "user_customers.user_id", "users.id")
            ->leftjoin("folders", "users.id", "folders.user_id")
            ->leftjoin("uploads", "folders.id" , DB::raw("uploads.folder_id AND customers.id = uploads.customer_id"))
            ->leftjoin("companies", "user_customers.company_id", "companies.id")
            ->where("user_customers.user_id", $user_id)
            ->where($types, 'LIKE',"%{$values}%")
//            ->groupBy(DB::raw("customers.id , customers.user_id"))
            ->groupBy(DB::raw("companies.id"))
            ->orderBy('customers.id','desc')
            ->paginate($limit);
       // dd($data);
        return $data;


via Chebli Mohamed

Laravel One to one relasionship showing property non object

I am trying basic laravel one to one relationship but there is an error. I have a table called posts(i will attach the image) and a Model Post.php. When I am trying to get the result from Route.php it is showing an error.MySql tableError message User.php

public function post()
{
    return $this->hasOne('App\Post');
}

Route.php

Route::get('/user/post', function () {
 $post = User::find(1)->post;
return $post;

});



via Chebli Mohamed