saqueib

saqueib

Member Since 4 Years Ago

New Delhi

Senior Web Developer at New Delhi

Experience Points 7,240
Experience Level 2

2,760 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 36
Lessons
Completed
Best Reply Awards 2
Best Reply
Awards
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

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

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

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

  • subscriber-token Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    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 Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

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

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

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

12 Feb
5 months ago

saqueib started a new conversation Clean Way To Update Nested Array Field Value

Hey folks, I wanted to ask do you know any clean way to do the update on nested values inside an array. I have done it using foreach loop 3 level of it ?.

Maybe you guys can suggest something cleaner

$config = [
    'sections' => [
        'sun' => [
            'options' => [
                [
                    'id' => 3,
                    'name' => 'Option 1',
                    'value' => 2,
                ],
                [
                    'id' => 4,
                    'name' => 'Option 2',
                    'value' => 4,
                ]
            ]
        ],
        'mon' => [
            'options' => [
                [
                    'id' => 1,
                    'name' => 'Option 5',
                    'value' => 5,
                ]
            ]
        ],
    ]
];

dd(updateValues($config));

function updateValues(array $config)
{
    // update the config value with multiply
    foreach (array_get($config, 'sections') as $sectionKey => $section) {
        foreach (array_get($section, 'options', []) as $index => $input) {
            foreach ($input as $key => $value) {
                if (in_array($key, ['value', 'name'])) {
                    array_set($config, 'sections.' . $sectionKey . '.options.' . $index . '.' . $key, $value. " updated");
                }
            }
        }
    }

    return $config;
}

You can use a laravel collection if needed. ?

30 Jan
1 year ago

saqueib left a reply on How To Validate Date After_or_equal To A Column

@BezhanSalleh thanks for your response, but I was hoping if I can do it using validation rules, I am looking for a unique revision by effective_date greater or equals to posted fields $request->get('effective_date') input.

Thanks anyway

29 Jan
1 year ago

saqueib started a new conversation How To Validate Date After_or_equal To A Column

I have a post and it can have many revisions, revision has an effective_date column, I want to make sure when creating, new revision effective dates must be >= the previous revision’s effective date.

I have tried using https://laravel.com/docs/5.5/validation#rule-after-or-equal

'effective_date' => 'date|nullable|after_or_equal:effective_date'

but its not working for me, please help

06 Dec
1 year ago

saqueib left a reply on Custom Package Config Value Not Accessible In Laravel App

the problem was I was inconsistent in accessing the config, I was using a mix of config('mypackage.allowed_access') and config('mypackage::allowed_access'), updating everything to use . dot syntax worked

05 Dec
1 year ago

saqueib started a new conversation Custom Package Config Value Not Accessible In Laravel App

I am having some issue my package which I am developing using orchestral/testbench.

Its laravel 5.5 package, I am not able to access the package's config value but same is working when I run packages phpunit test.

here is how I am accessing it in my package controllers

config('mypackage::allowed_access')

It passes the test but when I use this package in a laravel app above for testing as a path repository above is returning null.

Now if I change this to config('mypackage.allowed_access') I am able to access it in my laravel app but now my tests are failing since its not accecible in package now :(

MyPackageServiceProvider

public function boot()
{
    // Publish config 
    $this->publishes([
        __DIR__.'/Config/mypackage.php' => config_path('mypackage.php'),
    ], 'mypackage_config');
    ....
}

public function register()
{
    $this->mergeConfigFrom(
        __DIR__.'/Config/mypackage.php', 'mypackage'
    );
}

Please help whats I am doing wrong

28 Nov
1 year ago

saqueib left a reply on OrderBy On Nested Relation

@divanoli ok, how I can do that?

saqueib left a reply on OrderBy On Nested Relation

@Yamen thanks for reply but I have column comments.like_count so I don't need the global scope and order by doesn't work. I tried your suggestion but its not working.

27 Nov
1 year ago

saqueib started a new conversation OrderBy On Nested Relation

I am using a polymorphic relation and I want to get all the post order by comments.like_count but its not working, I have tried following

Post::whereNotNull('publised_at')
->with('comment')
->latest('comment.like_count')->paginate()

this gives error no column like_count from db

Post::whereNotNull('publised_at')
->with(['comment' => function($query) {
      $query->orderBy('like_count')
}])->paginate()

Post Model*

class Post extends Model {

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

}```


Please help
22 Oct
1 year ago

saqueib started a new conversation Unable To Test Filesystem TemporaryUrl

  • Laravel Version: 5.5.11
  • PHP Version: 7.1
  • Database Driver & Version: MySQL

Description:

I have written some test to verify that a file exists on s3 and download when tried to test Storage::disk('s3')->temporaryUrl($url, $urlExpires); It gives 500 error with this msg but the code works when test by the browser.

This driver does not support creating temporary URLs

Steps To Reproduce:

Test

Storage::fake('s3');

// Create attachment
$attachment = Attachment::create([
    'name' => 'PDF Doc',
    'url' => Storage::disk('s3')->put(
        'attachments', 
        UploadedFile::fake()->create('document.pdf'), 
    1000)
]);

Storage::disk('s3')->assertExists($attachment->url);
...
$this->actingAs($user)
    ->get(route('attachments.download', $attachment->id))
    ->assertRedirect()
// it fails with with 500

Implementaion

$url = Attachment::find($id)->url;

if( Storage::disk('s3')->exists($url) ) {
    // link expiration time
    $urlExpires = Carbon::now()->addMinutes(10);

    try {
        $tempUrl = Storage::disk('s3')->temporaryUrl($url, $urlExpires);
        return redirect($tempUrl);
    } catch ( \Exception $e ) {
        // Unable to test temporaryUrl, its giving driver dont support it issue.
        return response($e->getMessage());
    }
}

One more question? Is there any way to customize the URL generated by temporaryUrl(), problem is downloaded filename is some random string rlbPsVUhqubaXGoEQk96wjPXfQTqurJvNgVjRMZ8.doc which is not very good, I like to customize the name of file to something like project-details.doc etc ?

15 Oct
1 year ago

saqueib left a reply on Unable To Download File From S3 Using Return Response()->download($file);

$file_path is returning the file name and dumping file is giving binary data.

If visit the s3 file path directly its gives me access error this files are not publicly visible.

saqueib started a new conversation Unable To Download File From S3 Using Return Response()->download($file);

I am uploading files to s3 I want it to securely download it using following code, but its not working.

if( Storage::disk('s3')->exists($file_path) ) {
      $file =  Storage::disk('s3')->get($file_path);
      return response()->download($file);
}

abort(404, 'File not found.');

Its giving me this error

is_file() expects parameter 1 to be a valid path, string given
...
/home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php:36
#1 /home/vagrant/spark-etr/vendor/symfony/http-foundation/File/File.php(36): is_file('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#2 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(94): Symfony\\Component\\HttpFoundation\\File\\File->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...')
#3 /home/vagrant/spark-etr/vendor/symfony/http-foundation/BinaryFileResponse.php(53): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->setFile('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 'attachment', false, true)
#4 /home/vagrant/spark-etr/vendor/laravel/framework/src/Illuminate/Routing/ResponseFactory.php(125): Symfony\\Component\\HttpFoundation\\BinaryFileResponse->__construct('\\xFF\\xD8\\xFF\\xE0\\x00\\x10JFIF\\x00\\x01\\x01\\x00\\x00...', 200, Array, true, 'attachment')

06 Oct
1 year ago

saqueib left a reply on Team Name Change Not Honoured For Routes

What Spark version you are using? I am on spark 5.0 and it is working for me.

05 Oct
1 year ago

saqueib started a new conversation Add Additional Name Field In Laravel Spark Update Member Modal

I want to add some extra fields in Spark model form when we click on edit a member. Out of the box currently, Spark gives only role dropdown, I have added name field in this, box but How can save updated name in DB.

I have checked the route and found

Laravel\Spark\Http\Controllers\Settings\Teams\[email protected]

Is handling the update method. This controller delegates updation and validation to this class

Laravel\Spark\Interactions\Settings\Teams\UpdateTeamMember

I want to use Spark::swap() but It's not working

Spark::swap('UpdateTeamMember', 'App\Swap\UpdateTeamMember');

Please help to solve it.

03 Oct
1 year ago

saqueib started a new conversation I Want To Use Laravel Permission With Spark

I want to use laravel permissions, I can assign role on the register

Spark::createUsersWith(function ($request) {
    ...
    $user->assignRole('owner');
});

but how can I get the current role associated with a logged in user in front-end, and also I need to list all the roles available from roles table?

When I check in dev console user variable there is no roles property. and global spark.roles is also an empty array.

05 Sep
1 year ago

saqueib left a reply on Get All Users Which Dont Have Admin Role In BelongsToMany Relation

found it

$users = User::whereDoesntHave('roles', function ($q) {
    $q->where('name', 'supporter');
})->limit(5)->get()

saqueib left a reply on Get All Users Which Dont Have Admin Role In BelongsToMany Relation

@tisuchi updated my question with table, unfortunately, your solution doesn't work.

saqueib started a new conversation Get All Users Which Dont Have Admin Role In BelongsToMany Relation

I want to get all user which don't have admin role, it's a belongsToMany relation where a user can have many roles. I want to get only the user who is not an admin.

I have tried following but it gives me users nested in each role, I want it a list of users collection.

return Role::with('users')->where('name', '!=', 'admin')->get();

Any way to do it?

04 Apr
2 years ago

saqueib left a reply on Laravel 5.4 Is Not Setting Cookies When Uploaded To Server

@MortensenC Thanks, I fixed it but not sure which file, I replaced my complete config directory on the server with a fresh working copy config directory and started working :smile:

saqueib left a reply on Laravel 5.4 Is Not Setting Cookies When Uploaded To Server

Ok, is it a cookie or a session?

session ( SESSION_DRIVER=file) works by storing cookie, I am not seeing any cookie in my browser (chrome dev tool > Application > cookie ). ![alt text](http://image.prntscr.com/image/4e3582058f9d4cc0ba84cb50e1d06499.png"Cookie not saving")

Already tried all of them, none works for me

03 Apr
2 years ago

saqueib left a reply on Laravel 5.4 Is Not Setting Cookies When Uploaded To Server

@jlrdw I have already checked, tried it in different browser even on my mobile same error. I don't understand why the cookie is not being set.

On other hand if I did install a fresh copy it works on same server.

Is there any other settings which control cookies/session?

saqueib started a new conversation Laravel 5.4 Is Not Setting Cookies When Uploaded To Server

I am facing this issue since last 2 days, tried many things but not able to get it working, I am getting most annoying tokenMismatchExceptionexception.

I tried a fresh installation that works fine, so I copied vendor folder from working on to my actual app, but it didn't work. After more digging, I saw that laravel_session & XSRF-TOKEN cookies are not set in chrome dev tool.

What could be the reason, it's working on localhost but not working on the server.

Main problem what I see it not able to set the cookies

Session storage is working as I can see on server storage/framework/session/ creates new file on refresh. So it's not permission error.

Laravel Framework 5.4.16

.env

    APP_ENV=local
    APP_KEY=base64:7WcmnZI8WcYQiNr9jn3JcTf//1scVAPtz2crL0bz4TE=
    APP_DEBUG=true
    APP_LOG_LEVEL=debug
    APP_URL=http://localhost
    
    DB_CONNECTION=sqlite
    
    BROADCAST_DRIVER=log
    CACHE_DRIVER=file
    SESSION_DRIVER=file
    QUEUE_DRIVER=sync

app/session.php

    return [
        'driver' => env('SESSION_DRIVER', 'file'),
        'lifetime' => 120,
        'expire_on_close' => false,
        'encrypt' => false,
        'files' => storage_path('framework/sessions'),
        'connection' => null,
        'table' => 'sessions',
        'store' => null,
        'lottery' => [2, 100],
        'cookie' => 'laravel_session',
        'path' => '/',
        'domain' => env('SESSION_DOMAIN', null),
        'secure' => env('SESSION_SECURE_COOKIE', false),
        'http_only' => true,
    ];

Same settings work on fresh install.

09 Feb
2 years ago

saqueib left a reply on Undefined Function In The Custom Directive

Did you manage to get it working, I am also trying to create a directive to post the form through ajax

13 Jan
2 years ago

saqueib left a reply on How To Extend The App Instance On Specific Laravel Blade View

@Frankobingen that will be a way to do it. One script will be the best way to reduce http calls.

I am going to turn complete form, post & post list a component. that way it will be maintainable and all the related functionality will be in one file. But how should I keep all the common services in one place, like in angular you have services is there any way to declare service in Vue.

12 Jan
2 years ago

saqueib left a reply on This.$http.get Is Not Working

@dhaval you need to put it in assets/js/bootstrap.js or if you dont have that file you must require it before the app instance (it should be in app.js).

var VueResource = require('vue-resource');
Vue.use(VueResource);

const app = new Vue({
    el: '#app'
});

also make sure to fetch it from npm npm install vue-resource

11 Jan
2 years ago

saqueib left a reply on This.$http.get Is Not Working

If you are using webpack/broserfy, you need to use the vue-resource like this.

var Vue = require('vue');
var VueResource = require('vue-resource');

Vue.use(VueResource);

also make sure you have vue.js imported first and then vue-resource

saqueib left a reply on How To Give The Path Of Public Folder File In View(.blade.php) File ?

just use {{ asset('audio/crow.ogg') }}, its will give public folder path

saqueib started a new conversation How To Extend The App Instance On Specific Laravel Blade View

I am very new in vue.js please help me on this, by default Laravel 5.3 comes with vue integrated, in assets/js/app.js file it initializes the vue instance.

const app = new Vue({
    el: '#app'
});

I can make some global vue component and require them before above initialization.

But I want to have some data, method and components unique on specific page (.blade.php). for example, I need one form on login view and another list of posts in a different view.

How can I extend the vue app instance on the specific page and add local components etc.

I have @stack('scripts') in my layout. I wanted to do something like this

@push('scripts')
<script>
    app.src = "{{ $me->avatar }}";

    app.methods = {
        imageuploaded (comment) {
            this.comments.push(comment);
        }
    }
</script>
@endpush

Please help how I can do it, or any other best way to deal with this problem.

27 Dec
2 years ago

saqueib left a reply on Is It Possible To Use A Model Other Than User With Cashier

@barrygee I have same scenario, did you solved it. Please share if you found solution for this problem.

Thanks

02 May
3 years ago

saqueib left a reply on Get The Only Posts Which Don't Have Replies

@ohffs wow, is this that simple, I never heard of this doesntHave method. is this for real. I am on L5.1

I have tried but its giving me only post b now, any doc for doesntHave?

saqueib left a reply on Get The Only Posts Which Don't Have Replies

@marktimbol @tealiedie one post can have many replies and some don't have any. replies are linked with parent_id. i just want those which don't have any replies.

a post is like this { id : 1, title : 'abcd', body : 'xyx', parent_id : null, type : 'a' }

and it can have many replies { id : 2, title : 'abcd', body : 'xyx', parent_id : 1, type : 'b' }, { id : 3, title : 'abcd', body : 'xyx', parent_id : 1, type : 'b' }, { id : 4, title : 'abcd', body : 'xyx', parent_id : 1, type : 'b' }

@tealiedie your solution Post::where('type', '<>', 'b'); will be only giving me post types of a, but i need all 'a' post which don't have any type b post (linked with parent_id = post_id).

one way of doing it will be like this, which i don't like

$posts = Post::with('replies')->where('type', 'a')->get();

// now loop and check it if post has reply 
$noReplies = [];
foreach($posts as $post) {
   if($post->replies()->count()  == 0) {
       array_push($noReplies, $post);
   }
}

saqueib started a new conversation Get The Only Posts Which Dont Have Replies

I wanted to get all the Post which do not have any replies post by type a using, here is Post Model & relation.

class Post extends Model
{
    public function childs()
    {
       return $this->hasMany(Post::class, 'parent_id');
    }
}

table schema.

id     |     title      |  body   |  parent_id   | type 
1      |    abcd...  |  xyz...   |  null                | a
2      |    abcd...  |  xyz...   |  1                      | b
3      |    abcd...  |  xyz...   |  null                | a
4      |    abcd...  |  xyz...   |  1                      | b
5      |    abcd...  |  xyz...   |  1                      | b
18 Mar
3 years ago

saqueib left a reply on Laravel-cors Is Not Returning Access-Control Header On Error Response From Dingo API

@dmg yes it was fixed, I just need to move the middleware from route group to global, check this issue

26 Jan
3 years ago

saqueib started a new conversation Laravel-cors Is Not Returning Access-Control Header On Error Response From Dingo API

We have just moved our Laravel API from Apache to Forge (nginx and hhvm) but one thing stopped working, its no longer sending error response with Access-Control-Allow-Origin header. Here is issue I have opened at barryvdh/laravel-cors but he seems busy, please have a look if you guys can help.

I am using "dingo/api": "1.0.*@dev". with L 5.1

All below returns response don't have Access-Control-Allow-Origin header

// returning 401 without origin header
return $this->response->error($user->msg, 401);  

// returning 422 without origin header
return $this->response->error('This email id has been taken.', 422); 

and by looking into console I can see below when I miss type the password in login form.

XMLHttpRequest cannot load http://domain.com/api/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

All 200 responses are working, OPTIONS request is giving 200 on above /auth/login route as well, but when there is error response, no Access-Control-Allow-Origin headers were returned.

It was working before, I have moved app to forge, but I don't think that was the issue. sine it works with Postman. Do i have to set something for nginx

10 Dec
3 years ago

saqueib left a reply on Question On Queue Jobs

Setup homestead, It come with all the things.

But if you wanted to work on LAMP stack without homestead you can use queue by choosing database driver and running

php artisan queue:listen

to run the queue jobs, check the (docs)[http://laravel.com/docs/5.0/queues]

But I will say go with homestead

saqueib started a new conversation Is There Any HTML Purifier For Laravel, I Want To Allow Only Some Tags

I have a forum where user can post topics, from front-end they can insert only bold, italics, underline, strike through, insertLink, insert Image tags.

How I can sanitize this request from Laravel end, I want to store only tags allowed and get rid of extra stuff with inline styles.

Does Laravel 5.1 provide anything to do it, or only 'strip_tags($html, $allowedTags)' is enough.

09 Dec
3 years ago

saqueib started a new conversation Activity Feed Tutorial Way To Eager-load Relationship By Type

I followed this tutorial for activity feed https://laracasts.com/lessons/build-an-activity-feed-in-laravel

Everything works, but I wanted to eager load some relations, so I did this

Activity::with('subject')->get();

which is giving me all thing mixed with Post, Comment all on same. I wanted to loaded only Post or Comment.

How could we do it. should i use where clause to limit the activity by App\Post, or there any other way

18 Nov
3 years ago

saqueib left a reply on Code And Pre Tags Are Not Visible In New Design

yes, inline one. Find the tag in below para, its not that visible as was earlier

The web has changed. No longer are we writing static HTML, throwing it on Geocities, and then calling it a day. No, things have changed just a little. Okay - they've changed dramatically!

With Laracasts, not only will you learn the necessary skills for building modern web applications (using PHP, Laravel, VueJS, and more) but you'll have fun doing it. Ever wished for someone to sit next to you, and explain that complicated concept you're struggling with?

saqueib started a new conversation Code And Pre Tags Are Not Visible In New Design

Hi Jeff,

Please apply some background color in and

 tags or do anything to make it prominent, currently only fonts changed which is not that visible in paragraphs.

New design is very cool

saqueib started a new conversation Limit The Result From Eager Loaded Relation

I am building an API which needs below post data with many eager loaded relation. Here is how I have tried, its working but I can't limit the number of replies, adding ->limit(1) is not giving any effect.

How I can optimize query is so slow (taking 5 sec in local machine) since its returning huge data.


return $postRepo->with([
            'replies' => function($q) {
                $q->with(['user' => function($q) {
                    $q->with(['currentCompany' => function($q){
                        $q->addSelect(['id', 'name', 'logo', 'points']);
                    }])
                        ->select(['id', 'first_name', 'last_name', 'username', 'designation', 'created_at',  'avatar', 'points']);
                }])
                    ->where('status', 'Public')
                     //***************** Adding Limit clause not working *****************//
                    ->select(['id', 'title', 'body', 'upvote', 'downvote', 'view_count', 'parent_id', 'created_at', 'user_id'])
                    ->orderBy('id', 'desc');
            },
            'tags' => function($q) {
                $q->select(['id', 'name']);
            },
            'topic' => function($q) {
                $q->addSelect(['id', 'name', 'category']);
            },
            'user' => function($q) {
                $q->addSelect(['id', 'first_name', 'last_name', 'username', 'avatar', 'points']);
            }])
            ->where([
              'status' => 'Public'
            ])
            ->paginate( intval(config('listing_qa_per_page', 20)), 
               ['id', 'title', 'body', 'points', 'display_name', 'view_count', 'upvote', 'downvote', 'flagged_count', 'follow_count', 'created_at', 'updated_at', 'topic_id', 'user_id']);

Is there any other way to do this, I am using laravel LengthAwarePaginator and I don't know how to add custom data in paginate collection.

One way will be to first get the post then loop over and load all the realations needed. but I will lose the pagination. Please help

16 Nov
3 years ago

saqueib left a reply on User Can Follow Post And Category In Laravel

I am asking the number 1 @bashy if he could help will be fantastic.

13 Nov
3 years ago

saqueib started a new conversation User Can Follow Post And Category In Laravel

I need to implement a follow system like twitter but with exception a user can follow many Post and can follow whole Category or a user can follow a User.

I have come up with this relationship. I am using Laravel 5.1

User Model

public function followers()
{
   return $this->belongsToMany('App\User', 'user_follows', 'user_id', 'follow_id');
}

public function follows()
{
   return $this->belongsToMany('App\User', 'user_follows', 'follow_id', 'user_id');
}

and for follow a Category

Category Model

public function followers()
{
   return $this->belongsToMany('App\User', 'category_follows', 'user_id', 'category_id');
}

and for Post is the same way, as you can see I need 3 tables (user_follows, category_follows, post_follows) to make this work.

I know there is Polymorphic Relation but I cant wrap my head around it. Please help how i can simplify it. once again below are the requirements

  • User can follow many Posts
  • User can follow many Category
  • User can follow many User
09 Nov
3 years ago

saqueib left a reply on Get Password Reset Link, Token

@bobbybouwmann I can only find Illuminate\Auth\Passwords\PasswordBroker.php at line 90

$token = $this->tokens->create($user);

and here is my controller

$response = Password::sendResetLink($request->only('email'), function (Message $message) {
            $message->subject(Config::get('boilerplate.recovery_email_subject'));
        });

        switch ($response) {
            case Password::RESET_LINK_SENT:
                return $this->response->noContent();
            case Password::INVALID_USER:
                return $this->response->errorNotFound();
        }

Password facade don't have any token generation method.

saqueib started a new conversation Get Password Reset Link

I am trying to send a reset password email but I cant use the view for email template, since I am using PostMark API to send email with there template.

http://developer.postmarkapp.com/developer-api-templates.html#email-with-template

Is there any way I can get only the generated token for reset link. or I have to do str_random(32) and manually insert a row in password_reset table.

What will be the best way to do it?

22 Sep
3 years ago

saqueib left a reply on Error Logging Is Not Working When User Is Logged In

Yes I have checked it, use is logged in and i can access auth()->user() in controller but in AppServiceProvider@boot its returning null and Error Logging is also not working, but when I logout, error logging is working and I am getting User as Guest

saqueib left a reply on Error Logging Is Not Working When User Is Logged In

Thanks @bobbybouwmann tried the auth() helper function, same problem Trying to get property of non-object

saqueib started a new conversation Error Logging Is Not Working When User Is Logged In

I am getting this weird issue, I have setup slack with Monolog and its sending notification me, but when I am logged in there is not notification coming.

class AppServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('production')) {
            // Get The Logger
            $monolog = Log::getMonolog();

    // **********************************************************************************************
    // I have tried official WebProcessor to get url, but its not giving me anything
    // **********************************************************************************************

            $monolog->pushProcessor(new WebProcessor($_SERVER));

            $monolog->pushProcessor(function ($record) {
                $record['extra']['session_id'] = Cookie::get(config('session.cookie'));

                //Auth::user() is always null, how can i get the logged in user

        $record['extra']['user'] = \Auth::check() ? 'Name: '.\Auth::user()->name . "\n". url(\Auth::user()->username) : "Guest";
        $record['extra']['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
                return $record;
            });

            $slackHandler = new SlackHandler(env('SLACK_TOKEN'), '#sss-sslogs', 'sss-log', true, ':warning:', Logger::ERROR);

            $monolog->pushHandler($slackHandler);
        }
    }

I have tried with commenting out $record['extra']['user'] line from above but no luck, I need to logout to make it send notification.

How can i get the Auth::user() in AppServiceProvider its always returning null, or is there anywhere else I can register this SlackHandler

Please help guys I am stuck

21 Sep
3 years ago

saqueib started a new conversation Setting Up Monolog To With Slack, How I Can Get The Online Error Log With Requested Url Etc.

I have checked the official repo of monolog and put together below code, its working greate and I am getting response in Slack. But the response are very verbose, How Can i get simple online response.


class AppServiceProvider extends ServiceProvider {

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        if ($this->app->environment('production')) {
            // Notify Slack
            $monolog = Log::getMonolog();

                         //****************** I have tried official WebProcessor to get url, but its not giving me anything  
            $monolog->pushProcessor(new WebProcessor($_SERVER));
            $monolog->pushProcessor(function ($record) {
                $record['extra']['session_id'] = Cookie::get(config('session.cookie'));
                $record['extra']['request_id'] = Session::get('request_id');
                return $record;
            });

            $slackHandler = new SlackHandler(env('SLACK_TOKEN'), '#gs-logs', 'GS-Log', true, ':warning:', Logger::ERROR);
               
                        //****************** Setup Line Formatter but no lock 
            // the default date format is "Y-m-d H:i:s"
            $dateFormat = "Y n j, g:i a";
            // the default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
            $output = "%datetime% > %level_name% > %message% %context% %extra%\n";
            // finally, create a formatter
            $formatter = new LineFormatter($output, $dateFormat);
            $slackHandler->setFormatter($formatter);

            $monolog->pushHandler($slackHandler);
        }
    }

Above code is giving me below response

exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
Stack trace:
#0 /home/vagrant/Code/App/app/Http/Controllers/PortfolioController.php(30): Illuminate\Database\Eloquent\Builder->firstOrFail()
#1 [internal function]: App\Http\Controllers\PorofileController->show('users')
#2 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(246): call_user_func_array(Array, Array)
#3 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(162): Illuminate\Routing\Controller->callAction('show', Array)
#4 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(107): Illuminate\Routing\ControllerDispatcher->call(Object(App\Http\Controllers\PortfolioController), Object(Illuminate\Routing\Route), 'show')
#5 [internal function]: Illuminate\Routing\ControllerDispatcher->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
#6 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(141): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#7 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#8 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(101): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#9 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(108): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(67): Illuminate\Routing\ControllerDispatcher->callWithinStack(Object(App\Http\Controllers\PortfolioController), Object(I…

Level
----------------
ERROR

*Where is the requested URL and session data??

How can I get only below part with requested URL

exception 'Illuminate\Database\Eloquent\ModelNotFoundException' with message 'No query results for model [App\User].' in /home/vagrant/Code/App/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:151
19 Sep
3 years ago

saqueib left a reply on [L5.1] Testing With Select2 JQuery Plugin

Try adding tags[] as name of field

saqueib left a reply on Insert And Attach Tag To The Post In Same Time

You have to create the relation in Post model like this

public function tags()
{
        return $this->belongsToMany('App\Tag')->withTimestamps();
}

Now you can call as @sid405 suggested to save the tag on post model relation

public function store(Request $request)
{
        $post = Posts::create($request); //insert posts table
        $post->tags()->attach(['name' => $request->input('tag')); //attach tag to the post
}