saqueib

saqueib

Senior Web Developer at New Delhi

Member Since 4 Years Ago

New Delhi

Experience Points
8,260
Total
Experience

1,740 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
39
Lessons
Completed
Best Reply Awards
3
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.

Level 2
8,260 XP
18 Sep
4 days ago

saqueib left a reply on Add Axios Interceptor On Nova Requests

Here is how I manage to do it to focus on the input on error.

Nova.request().interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        // Focus first input field with error
        let firstError = Object.keys(error.response.data.errors)[0];
        let input = document.getElementById(firstError);

        if(input) input.focus()
        
        
        return Promise.reject(error);
    });

But I think its good idea to just add it in nova itself.

I still can't handle the exception from app/Exceptions/Handler.php can someone help

11 Sep
1 week ago

saqueib started a new conversation Add Axios Interceptor On Nova Requests

I there any way I can add interceptor for axios used in laravel nova. I have long-form I need to focus on the first error field if there is some validation error.

I already have some route beforeach hook running fine


// this is working fine
Nova.booting((Vue, router, store) => {
router.beforeEach((to, from, next) => {
    ...
    next()
})

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    // Do something with response error
    // NOT LOGING ANYTHING IN CONSOLE
    console.log(error.response)
    return Promise.reject(error);
});

I also can't handle the exception from app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
    // nothing is dumped on validation error
    dd($exception);

    return parent::render($request, $exception);
}

I am using Laravel 5.8 and Nova v2.3.0, please help guys

16 Aug
1 month ago

saqueib left a reply on How Edit A Reply Fills Markdown In Laracasts Forum Model

@bobbybouwmann Great! do you know which library @JeffreyWay is using to do the conversion?

15 Aug
1 month ago

saqueib left a reply on When A Route URL Is Same As The Package Name, That URL Does Not Work

If you have a lot of routes defined then you should try re-ordering them to see if it works, most of the time's route definition get overwritten by other lines.

If you can share your route file then it will be easy to help

saqueib left a reply on Remove Code On Click On A Button.

Since you are appending some HTML on a click. Events are not bound to the button you just added.

You need to change your click handler to use on or live (prior to 1.7 jquery)

$('.comments-section') .on("click", ".questions-section__button-cancel", function () { });

    var questionSectionCommentReply = $('.questions-section__comment-reply');

    $('.questions-section__comment-reply > .questions-section__body').remove();
  })

check more here https://stackoverflow.com/questions/4944293/jquery-liveclick-vs-click

saqueib left a reply on SQLite Driver Installed But Not Seen!

It looks like SQLite driver is not installed. You can test it by putting the following code at the top in public/index.php


$dir = 'sqlite:/database/database.sqlite';
$dbh  = new PDO($dir) or die("cannot open the database");
dd($dbh);

It should not give you cannot open the database

saqueib left a reply on Slug Validation

Your implementation looks good. I would suggest if you have an input for a slug from the user then you should prefer the client-side value for the slug, but if it is only going to be generated based on the title without any option to change it from client-side then you don't need anything else.

As saying goes, "Never trust user" so it's good you have a fallback setup.

saqueib started a new conversation How Edit A Reply Fills Markdown In Laracasts Forum Model

I wanted to know how the edited reply is implemented. What I think it stores body in markdown and it's converted to HTML when requested by view.

But when you click on edit reply it doesn't make any ajax request to get the reply markdown to prefill the textarea.

Does anyone know how it's done? Is @JeffreyWay using some frontend HTML to markdown converter?

saqueib left a reply on Cannot Access Attributes Of A Model In View.

It looks like you dont have relation setup in you post model, add the relation and it should work


class Post extends Model {
     //...
     
     public function author() {
          return $this->belongsTo(User::class, 'author_id');
     }
}

Share your model and posts table info if you need more help

12 Feb
7 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 sections.sun.options value
    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;
}

I want to update the options.value which will be path like this array_set($config, "sections.sun.options.0.value", " updated");

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.

maybe with additional where clause on Rule:unique('revisions')->where(???)

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 a 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 it's 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 it's not working, I have tried following

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

this gives error no column like_count from DB

Post::whereNotNull('published_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);

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

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

since I m checking the file for existence before returning response I don't understand whats wrong here

if( Storage::disk('s3')->exists($file_path) ) {
 //... this confirms file is present
}

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

I am uploading files tos3 I want it to download securely using following code, but it's not working. I am using Laravel 5.5 and files visibility is not public on s3.

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

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

It's 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
2 years 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', 'admin');
})->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 limit(5) as a collection.

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

here is table structure-

users
- id
- name
- email

roles
- id
- name

role_user
- user_id
- role_id

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 ????

Check out the demo of app which is now working fine http://www.qcode.in/youtube-like-app-vue-js-laravel/

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 ).

See the image http://image.prntscr.com/image/4e3582058f9d4cc0ba84cb50e1d06499.png

Already tried all of them since last 2 days did everything find on google, 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, same app is working on localhost but not working on the server.

Main problem what I see it not able to set the cookies (laravel_session & XSRF-TOKEN)

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

Alos tried by changing APP_URL & SESSION_DOMAIN, no luck.

Laravel Framework 5.4.16

Kernel Middleware

'web' => [
            \Illuminate\Session\Middleware\StartSession::class,
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
        ],

.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. please help guys

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/browserify, 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

you can also check in console that Vue.http is available, it should not be undefined.

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 initialization code in app.js.

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 (src) {
            this.src = src;
        }
    }
</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. 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::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 Don't Have Replies

I wanted to get all the Post which do not have any replies post by type a, here is Post Model & relation. Please help how can I do it in Eloquent

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

posts 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

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 @JeffreyWay 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 in one result. I wanted to loaded only Post or Comment. like

Activity::with('post')->get(); 
Activity::with('comment')->get();

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. Here is a game, 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 <code> and <pre> 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' ...]);
                }])
                ->where('status', 'Public')
//***************** Adding Limit clause not working *****************//
                ->select(['id', 'title', 'body', ...])
                ->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', ...]);
            }])
            ->where([
              'status' => 'Public'
            ])
            ->paginate( intval(config('listing_qa_per_page', 20)), 
               ['id', 'title', ...]);

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.