gmanish

gmanish

Member Since 3 Years Ago

Experience Points 13,310
Experience Level 3

1,690 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed 132
Lessons
Completed
Best Reply Awards 0
Best Reply
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • Chatty Cathy Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

27 Nov
1 year ago

gmanish left a reply on Passing On CSRF Token To Vue Components Through Props

Yes, I've added the prop to my vue component, like so:

File PettyCash.vue:

export default {

      props: [
          'api',
          'csrf_token'
      ],
 ...
}

I tried using the {!! csrf_token() !!} construct also, no difference. Actually, I probably missed it earlier, but vue is spitting out a warning:

[Vue warn]: Property or method "xPxRC236KN9Hd60vPAGRCTSsrnXkczUQ4IO2F8EL" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Thanks for the header suggestion, I'll go with it if I cannot get this to work.

gmanish started a new conversation Passing On CSRF Token To Vue Components Through Props

I want to pass the CSRF token from my blade file (where my vue components are declared) to the component like so:

<petty-cash v-bind:api="api" v-bind:csrf_token="{{ csrf_token() }}">
</petty-cash>

This doesn't work, neither does it give any error. The prop csrf_token remains uninitialized.

What am I missing here?

28 Sep
1 year ago

gmanish started a new conversation Is DB::transaction Equivalent To Locking A Database

I have a multi-part operation: Step 1) Find the resource that is free during a particular time slot Step 2) Allocate the resource to a specific project

Now, I'm thinking, a resource that was free after step (1) and before (2) executes, might get allocated to a different project by somebody else.

How do I ensure that doesn't happen? Do I lock the database or is using DB::transaction enough?

25 Sep
1 year ago

gmanish started a new conversation Best Practice For Populating Dictionary Tables

What's the best practice for populating dictionary tables?

I will have some dictionaries, essentially (name, value) pairs that for several reasons, need to be part of the database. I understand Laravel has seeders, but those seem more appropriate for databases with mock data. Also, running seeders in a production environment causes warnings.

Is it ok to put the database seeding in the migrations themselves?

23 Jan
2 years ago

gmanish left a reply on Eager Loading When Relation Does Not Exist

@adsa Did not find a solution using eloquent. I ended up using joins with the query builder directly. A sample below:

$query = $org->products()
                ->select ("products.*")
                ->leftJoin ("taxes as purchase_tax", 'products.purchase_tax_id', '=', 'purchase_tax.id')
                ->leftJoin ("taxes as sale_tax", "products.sale_tax_id", "=", "sale_tax.id")
                ->leftJoin ("categories", "products.category_id", "=", "categories.id");
'''
24 Dec
2 years ago

gmanish left a reply on Installing Repository Returns "SQLSTATE[08006] [7] Fe_sendauth: No Password Supplied"

Hi @LukeJoyce, I could not figure out the exact cause, but I found some threads that seemed to indicate that there were some ongoing problems with forge at that time. My errors, I concluded, were mostly related to the LetsEncrypt SSL certs. So, I took a shortcut, provisioned and deployed on an entirely new machine :(

01 Sep
2 years ago

gmanish started a new conversation Installing Repository Returns "SQLSTATE[08006] [7] Fe_sendauth: No Password Supplied"

So, I have this site up and running on Digital Ocean servers since April. Nothing has changed, and I've not been bothered with it. Except, a couple of days back someone reported that site inaccessible.

I checked, my site was returning ERR_CONNECTION_REFUSED. I also noticed some SSL certificates (LetsEncrypt) related errors and thought I'd be better off just provisioning a new server, etc.

To my surprise, what used to be as easy and clicking a few buttons, no longer is. I have created and new server and added my unchanged repository to it. Forge returns error after checkout of said BitBucket repository:

Generating autoload files
> php artisan clear-compiled
  [PDOException]                                         
  SQLSTATE[08006] [7] fe_sendauth: no password supplied  
Script php artisan clear-compiled handling the post-install-cmd event returned with error code 1

Also, the repository is uninstalled automatically after the error, so I can no longer ssh and poke around to find the cause of error. I could swear I was able to do this before.

I'm using the correct DB credentials in the .env file before I add a repository. I have also verified that I can use the same credentials to log into the same database using pdAdmin III.

I'd appreciate any help in this matter. Forge, also seems to have undergone some changes. For instance, I could swear I would previously be able to ssh into my machine to determine the cause of error. I also noticed that the checkbox for Run Migrations after installation" is missing. I'm not really sure what has changed.

Any help is appreciated.

03 Apr
3 years ago

gmanish left a reply on Queues Working Without Running `queue:listen`

@jekinney No worries. Thanks a bunch.

I got everything to work flawlessly. As it turns out mandrill api has it's own job, so we don't need to implement a separate job for sending emails. We just need to use Mail::queue to queue our emails.

On the development machine, we still need to run queue:listen and in production, we can use beanstalkd.

@StormShadow Thanks for your guidance.

01 Apr
3 years ago

gmanish left a reply on Queues Working Without Running `queue:listen`

@StormShadow That was the problem. The QUEUE_DRIVER in my .env was set to sync. I fixed that and now if I run queue:listen, I do see the message I'm var_dumping from my job. Also, I see "volatile" records in my jobs table. However, I now get two emails.

@jekinney Please see above note. Perhaps, you are right (messages are being queued twice), and we do not need to queue madrilll messages. Could you please elaborate if that would work in a production server?

The docs seem to suggest we need to use a service like beanstalkd in production servers for running queues.

gmanish started a new conversation Queues Working Without Running `php Artisan Queue:listen`

I just stated using madrill to send welcome emails to just registering users. I followed the official docs. Needless to say, setting everything up, was a cinch, really. Once I verified everything was working as expected, I decided to implement a job for sending the emails.

That too was a breeze. I'm using database driver and trying this in my homestead box. Here's what my Job's handle method looks like:

public function handle(Mailer $mailer)
{
    $mailer->send(
        'emails.welcome', [
            'user' => $this->user
        ],
        function($message){
            $message->to($this->user->email, $this->user->name)
                    ->from('123@abc.com', 'Welcome')
                    ->subject('Welcome');

            var_dump(sprintf(
                "Sent Welcome Email to: %s (%s)",
                $this->user->name,
                $this->user->email
            ));
        }
    );
}

This is also working as expected. I receive the welcome email in seconds. What I don't understand is, it seems to be working even if I do not run php artisan queue:listen on my homestead box.

I've created the necessary database tables, using:

queue:table
php artisan queue:failed-table

If I run php artisan queue:listen and watch the terminal, the mail arrives, but the message I'm trying to print from the handle function using var_dump never shows up in the console. Also, I do not see any entries in the jobs and failed_jobs table in my database.

Could someone shed a light on this please. I guess there's something crucial I'm missing.

25 Mar
3 years ago

gmanish left a reply on DB::insert - Returns No Error, Yet No Inserts Result From Statement

@Qlic It works just fine in pgAdmin SQL view. I am using a Postgres database. Really sorry, this information should have been part of the question.

gmanish left a reply on DB::insert - Returns No Error, Yet No Inserts Result From Statement

@Qlic I've tried that. No exceptions are thrown either. After the insert has executed, $void is empty.

gmanish started a new conversation DB::insert - Returns No Error, Yet No Inserts Result From Statement

I have created a backup of a given table using the following raw queries:

    DB::statement("DROP TABLE IF EXISTS answers_bup");
    DB::statement("CREATE TABLE answers_bup AS TABLE answers");

The answers table has the following schema:

    CREATE TABLE answers
    (
      id uuid NOT NULL,
      user_id uuid NOT NULL,
      survey_id uuid NOT NULL,
      question_id uuid NOT NULL,
      answer character varying(255) NOT NULL,
      created_at timestamp(0) without time zone NOT NULL,
      updated_at timestamp(0) without time zone NOT NULL,
    }

Now, in order to restore a single row, from the answers_bup table to the answers table. I wrote the following DB::insert:

$void = DB::insert("INSERT INTO answers
                SELECT
                '?'::uuid AS id,
                '?'::uuid AS user_id,
                '?'::uuid AS survey_id,
                '?'::uuid AS question_id,
                answer,
                created_at,
                updated_at
            FROM
                answers_bup
            WHERE
                id='?'::uuid", [
    $newId,
    $user_id,
    $survey_id,
    $question_id,
    $answer->id
]);

Basically, I only need to copy over three fields from the answers_bup table - answer, created_at and updated_at. The others, have to be assigned new values, hence the above statement.

When I run this code fragment, I get no errors. Yet, the insert does not happen. The answers table remains empty.

Could anyone help me understand what might be wrong here?

18 Mar
3 years ago

gmanish left a reply on 502 Bad Gateway

Been having the similar problems since yesterday. I've deleted the server and provisioned a new one, about n times. Went to bed out of sheer frustration. Woke up, nightmare continues. From what I understood, Digital Ocean servers were having DNS resolution problems. They seem to be fixed now, but something seems to have broken in Forge and I have never tried deploying directly on Digital Ocean.

My phone won't stop ringing, our website and app are down :(

gmanish started a new conversation Subdomain Routing Not Working

I have an app set up with Forge on a Digital Ocean server. This app has a sub domain, guests.myapp.com.

After deploying my app, the myapp.com domain works, but, the guests is not working (Page could not be found error)

My routes are modelled after the example in the official doc, like so:

Route::group(['domain' => '{guests.myapp.com'], function () {
    Route::get('user/{id}', function ($id) {
        //
    });
});

I did not choose "enable wildcard sub-domains" as I am not using them.

Do I needs to do anything else to get the sub domain working?

So far, I am working with the default, Forge provided, config files. I have only changed the .env.

16 Mar
3 years ago

gmanish left a reply on Laravel5 Upgrade Issue

I was getting the same reflection errors related to 'log' . The error message clearly stated the problem. Laravel 5.x depends on ext-mbstring, which was obviously missing from my installation (php7, ngnix, ubuntu LTS on digital ocean servers). What was evading me is how to install this extension on ubuntu running ngnix. Here are the two things I did after which sanity was restored:

  • I was using Html and Form facades from Illuminate\Html\HtmlFacade and Illuminate\Html\FormFacade::class. I removed those (since they're no longer maintained by the core team) and switched to using Laravel Collective.
  • Next, I found this thread, which list the proceedure for installing the missing ext-mbstring, like so:
sudo apt-get install php7.0-mbstring

Thats it! Can't believe I spent almost 3 hours trying to figure things out.

14 Mar
3 years ago

gmanish left a reply on Passing Dynamic (Model) Parameters To Middleware

@martinbean Thanks for the clarification. I will give sessions a try.

13 Mar
3 years ago

gmanish left a reply on Passing Dynamic (Model) Parameters To Middleware

@martinbean Perhaps, my comment has been misunderstood. Actually, my question is misconstructed. Sorry about creating the confusion.

I specifically, want the user to be able to log into any number of organizations, simultaneously. I am under the impression, that by using the session, to store the current organization, a user may not be able to log into more than one organization at the same time.

I seek a clarification is this regard.

12 Mar
3 years ago

gmanish left a reply on Passing Dynamic (Model) Parameters To Middleware

@ricardovigatti Thanks. I think you are talking about the driver parameter in config/session.php. It needs to be set to database. I'll give it a shot.

11 Mar
3 years ago

gmanish left a reply on Passing Dynamic (Model) Parameters To Middleware

@martinbean Thanks for your answer. I was afraid someone would point me to the session :)

I'm a little ignorant on sessions (I'm new to web development). Could you tell me if this approach will prevent the user from logging into two (or more) different organizations, say, in two (or more) browser windows?

I've seen a number of web applications which display this symptom.

gmanish started a new conversation Passing Dynamic (Model) Parameters To Middleware

My laravel app uses the auto generated model App for authentication. However, I also have a model Organization. The two models having a many to many relationship.

Now, in one of my middlewares, I find that I need to access the Organization a User belongs to. How do I pass the Organization information to the middleware.

I know about middleware parameters. The problem I'm facing is that the Organization a User belong to could be one of several. So, in the constructor of any Controller, I do not know which context (Organization) , the Controller is being instantiated. It will require a redirection to a page where a User picks the Organization, and hence cannot (I think) be done in the constructor of the Controller.

What is the best way to pass along this Organization information to the middleware?

08 Mar
3 years ago

gmanish started a new conversation Socialite: Invalidate Token

I've implemented login through Facebook with the help of Socialite. However, I need to invalidate the token when the user chooses to log out, such that when the next time he tries to "Log in with Facebook", he'll need to authorize the app again. Is there a way to achieve this?

PS: I've tried to use the stateless api's, but even then, the user is remembered.

Long story: I want this functionality because, I'm developing a feedback app for a restaurant. A tablet (on which my web page is open) is passed around to guests for feedback. I wouldn't want to leave tokens from one guest around, when the table is passed to another guest.

12 Feb
3 years ago

gmanish left a reply on Eloquent Authentication Using Two Separate User Models

@Hesto

Wow! It's good to know, that there is in-built in support for multi-auth in 5.2. I was wondering if I'm having a questionable requirement :)

However, I don't believe 5.2 is an LTS release (please correct me if I'm wrong), so it's out of reach for me :(

If anyone has any recommendations, other that creating a custom driver, I'm all ears. It's not like I'm resistant to the idea of custom drivers. I just want to make sure, there's no other option.

gmanish started a new conversation Eloquent Authentication Using Two Separate User Models

My app needs to support two types of users:

  • regular users , these are those who are subscribers (restaurants that use my app for managing their business). For these users, I have the out of box authentication (Laravel 5.1) set up. email and password are the fields I authenticate on. I maintain information about such users in my users table.
  • guests, these are people who visit the restaurants above, register to earn loyalty points, check their score etc, leave feedback, etc. I maintain information about such users in my guests table. Authentication, in this case, is simple. I just use a mobile_number to authenticate them into the app.

I get that I can implement guest's authentication in a subdomain of my app, with different Controllers and Views.

What I don't get is, how can I use the eloquent database driver with the two distinct models? I see that we specify the model eloquent would be using through config.auth.model. So, I'm assuming that we can only have one single model implementing authentication.

Is, what I trying to achieve, possible without implementing a custom driver?

09 Feb
3 years ago

gmanish left a reply on Routing For Optional Subdomain, Domain, And Optional Tld

@joelennon I'm relatively new to laravel (and loving it). How would the subdomain route be written if we change the filter pattern. Would really appreciate, if you could provide some code sample.

gmanish left a reply on Connect To PostgreSQL Database Using PgAdmin3

Works like a charm. Thanks very much.

08 Feb
3 years ago

gmanish left a reply on Connect To PostgreSQL Database Using PgAdmin3

@tykus_ikus I'm able to ssh into the server from MacOSX terminal. So, I guess, it should be. I also added my public key into the SSH Keys section of "Server Details".

gmanish started a new conversation Connect To PostgreSQL Database Using PgAdmin3

I've just gotten started with forge and have managed to deploy my app on a digital ocean server. However, I cannot seem to connect to the PgSQL database using pgAdmin3. I could not find anything in a google search.

Has anyone managed to connect to the database using pgAdmin3? Are there any other recommendations?

Here's what I'm using:

New Server Registration: Use SSH tunneling: true Tunnel host: Tunnel Port: 22 Username: forge Authentication: password Password:

I am seeing the following error when I try to connect: SSH error: Authentication by identity file failed with error code -16

I find this weird because I never tried connected through identity file. I'm using the password option.

If I use the "identity file" and supply the path to my public key @ ~/.ssh/id_rsa.pub, I get the same error.

Any help is appreciated (I hope you don't ask me to use the psql console :)

28 Jan
3 years ago

gmanish started a new conversation Raw Query With A Like %?% Clause Gives Indeterminate Datatype: 7 ERROR

I've got a seemingly simple query like so:

$query = $org->products()
 ->select ("products.*");

$searchString = 'abc';
if ($searchString) {
 $query->whereRaw(DB::raw("products.name like '%?%'"), [$searchString]);
}

$productCount = $query->count();

This generates a QueryException:

2/2
QueryException in Connection.php line 651:
SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data
type of parameter $2 (SQL: select count(*) as aggregate from "products" where 
"products"."org_id" = 3586397f-ebe4-4c07-af72-63edb7cbe1a7 and 
"products"."org_id" is not null and products.name LIKE '%abc%')

If I change the whereRaw clause to:

$query->whereRaw(DB::raw("products.name like ?"), ['%' . $searchString . '%']);

The query executes properly. What could be going on here?

PS:

I know it's best to use query builder for such clauses, like so:

$query->where("products.name", "like", '%' . $searchString . '%');

However, this query above is the reduced form of a more complex query where using DB:raw() with a LIKE clause is unavoidable (perhaps, I should ask a separate question about that)

gmanish left a reply on Eager Loading When Relation Does Not Exist

@SachinAgarwal Eager Loading Constraints don't work. They're used to specify additional query constraints for eager load. The with clause, whenever encountered, creates a basic query of the form SELECT * FROM taxes WHERE id IN (...). Whatever we add through the constrains become additional conditions. e.g. SELECT * FROM taxes WHERE id IN (...) AND ([additional constraints here]).

It's the IN clause that's creating a problem, because when there's only one product and that doesn't have a Tax associated (i.e.null), the query ends up like this: SELECT * FROM taxes WHERE id IN (0). Now, id is of postgres type uuid and (0) is not a valid uuid and therefore the error. I need to figure out how to avoid generating the IN(0) clause to make this work.

I've tried using load(), that doesn't work either.

gmanish left a reply on How To Delete Multiple Records Using Laravel Eloquent

@Stirnwendy Giving it to you, as I feel more comfortable passing in an array of id's to:

$org->products()->whereIn('id', $ids)->delete()

This way, a malicious user will not be able to delete products that do not belong to his organization, which he can easily do using Product::destroy().

gmanish started a new conversation Eager Loading When Relation Does Not Exist

So, I have a Product model which belongsTo('App\Tax'). A product may or may not be associated with a Tax (the tax_id fk in Product could be null).

The query below works fine as long as I have at least one Product associated with a Tax:

\App\Product::with("tax")->get()

It starts throwing the following error, when none of the Product's have associated Taxes:

Illuminate\Database\QueryException with message 'SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for uuid: "0" (SQL: select * from "taxes" where "taxes"."id" in (0))'

While this exception is quite understandable, my question is how do I avoid this situation?

Note: The tax.id column is of postgres uuid type

gmanish left a reply on How To Delete Multiple Records Using Laravel Eloquent

@ayekoto Be sure to add a subject in the subject line. The line is not very obvious, look at the thick colored portion at the top of the page with a blinking cursor.

27 Jan
3 years ago

gmanish started a new conversation How To Delete Multiple Records Using Laravel Eloquent

Now this, from what I can see, should have been simple.

I want to be able to delete multiple records from the database. I have the id's of all the records I wish to delete. I call the resource.destroy route using comma separated list of ids (id is of postgres type uuid), like so:

Request URL:http://foo.app/products/62100dd6-7ecf-4870-aa79-4b132e60c904,c4b369f1-d1ef-4aa2-b4df-b9bc300a4ff5
Request Method:DELETE

On the other end, my controller action looks like so:

public function destroy($id)
{
    try {
        $ids = explode(",", $id);
        $org->products()->find($ids)->delete();
    }
    catch(...) {
    }
}

This gives me the following error:

BadMethodCallException in Macroable.php line 81:
Method delete does not exist.

in Macroable.php line 81
at Collection->__call('delete', array()) in ProductsController.php line 251
at Collection->delete() in ProductsController.php line 251
at ProductsController->destroy('62100dd6-7ecf-4870-aa79-4b132e60c904,c4b369f1-d1ef-4aa2-b4df-b9bc300a4ff5')

I have verified that find() is returning a collection of products matching the specified ids.

What am I missing?

PS:

  1. The model Product has several belongsTo relationships with other models.
  2. The product.destroy code works fine if I pass it a single id
23 Jan
3 years ago

gmanish left a reply on How To Fetch Results Sorted On Relationship Column

Answering my own question, just in case someone stumbles by, some day. This did it for me:

      $products = Product::select(DB::raw("products.*"))
            ->join("taxes as purchase_tax", 'products.purchase_tax_id', '=', 'purchase_tax.id')
            ->join("taxes as sale_tax", "products.sale_tax_id", "=", "sale_tax.id")
            ->join("categories", "products.category_id", "=", "categories.id")
            ->orderBy($orderBy, $sortDir)
            ->with(['purchase_tax', 'sale_tax', 'category'])
            ->skip($start)
            ->take($length)
            ->get();
21 Jan
3 years ago

gmanish started a new conversation How To Fetch Results Sorted On Relationship Column

So, I got this model with three relationships:

class Product ... {
    public function purchase_tax() {
        return $this->belongsTo('App\Tax', 'purchase_tax_id');
    }
    public function sale_tax() {
        return $this->belongsTo('App\Tax', 'sale_tax_id');
    }
    public function category() {
        return $this->belongsTo('App\Category', 'category_id');
    }
}

I need to fetch all Products with the resultset sorted on category.parent_path. I've got this so far:

$products = $org->products()
            ->with([
                'purchase_tax', 
                'sale_tax', 
                'category' => function($query) { 
                    $query->orderBy("parent_path", "ASC"); 
                }])
            ->skip($start)
            ->take($length)
            ->get();

While this seems to be valid (I'm getting all products back), the result is not sorted on the category.parent_path column.

How do I frame my query correctly?