vendredi 31 août 2018

Querying Many to Many polymorphic relationship in laravel

I've following tables:

  • contacts(id, name, email, phone_no),
  • events(id, title, start_date, end_date),
  • addresses(id, city, state, country, zip_code),
  • addressables(id, address_id, addressable_id, addressable_type)

Here addressables have many to many polymorphic relation for contacts events. addressables could also hold other polymorphic model class.

Addres Model

public function addressable()
{
    return $this->morphTo();
}

Event/Contact Model

public function addresses()
{
    return $this->morphToMany(Address::class, 'addressable');
}

I wanted to fetch addresses along with their associated models. I would appreciate if anyone could help me to

  • List addresses with associated models
  • List addresses for specific model type
  • List addresses group by model type

Thank you in advance!



via Chebli Mohamed

Laravel unserialize

I have PHP 7.1, Laravel 5.5 in my server. But when I try to start using this app I have error

unserialize(): Error at offset 0 of 320 bytes {"exception":"[object] (ErrorException(code: 0): unserialize(): Error at offset 0 of 320 bytes at /var/www/html/DS-v2.0-Front/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:149)"} []

What I can do to fix this error?



via Chebli Mohamed

Larave redirect me to /home link when clicking on the reset password link

First time when i click on the link it redirects me to the password reset change form, and password successfully changed, but after that whenever i click on the link it just redirecting me directly to the /home page other than the reset password form for every email. Here is my password reset routes

Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController@reset')->name('password.reset');
Route::get('password/reset/{token?}', 'Auth\PasswordController@showResetForm')->name('password.request');



via Chebli Mohamed

Laravel: searching related data

I have models: Student, Tutor, Country.

Main model is Student with code:

public function studentTutors()
{
    return $this->morphedByMany(Tutor::class, 'studentable')
                ->with('tutorAddresses');
}

Then relations.

Tutor:

public function tutorAddresses()
{
   return $this->hasMany(TutorAddress::class, 'tutor_id', 'id')
               ->with('tutorCountry');
}   

TutorAddress:

public function tutorCountry()
{
   return $this->hasOne(Country::class, 'country_id', 'country_id')
               ->where('user_lang', 'en');
}

How do I use it:

$paginator = $student->studentFavouriteTutors()
    ->getQuery()  //for paginate
    ->where(function ($query) use ($searchPhraze) {
        if (strlen(trim($searchPhraze))) {
            return $query
                ->where('username', 'like', '%' . $searchPhraze . '%')
                ->orWhere('firstname', 'like', '%' . $searchPhraze . '%')
                ->orWhere('lastname', 'like', '%' . $searchPhraze . '%');
        }
    })
    ->paginate($pages, $columns, $pageName, $page);

Question:

I am searching in tutors table (Tutor) for user/first/last names.

Is there are way to search for country name from countries table (Country: tutorCountry)? Lets say, table has 'name' column with country names.

If yes, how should $paginator code look like, to get data from countries table?

Same question goes for relation tutorAddresses. Lets say, table has 'city' column with city names.

Is this possible?

Now, I do not use relations for search, and just do joins.

BTW: I tried hasManyThrough relation, but it does not seem to pass data from that 'through' table, so this is not going to work for me. Also, my 'through' relations go a bit too deep for it (unless I do not understand something as far as this relation is concerned).



via Chebli Mohamed

Nested With() in Laravel Model Collection Return

I have a collection that is returned as such:

$scheduleLoads = Load::with('shipment','driver','tractor');

Now, my question is related to the with issue - is there a way to add the relationships of these relationships into my returned collection?

For example:

In the shipment model I have the following relationship:

public function shiptoAccount(){
    return $this->belongsTo('App\Customer', 'ship_to');
}

Is there a way to include the shiptoAccount return of the shipment associated with the Loads collections?



via Chebli Mohamed

Laravel messages email notification

I need to set up email notifications for a messaging system (Laravel/vue/vuex/Pusher).

I already have in app real time notifications, but I´d like to send an email to the users in the conversation if they have not seen the new messages after X minutes.

The trouble I am having is with the logic to not flood the users inbox since I do not want to send an email for every message and I also do not want to keep emailing him about previous messages.

What would be the best way to keep track of what messages I have already emailed the user about?



via Chebli Mohamed

laravel task scheduler deleting a post

I setup a simple task scheduler in laravel everything works only problem that i am having is that the post is not deleting at the time i set. I want the post to delete after 5 minutes since the post was created at, not sure why my posts are deleting after a minute.I believe i want my task scheduler to check after every minute because each post has a different delete time. here my scheduler:

protected function schedule(Schedule $schedule)
{


    $schedule->call(function (){
    $post=    Post::where('created_at', '<', Carbon::now()->addMinutes(5))->delete();
    })->everyMinute();
}



via Chebli Mohamed

Laravel 5.6 Multi User Type Auth API

I have a site providing APIs for 2 different websites.

Example: merchant.mywebsite.com (merchant) mywebsite.com (normal users)

My User Model: I'm using polymorph for different type of users, userable_id determines the type of users, will have Admin, Merchant and Normal users, all have access to 3 different sites.

class User extends Authenticatable implements Auditable
{
   public function userable()
   {
      return $this->morphTo();
   }
}

API route:

Route::namespace('Api\V1')->prefix('v1')->group(function () {   

    Route::post('login', 'LoginController@login');
    Route::post('signup', 'LoginController@signup');



    Route::group(['middleware' => 'auth:api'], function() {
        Route::get('user', 'LoginController@user');
        Route::get('logout', 'LoginController@logout');        
    });
});

I would like to share the same auth functions for API call to Merchant and Normal Users, is there any way to do that?

For example, they will all need to auth in the same route:

mywebsite.com/api/v1/login but gets directed to their respective sites upon login and token.

Do i need to specify or make a custom column to identify the user type in oauth?

**I'm using Laravel Passport btw and all 3 sites are in different repos.



via Chebli Mohamed

Laravel customize log formatter

I want to customize the log line format of only the errorlog channel. Is it possible to define it in the config file (config/logging.php), or i have to made a class for it as the doc says? But it shows me no hint..

Can somebody show me some example?

Many thanks in advance!



via Chebli Mohamed

Copy entire contents of a directory to another using Laravel 5.6

I'm trying to create a controller function where form data is used as a request to copy an existing directory full of files and sub derectories to another location.

So far I've tried,

// Vendor repositoreis path
$vrepo = storage_path('app/public/repositories/vendor/laravel/');
$lnrepo = storage_path('app/public/repositories/');

// Check if directory with similar name exists
if(!File::exists($lnrepo . str_slug($request->name))) {
  // Copy repository from vendor directory
  if(File::copyDirectory($vrepo, $lnrepo)) {
    // Rename copied repository
    rename($lnrepo . 'laravel', $lnrepo . str_slug($request->name));
  } else {
    return back()->with('error', 'No such file or directory.');
  }
} else {
  // Return error message if directory with similar name exists
  return back()->with('error', 'Repository with the same name already exists.');
}

As a result I get an error saying,

 ErrorException (E_WARNING) rename(/Applications/MAMP/htdocs/storage/app/public/repositories/laravel, /Applications/MAMP/htdocs/storage/app/public/repositories/hui): No such file or directory

It's either this or I need to figure out a way to run,

exec('composer create-project --prefer-dist laravel/laravel ' . $request->name);  



via Chebli Mohamed

Guzzle HTTP send file stream throws error- "json_encode error: Type is not supported"

I am using Guzzle client in my Laravel application to send a request to API endpoint along with a file. I am achieving this by creating a multipart data as follow-

$rid = $this->wsl->curlWSl('POST', '/throttle', [], [
            'verify' => false,
            'multipart' => [
                [
                    'name'     => 'csv',
                    'contents' => fopen($dest, 'rb')
                ],
                [
                    'name' => 'name',
                    'contents' => $request->input('name')
                ],
                [
                    'name' => 'description',
                    'contents' => $request->input('description')
                ],
                [
                    'name' => 'header',
                    'contents' => '1'
                ]
            ]
]);

The curlWSL method I have defined a below -

public function curlWSl(string $method, string $path, Array $headers = [], Array $data = null, Array $options = [])
    {
        $endPoint = $this->getUri() . $path;

        if (!empty($headers)) {
            $options['headers'] = $headers;
        }

        if ($method == 'GET' && $data) {
            $endPoint .= http_build_query($data);
        }
        if ($method == 'POST') {
            $options['json'] = $data;
        }

        try {
            $response = $this->getClient()->request(
                $method,
                $endPoint,
                $options
            );
        } catch (\Exception $ex) {
            return ['statusCode'=>$ex->getCode(), 'errorMsg' => $ex->getMessage()];
        }

        return json_decode($response->getBody()) ?? (string)$response->getBody();
    }

Doing this, throws me an exception -

InvalidArgumentException {#296 ▼
  #message: "json_encode error: Type is not supported"
  #code: 0
  #file: "/var/www/html/vendor/guzzlehttp/guzzle/src/functions.php"
  #line: 327
  trace: {▶}
}

I am sure, this is because of fopen file stream because when I remove that, my request is received at the endpoint.

I am also looking for some help on how can I validate the request data at the API endpoint using laravel validators.

Your help is much appreciated.



via Chebli Mohamed

Validation rule for 2 fields unique

In my laravel 5.6 application I use next rule to check unique for name field

    'name' => [
        'required',
        'string',
        'max:255',
        Rule::unique('votes')->ignore($vote_id),
    ],

I use ignore condition to update this vote.

But I have a table where field “name” is unique inside of any "vote_id" :

CREATE TABLE "vote_items" 
  "id" integer not null primary key autoincrement, 
  "vote_id" integer null, 
  "name" varchar not null, 

Can I use unique checks condition in such cases and if yes which syntax is correct?

Thanks!



via Chebli Mohamed

Laravel 5.1: Kbwebs\MultiAuth\Guard' does not have a method getAuthIdentifier

I am running Laravel 5.1 and am encountering the following error.

[2018-08-31 12:38:33] prod.ERROR: Debugbar exception: call_user_func_array() expects parameter 1 to be a valid callback, class 'Kbwebs\MultiAuth\Guard' does not have a method 'getAuthIdentifier' 

I am trying to display a user account with the following controller:

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {

        /** @var User $user */
        $user = Auth::user()->get();
        $transactions = $user->transactions()
            ->with('orders')
            ->where('type', '=', 'mealservice')
            ->whereIn('status', [Transaction::TRANSACTION_STATUS_DONE])
            ->orderBy('created_at', 'DESC')
            ->get();

        if ($transactions) {
            $moments = Moment::get();
            $meals = Meal::get();
        } else {
            $moments = collect();
            $meals = collect();
        }

        return view('website.pages.account.index')
            ->with(['transactions' => $transactions, 'user' => $user, 'userData' => $user->data]);
    }

I am able to get the user->data just fine. But once the view is triggered im encountering the above error. Does anyone have an idea?



via Chebli Mohamed

Laravel: Multiple Polymorphic relationships in a Eloquent Model

I have a Table Named Comment with following structure

Schema::create('model_notes', function (Blueprint $table) {
$table->increments('id');
$table->morphs('commentable');
$table->morphs('creatable');
$table->text('note');
$table->timestamps();
});

where I have two polymorphic relationships

commentable for any Article/Post or a Video

creatable for the comment Creator of the comment User/Admin

How to add comment against a Post created by a user?

I tried creating using following code

public function addComment($creatable, $comment)
{
        $this->comments()->create(['comment' => $comment, 'creatable' => $creatable]);
}

It did work

Thanks in advance!!!



via Chebli Mohamed

Two middleware for only one Function in laravel

I can use only one middleware at a time..inside a constructor..I want to use if else condition inside constructor or two middleware.

I can use only only middleware inside constructor & if else condition also not working

I want only one function work or use according to middleware

Example are follows

If else

class HRJob extends Controller
   {   
       public function __construct()
       {
          if(Auth::guard('admin'))
         {
          $this->middleware('auth:admin');
         }
       else
       {
       $this->middleware('auth');
        }
    }
      public function userdetails()
      {
     dd(Auth::user());
      }
    }

Two middleware

class HRJob extends Controller
 {  
   public function __construct()
       {
     $this->middleware('auth:admin');
     $this->middleware('auth');
     }

  public function userdetails()
     {
     dd(Auth::user());
      }
 }



via Chebli Mohamed

Laravel - Check if value is equal to any record in collection

I have a collection of records.

  $pastSessions = Sessions::where('id', $id)->pluck('event_start_time');

This has 12 records.

I'm trying to check if a variable is equal to any of these records, but it's only checking the last one.

if($application->appointment == $pastSessions)

How do I check is it equal to any of the records.

This is all in my controller



via Chebli Mohamed

Get Laravel 5 controller name in boot method

I have some theme in laravel that boot via this in my Custom package

 $this->app->makeWith( $themeClass, [ $this->app ] )

How I can get current controller name? I need this for know if this page is post or product and get id this product

in view works fine this code

            $routeArray = app( 'request' )->route()->getAction();
            $controllerAction = class_basename( $routeArray['controller'] );

but in theme not works

Call to a member function getAction() on null

I use laravel 5.6



via Chebli Mohamed

wanted to installlaravel in the end but amid updating composer error when updating composer in centos 7

[Composer\Downloader\TransportException]
The "http://repo.packagist.org/p/provider-2018-04%24f9978a9325d44b58afb83d14b6ccdbcc0937c5ad7690238e7b4525c0028d8953.json" file could not be down
loaded (HTTP/1.1 404 Not Found)



via Chebli Mohamed

Change ways to retrieve user data - Password Broker - Laravel 5.1

First of all, sorry for my bad English

Currently I use PasswordBroker facade to reset password of users. Below is script to do:

use Password; // Facade: Illuminate\Auth\Passwords\PasswordBroker
...
...
$userCredentials = $request->only(
    'email', 'password', 'password_confirmation', 'token'
);

$response = Password::reset(
    $userCredentials,
    function (User $user, $password) {
        $user->password = $password;
        $user->save();
    }
);

With correct email, token and valid password, all users can reset their password easily.

New my system had been updated. All emails in users table has been encrypted (AES_ENCRYPT), so I need to make some changes to apply.

Here is getUser method of Password facade

public function getUser(array $credentials)
{
    $credentials = Arr::except($credentials, ['token']);

    $user = $this->users->retrieveByCredentials($credentials);

    if ($user && ! $user instanceof CanResetPasswordContract) {
        throw new UnexpectedValueException('User must implement CanResetPassword interface.');
    }

    return $user;
}

I need some where criteria like

$user->where(
    DB::raw("AES_DECRYPT(email, 'encryption key')"),
    $userEmail
);

How to apply the criteria without change original source code of Laravel?



via Chebli Mohamed

Provider Class not found in In ProviderRepository.php line 208

I have create a simple Laravel Package and pushed it on Github

https://github.com/akshaykhale1992/model-notes

and Published the Package on Packagist

https://packagist.org/packages/akshaykhale1992/model-note

I tried to install it in my laravel application, it pulled the package from Github but the package installation was not successful.

Below is the Error that is returned by composer command

root@root.com:~/$ composer require akshaykhale1992/model-note
Using version dev-master for akshaykhale1992/model-note
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing akshaykhale1992/model-note (dev-master 5543914): Cloning 554391487e from cache
Writing lock file
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> @php artisan package:discover

In ProviderRepository.php line 208:

  Class 'AkshayKhale1992\ModelNote\ModelNoteProvider' not found  


Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Thanks in advance.



via Chebli Mohamed

jeudi 30 août 2018

Is it worth the effort to create a site in Laravel and React, or simply Laravel when you have to create API's for an Android APP

I am working on a website for which the client requirement is a php website and an Android APP, is it viable to create a React Frontend, so that there's no need for creating separate API's for the android App. Correct if i am wrong, i have worked on MERN stack and LAMP stack but never on a combination of both.

What would be a better option Laravel+React or Simply Laravel to have the least development time, all the data for the Android App will be handled by the Laravel API.



via Chebli Mohamed

retrieve all rows in Google Spreadsheet via API using Laravel

I'm trying to get the data from Google spread sheet by using this library: https://github.com/kawax/laravel-google-sheets, and I follow this tutorial to configure the setup of API and no any error, but once I tried to implement any of the examples they provide in the above link, it show me some errors:

Example 1 (on their link):

Undefined variable: request

Example 2 (on their link):

Unresolvable dependency resolving [Parameter #0 [ array $config ]] in class PulkitJalan\Google\Client

Can anyone guide me through the solution how I can get the data from spreadsheet or solve the problem considered here.



via Chebli Mohamed

Laravel unit test with upload file can not get file

I'm working on Laravel 5.6.

My code for unit test:

public function testUpload()
{
    Storage::fake('local');

    $this
        ->post(route('/upload', ['file' => UploadedFile::fake()->create('file.txt', 1024)]))
        ->assertSuccessful();
}

But in controller $request->file('file') always null.

Does anyone have any idea about this issue?



via Chebli Mohamed

Laravel Cashier Subscriptions for Featured Posts

I am currently using Laravel Cashier for my users so they can subscribe for premium accounts.

I also want to let any user make Featured Posts that are different from regular posts.

I want to charge the user $10/week for a featured post. I assume a Laravel Cashier subscription would work for this.

But I do not know how to link the Post, the User, and the Subscription together with Laravel Cashier.

Ideally there would be a post_id field in the subscriptions table. But there is not.

I need a way to check if a post is a featured post and if the user who owns the post has paid for it (the subscription is active)

With Laravel Cashier I can check if a user is subscribed for a premium account, but I don't know how to check if a post is subscribed to be featured by the post owner.

Does anyone know how this can be done?



via Chebli Mohamed

Integration of vue.js with laravel 5.4 and upper

I am new in vue.js and trying to work with laravel. I have some question regarding that. If anyone give feedback, then it will better for my learning.

  1. npm run watch. Is this command necessary for every modification of my code? I am facing that issue. If I modify or add something , it doesn't show expected output. it shows [vue warn] Unknown custom: element ......
  2. I've followed this steps to install. Firstly I install node js from https://nodejs.org/en/ . Then did npm install in command prompt. is this right way ?
  3. When I'll deploy this project is shared hosting server, is this as-usual of laravel project deployment or more ?

Thanks is advance ....



via Chebli Mohamed

How can I save additional data in my Laravel Nova fields?

I am using Laravel Nova and really enjoying it so far.

I have a Place field that I am successfully collecting the address, city, state etc.

I would also like to save the geolocation data that is returned by the Algolia API.

Specifically, I want to store:

"_geoloc":{"lat":xx.xxx,"lng":-xx.xxx}

Is this where an observer comes into play? I have tried that but I am only getting the data from the model. Not the data returned by Algolia.

I would like to say "Hey, save address, city & state like normal, but also save _geoloc into my lat and lng fields."

Is there a way to do that?



via Chebli Mohamed

Any pdf Library for Laravel that supports Arabic?

I have tried alot of Libraries for Pdf with laravel, like Dom Pdf, Mpdf, .. Etc

If any one know a library that supports arabic, or a solution with Dom Pdf, i will appreciate that, cause the letters in DOM Pdf shown in reverse manner.

Any help?



via Chebli Mohamed

Laravel 5.4 route not working on apache server vhost: 404: NotFoundHttpException

Been stuck on this for the better part of the day... Can anyone think of what might be wrong? I have a very straightforward route:

Route::get('incidents/{incident}', 'IncidentsController@show');

It works fine in my testing environment. I'm using route model binding with the Incident eloquent model. In production it's barfing out the RouteCollection NotFoundHttpException when it redirects to the url:

https://example.com/application/incidents/1411667

Not that it would matter, but the incident does exist in the database. When I run php artisan route:list on the server, it shows that the route exists. All other routes are working. I am using the web middleware on the Route::group that this is part of. I have tried all the obvious artisan commands: route:clear, route:cache, cache:clear, view:clear, clear-compiled, config:clear, optimize... AllowOveride All is in the apache conf for this vhost. I checked for other caches, including OPcache and it looks like there aren't any set up.



via Chebli Mohamed

Laravel 5.4 route works in testing, but not in production on apache server: Returning a 404: NotFoundHttpException

Just wondering if anyone might have an insight into this or at least how to proceed with debugging. I have a very straightforward route:

Route::get('incidents/{incident}', 'IncidentsController@show');

It works fine in my testing environment. I'm using route model binding with the Incident eloquent model. In production it's barfing out the RouteCollection NotFoundHttpException when I navigate to the url:

https://example.com/application/incidents/1411667

Not that it would matter, but the incident does exist in the database. When I run php artisan route:list on the server, it shows that the route exists. All other routes are working.I am using the web middleware on the Route::group that this is part of.



via Chebli Mohamed

Laravel asset file 404

I upload new file on my server in public\js\ folder. But I can't access it - 404 error. All other files in folder is fine. I can open it. But if I rename one of this files (for example file named test.js and I can access it) to other name (test.js to test2.js) - I'v got 404 error.

https://some/js/app.js - work fine
rename `app.js` to `app2.js`
https://some/js/app2.js - 404 error

Is Laravel 5.5 store names of allowed to access files? How can I fix it?



via Chebli Mohamed

Array not being added to variable in foreach loop

Ran into a weird problem and I'm pulling my hair out with it.

I've got this foreach loop

foreach ($rubrics as $rubric) {

            $answers = ReaderRubricAnswer::where('rubric_id', "=", $rubric->rubric_id)->get();

            $rubric['answers'] = $answers;

            Log::info($rubric['answers']);
        }

If I check the logs for $rubric['answers'] it's exactly as it should be.

However, if I var dump $rubrics, none of them have the $rubric['answers'] to them.

I know it's something simple, I've just been staring at it too long to see it now.

Thanks!



via Chebli Mohamed

Change name of uploading file into s3

I use the below code to store an image to my S3 disk. But using this code i get a random name i.e filename to the image that I'm uploading. So how can i set the filename of $request->renter_proof while uploading? Someone please help.

$storagePath = Storage::disk('s3')
    ->put('/company/'.Auth::user()->company.'/renter-proof/',
          $request->renter_proof,
          'public');

I want the name of the file to be :

$imageName = 'Tag '.$request->input('stock_on_rent').'.'.$request->renter_proof->getClientOriginalExtension();



via Chebli Mohamed

Props are somehow getting mixed between components

I'm passing two different arrays to the same component but two different instances of it. Then inside those instances I do a v-for and send a single item of array to another component using props. The problem is that when I inspect the Vue tools for the last component, I see that the prop is good but when I try to assign it to data it returns the prop from previous array(the one that was sent to another component).

Laravel:

<co-notifications class-name="writable" nots=""></co-notifications>

<co-notifications class-name="writable extended" nots=""></co-notifications>

CoNotifications:

<template>
<div>
    <div v-for="notification in notifications">
        <co-notification-item :class-name="className" :not="notification"></co-notification-item>
    </div>
</div>
</template>

    <script>
    import notificationComponent from './NotificationComponent.vue';

    export default {
        props: ['className', 'nots'],
        components: {
            'co-notification-item': notificationComponent
        },
        // data() {
    //     return {
    //         notifications: JSON.parse(this.nots),
    //     }
    // },
    computed: {
        notifications(){
            return JSON.parse(this.nots)
        }
    },
    }
</script>

CoNotificationItem

<template>
<div :class="['tableItem',className]">
    <div class="textareaWrapper">
        <input type="text" class="form-control" placeholder="Title" v-model="notification.title" v-if="notification.type === 'main'">
        <textarea class="form-control" rows="6" placeholder="Some text..."
                  v-model="notification.text"></textarea>
    </div>
    <div class="buttonWrapper">
        <button type="button" class="btn btn-success" @click="updateNotification"><i
                class="fe fe-check mr-2"></i>Save
        </button>
        <button type="button" class="btn btn-danger" @click="deleteNotification"><i
                class="fe fe-check mr-2"></i>Delete
        </button>
    </div>
</div>
</template>


    <script>
    import notificationComponent from './NotificationComponent.vue';
    export default {
        props: ['className', 'not'],
        components:{
            'co-notification-item': notificationComponent
        },
        data(){
           return {
               notification: this.not
           }
        },
        methods: {
            updateNotification(){
            this.notification.text = "test";

            },
            deleteNotification(){


            }
        }
    }
</script>

As for the data in arrays, I have 2 in the arr(0) and 2 in arr(1). When I open Vue tools on the FIRST notifications I see this (THIS IS GOOD)

enter image description here

However, when I open other notifications that read from arr(1) I see this (this is obviously not how it's supposed to be)

enter image description here

As you can see I used computed for the CoNotification but if I remove it and use only data() both nots recieve the same array, but if I use computed it is okay. However, I can't use computed in CoNotificationItem beacuse I need to have it in data() so I can bind it with v-model.

So, my question is, how to make notification on the CoNotificationItem be the same as not (variable) but be accessible in data() so I can put v-model to it - why am I getting mixed values?

Note: I also tried with computed and watch and created/mounted.

I've been stuck at this problem for half the day and I searched my as* off both in official docs and tutorials/questions on stackoverflow and whatnot.

Some searches that I tried :

Vue.js passing props to data

Passing data from Props to data in vue.js

https://forum.vuejs.org/t/update-data-when-prop-changes-data-derived-from-prop/1517



via Chebli Mohamed

Passing multiple parameters with laravel routes but keep the url "clean" (without showing them)

I'm actually working on an application using php framework Laravel.

I've hitted a problem since i need to open a modification form with two parameters. I pass them in my url like so :

<tr class="beBlack" onclick="document.location = '/showGriefs//'">

(i know that it is sketchy to create a link within a table but i need the url to change according to wich row is clicked/selected)

and i recieve them in the following route:

Route::any('/showGriefs/{No_Grief}/{No_Employe}', 'GriefController@showGrief')->name('showGriefs');

My problem is that i don't want my url to change, because, with these url changes, my application can't find the files (CSS, JS and Plugins). And since laravel is using the public directory to store all those files, it's destroying my page. The only errors i get is some missing flies error.



via Chebli Mohamed

Laravel Validation depending on the value of field

Let's say I have a combo box with some values

<option value="0">All</option>
<option value="1">ABC</option>
<option value="2">PQR</option>
<option value="3">XYZ</option>

My validation is as follows

'dept_id' => 'required|exists:department,id'

As you can see I want the dept_id field to be the id that exists in department table id column but my first option is "All" whose id obviously does not exists in department table.

So how can I ignore the exists rule if value=0 in Laravel 5.6 ?



via Chebli Mohamed

Laravel SQLSTATE[23000]: Integrity constraint violation 1452

I get the following error when I try to post into the tasks table.

This is how my store function looks like:

 public function store(Request $request)
    {

        $request->validate([
            'name' => 'required|min:3|max:128',
            'status' => 'required|in:ongoing,deleted,completed',
            'dueDate' => 'required',
        ]);
        $user_id = Auth::user()->id;

        $request->request->add(['responsible_id' => $user_id]);

        Task::create($request->all());

        //Task::create(request(['name', 'responsible_id', 'dueDate', 'status']));

        $tasks = Task::all();

        // And then redirect to the tasks page
        return ['data' => $tasks];
    }

My users table has the following culomns:

 public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

and my tasks table:

Schema::create('tasks', function (Blueprint $table) {

    $table->increments('id');
    $table->text('name');
    $table->date('dueDate');
    $table->text('status');
    $table->timestamps();

    $table->string('responsible');

    $table->integer('user_id')->unsigned();


    $table->foreign('user_id')->references('id')->on('users');

    $table->index('user_id');

});

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (homestead.tasks, CONSTRAINT tasks_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id))



via Chebli Mohamed

How to get allTags() in laravel from a filtered model

I have two models Song and Album.

Song is Taggable(using eloquent-taggable).

1)Song belongs_to Album.

Album has columns name and language.

I want to get all tags of Song for a particular Album language.

I tried

Song::join('albums','albums.id','=','songs.album_id')
     ->where('albums.language', 'hindi')
     ->allTags()->orderBy('count', 'DESC')->get(); 

But not working.



via Chebli Mohamed

Laravel 5.7 + socialite Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login()

I am using solcialite to login Laravel via Gihub, but there is problem to login. I get a error: Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_RECOVERABLE_ERROR) Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, null given, called in /var/www/html/testio/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php on line 292

My LoginController:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Socialite;
use App\User;
use Auth;


class LoginController extends Controller
{
    use AuthenticatesUsers;


    protected $redirectTo = '/home';


    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    /**
     * Redirect the user to the GitHub authentication page.
     *
     * @return \Illuminate\Http\Response
     */
    public function redirectToProvider()
    {
        return Socialite::driver('github')->redirect();
    }

    /**
     * Obtain the user information from GitHub.
     *
     * @return \Illuminate\Http\Response
     */
    public function handleProviderCallback()
    {
        $github_user = Socialite::driver('github')->user();

        $user = $this->userFindorCreate($github_user);

        Auth::login($user, true);

        return redirect('/home');


        // $user->token;
    }
    public function userFindorCreate($github_user){
        $user = User::where('provider_id', $github_user->id)->first();

        if(!$user){
            $user = new User;
        $user->name = $github_user->getName();
        $user->email = $github_user->getEmail();
        $user->provider_id = $github_user->getid();
        $user->save();
        }
    }
}

My User.php model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Foundation\Auth\User as AuthUser;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'email',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

create_users_table :

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->nullable();
            $table->string('email')->unique();
            $table->string('password')->nullable();
            $table->string('provider_id');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Damn it what I am doing wrong?



via Chebli Mohamed

Invoke Laravel controller method on start

How nad where to call a controller method not from client request but within the Laraval app when the app is ready and up. I saw schedule but it seems good for repeated tasks not for a direct call....



via Chebli Mohamed

Laravel - Checking if a user is a certain age upon registration

I'm looking to check if a user is 16 or 17 years old when they register. They're the only ages i'm looking for. I know I can use the before validation rule in Laravel, but then doesn't do what I need.

Any solutions?



via Chebli Mohamed

How to integrate Amazon Pay Payment Gateway in Laravel Application

I want to use https://github.com/amzn/amazon-pay-sdk-php This amazon pay php sdk in laravel application.



via Chebli Mohamed

What is the difference between attributesToArray() and toArray() in Laravel?

Can someone explain the difference between $model->attributesToArray() and $model->toArray() on a model?

I have an issue where a seeder is throwing an error about getCreatedAtAttribute method is not defined and it's complaining due to a toArray() method call. This is what prompted me to try and find out the difference between the two.

After switching to attributesToArray() the seeder runs fine.



via Chebli Mohamed

Laravel set from address email

Please help me, i try using Laravel to send email but i want when receive email, it will show fromEmail. I had set $messavge->from() but it get MAIL_USERNAME. It get name 'test' but from Address 'testemail@gmail.com'.

ENV

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=testemail@gmail.com
MAIL_PASSWORD=yhhbytlrqldnccig
MAIL_ENCRYPTION=tls

Config mail

'from' => [
        'address' => env('MAIL_FROM_ADDRESS', ''),
        'name' => env('MAIL_FROM_NAME', 'Matrix'),
    ],

Code

 Mail::send('order::admin.email-confirm-order', $data, function ($message) use ($data) {
                    $message->from('abc@gmail.com', 'test');
                    $message->to($data['user_email']);
                    $message->cc($data['email_cc']);
                    $message->subject($data['order_code'] );
                });



via Chebli Mohamed

Images don't show on browser Laravel 5.4

I have some images saved and uploaded in the storage folder, I have created a link and the storage folder is accesible from the public folder. When I try to load the image using this code:

<img class="" style="width:100%" src="" alt="Photo">

This is what the Chrome dev tools show

It should load but it looks like the image is there but something blocks it, if I click on the link in the image provided the browser shows the image



via Chebli Mohamed

Validate Two Inputs which depends on each other

I have two Inputs 'creditor' and 'debtor' , I want The user to put value in one of them at least, or both.

if($request->input('creditor')==Null && $request->input('debtor')==Null){
        Session::flash('danger','Please add Value in one of the two inputs at least');
        return redirect()->back();
    }

How to do the same thing with laravel validation



via Chebli Mohamed

Why is white page is loaded before my background-images in Laravel?

I loaded background image in css for my web app, but problem is that before image is loaded it shows me first, elements of html code and white background ? Is this problem with Laravel or someone knows solution ? Also size of image is only

Example: http://559c8451.ngrok.io/login 267Kb,

app.blade.php

<!DOCTYPE html>
<html lang="en">
  <head>

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

    <!-- CSRF Token -->
    <meta name="csrf-token" content="">
    <title>Master thesis application</title>

   <!-- Jquery --> 


  <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

      <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

<!-- Import css file-->

<link href="" rel="stylesheet" type="text/css"/>


 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script type="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
<!-- Highcharts for normal chart


<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

-->

<!-- Highcharts for normal tockSchart -->


<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>


  </head>
<script type="text/javascript">

</script>
  <body>
     @include('inc.header')

   @include('inc.nav')
<script>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
</script>
    <div class="container">
     @include('inc._messages')


    @yield('content')
    </div> <!-- /container -->

 @include('inc.footer')


  </body>
</html>

app.css body {

background: url(/images/images.jpeg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;

}

  .container {
            max-width: 940px;
        }
#header{
    height: 120px;
    background-color: #007ab3;
    padding: 20px;
    padding-left: 100px;


}

.navbar {
    position: relative;
    min-height: 30px;
    margin-bottom: 20px;
    border: 1px solid transparent; 
    z-index: 1;
    border-radius: 0;
}

.navbar-inverse{

    background-color: #004666;
}

@media (min-width: 768px){
.navbar-nav>li>a {
    padding-top: 0px; 
    padding-bottom: 0px; 
}}
.navbar-nav>li>a {
    padding-top: 0px; 
    padding-bottom: 0px; 
}
.nav>li>a {
    padding: 0px;
    padding-left: 10px;
    padding-right:10px;
    color: white;
    padding-top: 3px;
    font-weight: 500;
    font-size: 1.2em;
}
.navbar-inverse .navbar-nav>li>a {
    color: white;

}

.tablica{

    float:left;
}
td{
  text-align: center;  
  width: 10%;
}

th{
  font-size: 10px;
}

.table {
    width: 90%;
}

.navbar-toggle {
    position: relative;
    float: right;
    padding: 5px 5px;
    margin-top: 2px;
    margin-bottom: 8px;
    background-color: transparent;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
}


.container>.navbar-header, .container-fluid>.navbar-header, .container>.navbar-collapse, .container-fluid>.navbar-collapse {
    background-color: #004666;
    margin-right: -15px;
    margin-left: -15px;
    position: relative;
    float: none;
}

th{
    text-align: center;
}


.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

.sticky + .content {
  padding-top: 60px;
}



via Chebli Mohamed

Laravel Eloquent get where doesnt have, search where has when not null

This question is really hard to word, so I apologise for the title!

Lets say I have a Rooms model and a Bookings model, 1 room can have many bookings.

I am building a table with filters, and I need to be able to run a filter on the booking relationship IF there is a booking, else grab the record anyway.

Lets say my room has a booking relationship like so

public function latestBooking(){
    return $this->hasOne('App\Models\Bookings', 'room_id', 'id')
    ->orderBy('expiry_date', 'DESC')->limit(1);
}

The above relationship gets me the latest booking.

I'm running a 'vacant from' filter like so

    if ($request->has('filters.vacant_from')) {
        $rooms = $rooms->whereHas('latestBooking', function ($query) use ($request) {
            $query->where('expiry_date', '<', Carbon::createFromFormat('d/m/Y',$request->input('filters.vacant_from'))->format('Y-m-d'));
        });
    }

The issue is that this only gets rooms that have a booking and are available after the date specified. I need it to be able to search all rooms, if it does have a booking, check if the expiry date is after the date specified, if it doesn't have a latest booking, get it anyway as its a vacant room.

Basically how would I structure my filter function so that it runs like this

Search all rooms, if it has a latest booking, check its expiry date is after the date specified and only grab it if its true/vacant, if it doesn't have a latest booking then grab it anyway as it is vacant



via Chebli Mohamed

display the searched data in labels of the form

I've made a form for searching the bill number. When the bill is found in database table, the data should be shown in labels. How can I do that? Then the user press the button to pay for the billed amount.

view block

<form class="form-horizontal" method="POST" action="" enctype="multipart/form-data">
                        
                <div class="row" style="padding-left: 1%;">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Bill Number</label><span class="required">*</span>
                                <input type="text" maxlength="15" required="required" autofocus="autofocus" autocomplete="off" name="NBillNumber" class="form-control"/>                                
                            </div> 
                        </div> 
                        <div class="col-md-4">
                            <div class="form-group"></div> 
                            <div class="form-group" style="padding-left: 5%;">
                                <button type="submit" class="btn btn-primary">Search</button>        
                            </div> 
                        </div>                      
                </div>
</form>

<div class="row" style="padding-left: 1%;">
        <div class="col-md-4">
            <div class="form-group">
                <label>Book ID</label>
                <output name="NBookID" class="form-control" aria-readonly="true"/> 
            </div>
            <div class="form-group">
                    <label>Billed Date</label>
                    <output name="NBilledDate" class="form-control" aria-readonly="true"/>
            </div>
        </div>
        <div class="col-md-4" style="padding-left: 3%;">
            <div class="form-group">
                    <label>Billed Number</label>
                    <output name="NBilledNumber" class="form-control" aria-readonly="true"/>
            </div>
            <div class="form-group">
                <label>Quantity</label>
                <output name="NBilledQuantity" class="form-control" aria-readonly="true"/>
            </div>  
        </div>
        <div class="col-md-4"style="padding-left: 3%;">
            <div class="form-group">
                <label>Price</label>
                <output name="NBilledPrice" class="form-control" aria-readonly="true"/>
            </div>
            <div class="form-group">
                <label>Remarks</label>
                <output name="NBilledRemarks" class="form-control" aria-readonly="true"/>
            </div>
            <div class="form-group">
                    <button type="submit" class="btn btn-primary">PAY</button>        
            </div> 
        </div>
</div>

OrderedBookController code block

public function searchBill()
    {
        return view ( 'pages.payBill');
    }

public function billPay(Request $request)
    {
        $billNum = $request->input('NBillNumber');

        if($billNum != ""){
            $billsrch = OrderedBook::where ( 'BilledNum', $billNum )->get ();
            if (count ( $billsrch ) > 0)
            {
                return response()->json($billsrch);
                return view('pages.payBill', compact('billsrch'));
            }                
            else
            {
                return view ( 'pages.payBill',compact('billsrch'))->with('alert-danger', 'Sorry No details found');
            }

        }
    }

While debugging my billPay method, I am getting data from the database. Then how to show data in my view block. In previous forms I am displaying the data in a table, but now I need to show my data in form and update the paid column on button press PAY. How can I do this?

route code block

Route::get('/billSearch','OrderedBookController@searchBill');
Route::post('/billPay','OrderedBookController@billPay');



via Chebli Mohamed

Laravel Collection query results

In a custom artisan command, I'm trying to access all of the members of a model (e.g. User) with User::all().

Records exist in the database for this model but User::all() in the command just returns "Illuminate\Database\Eloquent\Collection {#3308}" instead of the actual results.

This seems to only happen within the command as I am able to pull the results using Tinker.

Does anyone know why this would be happening?



via Chebli Mohamed

How can I send email and SMS together using Laravel 5.5?

How can I send email and SMS together using Laravel 5.5 ?

Should I use mailable and SMS service or Notification with SMS and How ?



via Chebli Mohamed

Laravel Eloquent Relationship foreign key with condition?

I'm building a forum with threads and comments. Both threads and comments can be reported. So I have 3 models: Thread, Comment and Report.

The report table should be used for both threads and comments for users to report spam and harassment. It has the following columns:

$table->increments('id');
$table->string('reported_type');
$table->unsignedInteger('reported_id');

reported_type can either be 'thread' or 'comment' and the reported_id is the id of the corresponding thread.

Now I am struggling to form proper relationships with eloquent. Because within the 'thread' model I cannot just say

public function reports()
{
    return $this->hasMany(Report::class, 'reported_id');
}

because it's not clear whether the id belongs to a comment or a thread.

What could be a solution to this? I would really like to use one report table only to keep it simple.

Thanks!



via Chebli Mohamed

Laravel Modal->save() it says Undefined property: stdClass::$plot

I am getting this Undefined property: stdClass::$plot error, and trying to fix that from last 2 days. Please help me, thanks in advance. NOTE: dd($video,$VodDetail,$tmdb ); all are set and have required details.

$article= new Article();
            $article->type = 'link';
            $article->title = $video->name;
            $article->description = ($VodDetail->plot)?$VodDetail->plot:($tmdb->overview)?$tmdb->overview:'';
            $article->releaseDate = ($VodDetail->releasedate)?Carbon::parse($VodDetail->releasedate)->format('Y'):($tmdb->release_date)?Carbon::parse($tmdb->release_date)->format('Y'):'';
            $article->stream_id = $video->stream_id;
            $article->trailer = ($VodDetail->youtube_trailer)?'https://www.youtube.com/embed/'.$VodDetail->youtube_trailer:null;
            $article->rating = ($video->rating)?$video->rating:($tmdb->vote_average)?$tmdb->vote_average:'';
            $article->director = ($VodDetail->director)?$VodDetail->director:null;
            $article->runtime = ($VodDetail->duration)?$VodDetail->duration:null;
            $article->avatar = ($img_path) ? url(url($img_path)) : 'default.jpg';
            $article->background_image = ($VodDetail->backdrop_path) ? (($VodDetail->backdrop_path[0])?$VodDetail->backdrop_path[0]:null) : null;
            $article->genre = ($VodDetail->genre) ? preg_replace("' / '", ",", $VodDetail->genre) : null;
            $article->category_idFk = Category::where('title', 'LIKE', $xtreamCategories[$video->category_id])->first()->category_id ?: null;
            $article->tmdb_id = ($VodDetail->tmdb_id)?$VodDetail->tmdb_id:($tmdb->id)?$tmdb->id:'';
            $article->created_at = Carbon::now()->toDateTimeString();
            $article->updated_at = Carbon::now()->toDateTimeString();
            $article->imdb_id = ($tmdb->imdb_id)?$tmdb->imdb_id:null;
            $article->secondary_title = ($tmdb->original_title)?$tmdb->original_title:null;
            $article->language_name = ($tmdb->spoken_languages)?$tmdb->spoken_languages[0]->name:null;
$article->save();

If I put dd($article); before $article-save(); it gives me following result:

Article {#4048
  #primaryKey: "article_id"
  #table: "articles"
  +timestamps: false
  #fillable: array:15 [
    0 => "subtitle_path"
    1 => "stream_id"
    2 => "type"
    3 => "imdb_id"
    4 => "runtime"
    5 => "title"
    6 => "releaseDate"
    7 => "description"
    8 => "avatar"
    9 => "rating"
    10 => "category_idFk"
    11 => "director"
    12 => "genre"
    13 => "created_at"
    14 => "updated_at"
  ]
  #attributes: array:19 [
    "type" => "link"
    "title" => "Sacudete Las Penas"
    "description" => "One of the prisoners who have to spend a long season in jail, González, ...."
    "releaseDate" => "2018"
    "stream_id" => 9415
    "trailer" => "https://www.youtube.com/embed/5jstm_JeyW8"
    "rating" => 10.0
    "director" => null
    "runtime" => "01:25:17"
    "avatar" => "default.jpg"
    "background_image" => null
    "genre" => "Drama"
    "category_idFk" => 1
    "tmdb_id" => 518326
    "created_at" => "2018-08-30 07:30:45"
    "updated_at" => "2018-08-30 07:30:45"
    "imdb_id" => "tt7945596"
    "secondary_title" => "Sacudete Las Penas"
    "language_name" => "Español"
  ]
  #guarded: array:1 [
    0 => "*"
  ]
}



via Chebli Mohamed

How to access Response Body of GuzzleHttp and Extract Data of Response?

I'm creating application with Guzzle and Laravel 5.4. In there I'm doing request to external API and It gives response like this.

{
  "scope": "PRODUCTION",
  "token_type": "bearer",
  "expires_in": 3600,
  "refresh_token": "",
  "access_token": ""
}

And I need to access to the access_token property of this response. How I access these in GuzzleHttp. Response Content type is in application/json



via Chebli Mohamed

How insert statement works in open source akaunting script?

I have downloaded open source accounting script from akaunting.com. This source code developed in laravel. I am trying to add one more field in items table. But I am not able to find insert statement in this script.

Here is the controller code. After this I am not getting any idea..

public function store(Request $request) {

     $item = Item::create($request->input());

    // Upload picture
    if ($request->file('picture')) {
        $media = $this->getMedia($request->file('picture'), 'items');

        $item->attachMedia($media, 'picture');
    }

    $message = trans('messages.success.added', ['type' => trans_choice('general.items', 1)]);

    flash($message)->success();

    return redirect()->route('items.index');
}



via Chebli Mohamed

make clean url in laravel pagination

From this url:

http://localhost/testing/public/?page=2

To this url:

 http://localhost/testing/public/page/2

i got an example like this code below with pagination and i want to format url in my pagination look clean and nice like url ahead.

$items = [
    'item1',
    'item2',
    'item3',
    'item4',
    'item5',
    'item6',
    'item7',
    'item8',
    'item9',
    'item10'
];

// Get current page form url e.x. &page=1
$currentPage = LengthAwarePaginator::resolveCurrentPage();

// Create a new Laravel collection from the array data
$itemCollection = collect($items);

// Define how many items we want to be visible in each page
$perPage = 1;

// Slice the collection to get the items to display in current page
$currentPageItems = $itemCollection->slice(($currentPage * $perPage) - $perPage, $perPage)->all();

// Create our paginator and pass it to the view
$paginatedItems= new LengthAwarePaginator($currentPageItems , count($itemCollection), $perPage);

// set url path for generted links
$paginatedItems->setPath($request->url());

return view('items_view', ['items' => $paginatedItems]);

An example view:

<h1>Items List</h1>     
<ul>
    @foreach ($items as $item) 
        <li>  </li>
    @endforeach
</ul>

<div>
    
</div>

Any solution for these?



via Chebli Mohamed

How can I require composer autoloader in the laravel?

I want to install guzzle https://github.com/guzzle/guzzle

I read the reference, but I'm confused this section :

enter image description here

From that tutorial, asking for require composer autoloader. So seems needed to add require 'vendor/autoload.php'; Where I add the script?

I using laravel 5.6



via Chebli Mohamed

mercredi 29 août 2018

In controllers authorize() method fails for custom User model - laravel 5.4

I have created a custom user model DrupalUser which I use for authentication for my project. I have also created custom user provider and custom auth provider for it. But when I use authorize() method and pass DrupalUser model as argument it denies request. Do I need to write a custom UserResolver for it NOMGUY



via Chebli Mohamed

Laravel 5.5 Auth attempt method only returns false

This might a recurring question on why auth:attempt is returning always false, but despite looking for answers I am not able to solve my issue any further.

I have a students table with id as std_id, email as std_email and password as std_password. to overcome the default password field, I went through some answers and recommend to use this function to override the field name

public function getAuthPassword() {
        return $this->std_password;
    }

and the attempt function is

public function authenticate(Request $request)
    {
        if (Auth::attempt(['std_email' => $request['std_email'], 'password' => $request['std_password']])){
            return response()->json([
                'validated' => true
            ]);
        }else{
            return response()->json([
                'validated' => false
            ]);
        }
    }

So, I've updated two files, auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use \Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function authenticate(Request $request)
    {
        if (Auth::attempt(['std_email' => $request['std_email'], 'password' => $request['std_password']])){
            return response()->json([
                'validated' => true
            ]);
        }else{
            return response()->json([
                'validated' => false
            ]);
        }
    }

}

and the User model as

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $primaryKey = "std_id";
    protected $table = "students";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'std_email', 'std_password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        //'adv_password', 'remember_token',
    ];

    public function getAuthPassword() {
        return $this->std_password;
    }

}

I made sure that in User mode, I've set the primary key as std_id and table as students.

Also, when I register a student, I use bcrypt to has the password and save it in the DB.

public function create(Request $request){

        $account_exists = $this->check_account_exists($request['email']);

        if($account_exists){

            return response()->json(['account'=>true]);

        }else{

            DB::table('students')->insert([
                'std_fname'     => $request['first_name'],
                'std_lname'     => $request['last_name'],
                'std_email'     => $request['email'],
                'std_password'  => bcrypt($request['std_password']),
                'group_id'      => $request['group'],
                'std_isActive'  => 1
            ]);

            return response()->json(['created'=>true]);

        }

    }

At this point i am not getting any answers why the attempt method fails as I've made sure the login information is correct? Can you see if i have missed anything else?

Thanks!



via Chebli Mohamed

laravel csrf in javascript return The page has expired due to inactivity. Please refresh and try again

I have a code for the delete data loop in a table. this can be used, and works.

            
                            @foreach ($datasiswa as $a)

                                <a class="btn btn-info btn-sm" data-toggle="modal" data-target="#aktifMagang"><i class="fa fa-check"></i> Aktifkan Magang</a>
                                <!-------- start Modal --->
                                <div id="aktifMagang" class="modal fade" role="dialog">
                                  <div class="modal-dialog">
                                        <!-- Modal content-->
                                        <div class="modal-content">
                                          <div class="modal-header bg-aqua">
                                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Daftarkan Magang</h4>
                                          </div>
                                          <div class="modal-body">
                                                <form action="" method="POST" class="form-horizontal">
                                                   Aktifkan <strong></strong> sebagai peserta magang ?
                                                  <input type="hidden" name="siswa_id" value="">

                                          </div>
                                          <div class="modal-footer">
                                                <button type="submit" class="btn btn-primary">Aktifkan</button>
                                                <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
                                          </div>
                                        </div>
                                        </form>
                                  </div>
                                </div>
                                @endforeach

                        


but the results will make every data a modal. if I have 100 data then there should be 100 modal.

Is there a way to make each loop use a single modal?

searching ... and i found this .

            
                            @foreach ($datasiswa as $a)

                                <a class="btn btn-info btn-sm"data-toggle="modal" data-target="#aktifMagang" data-siswaid=""><i class="fa fa-check"></i> Aktifkan Magang</a><br /> 
                                @endforeach

                        


then

    
                    <div id="aktifMagang" class="modal fade" role="dialog">
                                <div class="modal-dialog">
                                  <!-- Modal content-->
                                  <div class="modal-content">
                                        <div class="modal-header bg-aqua">
                                          <button type="button" class="close" data-dismiss="modal">&times;</button>
                                          <h4 class="modal-title">Daftarkan Magang</h4>
                                        </div>
                                        <div class="modal-body">
                                          <form action="" method="POST" class="form-horizontal">
                                                
                                                Aktifkan <strong class="namasiswa"></strong> sebagai peserta magang ?
                                                <input type="hidden" name="siswa_id" value="">
                                        
                                        </div>
                                        <div class="modal-footer">
                                          <button type="submit" class="btn btn-primary">Aktifkan</button>
                                          <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
                                        </div>
                                  </div>
                                          </form>
                                </div>
                        </div>
        


then add another

        
                    <script>
                          $('#aktifMagang').on('show.bs.modal', function(event) {
                                var button = $(event.relatedTarget) 
                                var recipient = button.data('siswaid') 
                                var modal = $(this)
                                modal.find('.namasiswa').text(namasiswa)
                                modal.find('.modal-body input').val(recipient)
                          })
                        </script>

                


but The page has expired due to inactivity. Please refresh and try again



via Chebli Mohamed

How can I make a checkbox checked or not checked depending on what the value is in the database

So, I have this in my edit.blade.php

<div class="form-check disabled">
    <label class="form-check-label">
        <input class="form-check-input" type="hidden" value='0' name="is_default">
        <input class="form-check-input" type="checkbox" value='1' name="is_default">
        Default Variant
    </label>
</div>

and I have an is_default column in my database which has the values of either 0 or 1 depending if the checkbox is checked or not.

Now, I want to create an edit page and I want to show if that if is_default value is 1 then the checkbox should be checked, else it will be unchecked.

the value of is_default is represented as value=""



via Chebli Mohamed

How to kick(disconnect) specific user (client) in mysql using laravel query?

I want to kick(disconnect) specific user(client) in mysql using Laravel.

What I tried:

I make a function in Login Controller to store connection id, ip and dateTime.

public function authenticated(Request $request, $user)
{   

    $conn = DB::select("show full processlist");

    foreach($conn as $con){
        $user->connID = $con->Id;
        $user->connDate = Carbon::now();
        $user->last_login_ip = $con->Host;
        $user->update();
        }
}   

and i create a button and make some Ajax to trigger the button and pass the user id and connection id in controller.

In my controller here is my code.

Public function closeConnection(Request $request, $id){

    $userCon = $request->conID;

    $user = DB::table('users')
                ->where('id', $id)
                ->update([
                        'connID' => null,
                        'last_login_ip' => null,
                        'connDate' => null,
                         ]);


    //return $conn;
    $conn =  DB::select("SELECT concat('KILL ',$userCon,';')");
}

the problem is, connection_id will be change dynamically if the user visit other page or doing something in web, and when i click the close button there's an error prompted "Thread not found or sometimes there's no error but the user is still connected.

What should i want to do?

I want to disconnect(kick) specific user(client) when i clicked the button.

Hope someone have an idea.



via Chebli Mohamed

Admin session in user accounts [Laravel]

We have a laravel web app in that has the functionality of an admin account to access a user account just by clicking a button. Now, as we click the button, it destroys the session of the admin and creates another session for the user so by the time we want to go back to the admin account, we have to log that account back in. I'm having headaches and all but I guess it's natural. Is there a way to retain the use the admin session while logged in as a user? I'm a beginner so I'm having a hard time figuring this out. Help.

  • Keen


via Chebli Mohamed

Laravel 5.5 app outputs a 0 before any content

I'm coding a laravel 5.5 app and in this case I have a stranger issue which I can't locate.

Any output from my application is preceded by 0, so source code of a single page starts with the following

0<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="csrf-token" content="JoznVUdPwxyz7H8qWd2Np8lPiVld1GTq9BxeC2H2">

Even on ajax response I got a 0 before correct data. eg: return response('Subscription accepted!', 201); will output as 0Subscription accepted!

I suspect that it's related to some kind of encoding because when I first initialized git on this folder, I got a message related to CRLF and LF (I'm coding on a mac with 10.12 macOS), after some research I found a solution using git config --global core.autocrlf input, but since that change this weird 0 appears on my views.

I first said "in this case" because I'm working on several laravel projects in the same machine, and no one have this issue.

Any ideas on how to solve this will be really appreciated.

Thanks in advance.



via Chebli Mohamed

How do I query two related models in Laravel

I'm stucked on a Laravel blog project I'm working on & will appreciate any assistance. I have 2 related models, User and Post, & then in my blade file a search form which will query both models for result. In my Controller method, I have:

    $q = $request->keyword;
    $results = Post::where ('title', 'LIKE', '%{$q}%')->orWhere('body', 'LIKE', '%{$q}%')->with(['user' => function($x){
        $x->orWhere('name',  'LIKE', '%{$q}%')->get();
    }])->get();
return view('result')->withResults($results);

Issue is i dont get a response in my blade file. I suspect there's a bug in my controller method but I just can't wrap my head around it. I am using Laravel 5.4



via Chebli Mohamed

Is NetBeans not accepting _ide_helper from Laravel?

Using NetBeans 8.2 with Laravel, I'm setting the _ide_helper.php to my project as described in his link https://github.com/barryvdh/laravel-ide-helper, it was set on terminal the command

composer require barryvdh/laravel-ide-helper

then after, it was added into config/app.php the line

Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

and for last, the command on the project folder

php artisan ide-helper:generate

but nothing has changed apparently. No auto complete, no references. Here are some images comparing what is expected and what is happening.

Expected

Happening

Plus, NetBeans is marking an error inside the ide_helper file which confuses the syntax by the name of the function ('if'). I'll put an image of the part showing the error

Error_NetBeans_ide_helper

I've rebooted NetBeans, tried downloading and setting directly the file, but no lucky. Is the function 'if' causing the problem? Or is NetBeans not accepting the _ide_helper?



via Chebli Mohamed

Laravel 5.7 - Broadcasting - socket.io - redis : Nothing happen on client

Since few days I read about how to setup laravel-echo on my local machine. I manage to be able to run laravel-echo-server with redis and socket.io.

The problem is that the event is fired, but nothing happen on the client side.

I know that the event is fired, because it's log into my horizon.log file.

Horizon started successfully.
[2018-08-29 18:35:30][31] Processing: App\Events\NewModel
[2018-08-29 18:35:31][31] Processed:  App\Events\NewModel

Then, into my echo.log file, I can see that the user is connected to the channel and echo trigger the event.

L A R A V E L  E C H O  S E R V E R

version 1.3.9

⚠ Starting server in DEV mode...

✔  Running at localhost on port 60010
✔  Channels are ready.
✔  Listening for http events...
✔  Listening for redis events...

Server ready!

[6:35:15 PM] - QW3VITRzWPH4FvxPAAAB joined channel: channel-name
Channel: presence-channel-name
Event: App\Events\NewModel

It run on port 60010, because when I tried to do it on port 6001, the client is unable to connect.

I'm using virtualbox/homestead on a windows 10 machine.

There is the port forwarding into my Homestead.yaml

ports:
    - send: 60010
      to: 6001

So, I don't understand why client don't log the event. There is why my code at the moment

echo.js
/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

import Echo from "laravel-echo"
window.io = require('socket.io-client');
// Have this in case you stop running your laravel echo server
if (typeof io !== 'undefined') {
  window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':60010',
  });
    console.log('Connected to socket.io');
} else {
    console.log('Not connected to socket.io');
}

window.Echo.channel('channel-name')
    .listen('NewModel', (e) => {
        console.log('1:');
        console.log(e);
    })
    .listen('App\Events\NewModel', (e) => {
        console.log('2:');
        console.log(e);
    })
    .listen('App.Events.NewModel', (e) => {
        console.log('3:');
        console.log(e);
    });

laravel-echo-server.json
{
    "authHost": "https://app.torque.homestead",
    "authEndpoint": "/broadcasting/auth",
    "clients": [{
        "appId": "appId",
        "key": "key"
    }],
    "database": "redis",
    "databaseConfig": {
        "redis": {
            "port": "6379",
            "host": "127.0.0.1"
        },
        "sqlite": {
            "databasePath": "/database/laravel-echo-server.sqlite"
        }
    },
    "devMode": true,
    "host": "",
    "port": "60010",
    "protocol": "https",
    "socketio": {},
    "sslCertPath": "app.torque.homestead.crt",
    "sslKeyPath": "app.torque.homestead.key",
    "sslCertChainPath": "",
    "sslPassphrase": "",
    "apiOriginAllow": {
        "allowCors": false,
        "allowOrigin": "",
        "allowMethods": "",
        "allowHeaders": ""
    }
}

channels.php
<?php

/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/


Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('channel-name', function () {
    return true;
});

If you want to see another file, let me know. Actually I don't know what could be needed to fix the issue.

I think the problem may come from the forwarding port... But like I said, using 6001 is not working.

I tried many things like changing port(maybe not the right combination like client on 60010 and server on 6001????)

I also change that line into echo.js many times

host: window.location.hostname + ':60010',

There is some version of what i'm using :

vagrant@homestead:~$ node -v
v10.8.0
vagrant@homestead:~$ npm -v
6.4.0
vagrant@homestead:~$ php -v
PHP 7.2.9-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Aug 19 2018 07:16:54) ( NTS )

packages.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.18",
        "babel-preset-react": "^6.24.1",
        "bootstrap": "^4.1.3",
        "cross-env": "^5.2.0",
        "jquery": "^3.2",
        "laravel-mix": "^2.1.14",
        "lodash": "^4.17.4",
        "popper.js": "^1.14.4",
        "vue": "^2.5.17"
    },
    "dependencies": {
        "@fortawesome/fontawesome": "^1.1.8",
        "@fortawesome/fontawesome-free-brands": "^5.0.13",
        "@fortawesome/fontawesome-free-regular": "^5.0.13",
        "@fortawesome/fontawesome-free-solid": "^5.0.13",
        "@fortawesome/fontawesome-free-webfonts": "^1.0.9",
        "@fortawesome/vue-fontawesome": "0.0.22",
        "ajv": "^6.5.3",
        "bootstrap-confirmation2": "^4.0.1",
        "datatables.net": "^1.10.19",
        "datatables.net-bs4": "^1.10.19",
        "datatables.net-buttons": "^1.5.3",
        "datatables.net-buttons-bs4": "^1.5.3",
        "express": "^4.16.3",
        "ioredis": "^4.0.0",
        "laravel-echo": "^1.4.0",
        "laravel-echo-server": "^1.3.9",
        "socket.io": "^2.1.1",
        "socket.io-client": "^2.1.1",
        "vee-validate": "^2.0.9",
        "vue-inject": "^2.1.1",
        "yarn": "^1.9.4"
    }
}

composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": "^7.1.3",
        "aloha/twilio": "^4.0",
        "eyewitness/eye": "dev-beta",
        "fideloper/proxy": "^4.0",
        "guzzlehttp/guzzle": "^6.3",
        "laravel/framework": "5.7.*",
        "laravel/horizon": "^1.3",
        "laravel/passport": "^6.0",
        "laravel/tinker": "^1.0",
        "predis/predis": "^1.1"
    },
    "require-dev": {
        "filp/whoops": "^2.0",
        "fzaninotto/faker": "^1.4",
        "mockery/mockery": "^1.0",
        "nunomaduro/collision": "^2.0",
        "phpunit/phpunit": "^7.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

Thank you for helping me!



via Chebli Mohamed

Can a view check if the page is 404?

My 404.blade.php view is using my default layout, but if the page is 404 i want to hide some views I include in the default layout. Is this possible?

Something like

@if ($page->notFound)

Or do I really have to create a custom layout to use in the 404 view.



via Chebli Mohamed

PayU POST confirmation validation

I have an API service that should be requested only by Payu. I need ideas about how to validate this.

For example: Edit allowedOrigins

I don't know if there is a Payu service that confirm that the request has been made from their servers.



via Chebli Mohamed

how to extend a view having dynamic data in laravel

From a controller method i send $notifications to the home view and display notifications on header of my website.

The Profile views extends the home view, and i also wanted to display the notifications on profile view.

But it generates an error that undefined variable $notifications when i request for profile view.

I think one solution is that to send $notifications when returning profile view from controller method, but in website there are many views on which i wanted to show notification tab so it's the right way that i am thinking.

here is the code in the home view in the header section

<ul class="dropdown-menu" id="notificationlist">
            @foreach($notifications as $notification)
        <li><a href="" class="dropdown-item">
                <img src="http://localhost/webproject/public/user_images/" class="img-thumbnil" width="20px" height="20px"> <strong></strong>
                <span style="white-space: initial;">sent you a friend request.</span>
                </a></li>
                @endforeach
                </ul>



via Chebli Mohamed

How to 'use' packages in my own Laravel middleware?

I wrote a localization middleware in Laravel using the LaravelGettext package which looks like this:

<?php

namespace App\Http\Middleware;

use Closure;

class Locale {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        if ($request->method() === 'GET') {
            $segment = $request->segment(1);

            if (!in_array($segment, config('laravel-gettext.supported-locales'))) {
                $segments = $request->segments();
                $fallback = session('locale') ?: config('laravel-gettext.fallback-locale');
                $segments = array_prepend($segments, $fallback);

                return redirect()->to(implode('/', $segments));
            }

            session(['locale' => $segment]);
            LaravelGettext::setLocale($segment);
        }
        return $next($request);
    }

}

I am routing into the middleware via:

Route::prefix('{lang?}')->middleware('locale')->group(function () {
    ...
}

Running through the middleware gives me this error though:

"Class 'App\Http\Middleware\LaravelGettext' not found"

So I figured I might have to import the LaravelGettext package manually by adding:

use Xinax\LaravelGettext\LaravelGettext;

Which now gives me this Exception:

"Non-static method Xinax\LaravelGettext\LaravelGettext::setLocale() should not be called statically"

Which makes me wonder: Is there even a valid option to access the package inside a middleware? Or did I drive into a design flaw here?



via Chebli Mohamed

How can I include js files correspondes to render files in laravel blade template?

In my laravel app I have app.blade.php with following code

<html>
    <body>
        <div>
            @yield('content')
        </div>
        <script src="" ></script>
        <script src="" ></script>
    </body>
</html>

I have several pages such as page1, page2 etc and each page is rendering as page1.blade.php etc and these pages has separate javascript files like page1.js, page2.js.

page1.js should be included with page1.blade.php only and same for page2.js also. How can I include js files for the corresponding blade files?

My page1.blade.php is

@extends('layouts.app')

@section('content')
<section class="content-header">
  <h1>
    Page 1
  </h1>

</section>
@endsection



via Chebli Mohamed

Does Laravel cache polymorphic calls?

Got a polymorphic relationship like this: User -> polymorph -> subscription from various platforms. Toy but working example:

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

    public function subscription()
    {
        return $this->morphTo();
    }

    public function isExpired()
    {
        return $this->subscription->isExpired(); // Checks an attribute
    }

    public function isActive()
    {
        return $this->subscription->isActive(); // Checks an attribute
    }
    ...
}

class User{
    ...
    public function poly()
    {
        return $this->hasOne(Polymorph::class);
    }
    ...
}

And I'm doing:

$poly = $user->poly
$poly->isExpired(); // One DB call
$poly->isActive(); // No DB call
// etc..

It seems like Laravel caches the $this->subscription call. I'm looking at a query log as I'm calling these methods, and there is only one SELECT for the appropriate subscription object.

I looked through the docs, but don't think I found anything about it. Is it being cached? If so, what is it called or is there documentation describing it?



via Chebli Mohamed