vendredi 24 avril 2020

Property [categories] does not exist on this collection instance. (View: D:\xampp\htdocs\olshop\resources\views\backend\product\index.blade.php)

this is my Model

//relation from model products to model categorys
public function categorys()
{
    return $this->belongsTo('App\Category');
}

 //relation from model products to model categorys
public function categorys()
{
    return $this->belongsTo('App\Category');
}

this is my controller

 public function index()
{
    //controller buat manggil foreachnya
    $data['title'] ='Product';
    $data['page'] = 'Semua Product';
    $data['products'] = Product::all();
    return view('backend.product.index', $data);
}

**this is my **

                @foreach($products->categorys as $key => $value)
                <tr>
                    <!-- view bladenya  -->
                    <td></td>
                    <td></td>
                    <td></td>

I am trying to using $products->$categorys but its gone wrong



via Chebli Mohamed

If output of \Log::info depens on some options?

If output of

 \Log::info('text');

function is dependable on some options ?

in .env I have :

APP_DEBUG=false

and in config/app.php

'debug' => env('APP_DEBUG', false),

Also in config/logging.php I have options(seems default):

<?php

use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [


    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => 'debug',
            'days' => 14,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => 'critical',
        ],

        'papertrail' => [
            'driver' => 'monolog',
            'level' => 'debug',
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
        ],

        'stderr' => [
            'driver' => 'monolog',
            'handler' => StreamHandler::class,
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => 'debug',
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => 'debug',
        ],
    ],

];

The quesion is that with my options on live server I expected

 \Log::info('text');

would not log lines, but it writes lines anyway.

I read here https://laravel.com/docs/5.7/logging do not see any dependencies.

? Laravel 5.7

Thanks!



via Chebli Mohamed

Firebase receive notification while tab is active or on focus

What i want is to be able to perform an action when a user receives a notification while the browser is open and tab is active or focused. I can seem to figure out a way to receive notification or perform am action while browser tab is open or focused, It works well when browser is at the background.I upgraded to firebase version 7.8.0 and below is the code am using

     <script>
    // Your web app's Firebase configuration
  var firebaseConfig = {
   apiKey: "xxxx",
   authDomain: "xxx",
   databaseURL: "xxxxx",
   projectId: "xxxx",
 storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx"
};
 // Initialize Firebase


  if (!("Notification" in window)) {
   console.error("Notification isn't enabled");
   } else if (Notification.permission === "granted") {
   console.log("Notification is enabled");
   } else if (Notification.permission !== "denied") {

  // Retrieve an instance of Firebase Messaging so that it can handle background
 // messages.
 firebase.initializeApp(firebaseConfig);
 const messaging = firebase.messaging();

messaging.onMessage((payload) => {
 console.log('Message received. ', payload);
 // ...
 });

  messaging
  .requestPermission()
  .then(function () {
    // MsgElem.innerHTML = "Notification permission granted." 
    //console.log("Notification permission granted.");

     // get the token in the form of promise
      return messaging.getToken()
     })
    .then(function(token) {
    // print the token on the HTML page
   //TokenElem.innerHTML = "token is : " + token
         $.ajax({
        type:'POST',
        url:'/SaveNotificationToken',
        data:{token : token, _token: "<?php echo csrf_token(); ?>",UserId:     },
             success:function(data){
            //alert(data+"You will receive notiications from clients that viewed your service ");
            $("#msg").html(data);
        }
     }); 

   })
  .catch(function (err) {
   //ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
   console.log("Unable to get permission to notify.", err);
     });

 }


 </script>


via Chebli Mohamed

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