SNaRe

Experience

17,915

6 Best Reply Awards

  • Member Since 4 Years Ago
  • 120 Lessons Completed
  • 2 Favorites

21st September, 2018

SNaRe left a reply on How To Dispatch A Job From As I Do From Controller • 1 month ago

I have finally found the solution. It's a very silly problem though. The problem is due to the terminal.

export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8

solves the problem

SNaRe left a reply on Dispatching Jobs From Tinker Error • 1 month ago

I'm using laravel 5.6 and redis connection I couldn't solved this issue. Any help would be very nice.

17th September, 2018

SNaRe started a new conversation Dispatching Jobs From Tinker Error • 1 month ago

Hi,

I can dispatch my job from controller. But when I try to dispatch from php artisan tinker it gives me error. What could be the problem.

Note: I only use redis::funnel and it functions very well while I dispatch job from controller.



Psy Shell v0.9.6 (PHP 7.2.5-1+ubuntu16.04.1+deb.sury.org+1 — cli) by Justin Hileman
>>> dispatch(new \App\Jobs\someJob(2600))->onQueue('P-4')

=> Illuminate\Foundation\Bus\PendingDispatch {#3168}
>>> dispatch(new \App\Jobs\someJob(2600))->onQueue('P-4')


Predis/ClientException with message 'Command 'iNCR' is not a registered Redis command.'

>>> dispatch(new \App\Jobs\someJob(2600))->onQueue('P-4')
=> Illuminate\Foundation\Bus\PendingDispatch {#3181}

>>> dispatch(new \App\Jobs\someJob(2600))->onQueue('P-4')

Predis/ClientException with message 'Command 'iNCR' is not a registered Redis command.'
PHP Fatal error:  Uncaught Predis\ClientException: Command 'iNCR' is not a registered Redis command. in /home/forge/mutlumusteri.com/vendor/predis/predis/src/Profile/RedisProfile.php:88
Stack trace:
#0 /home/forge/mutlumusteri.com/vendor/predis/predis/src/Client.php(323): Predis\Profile\RedisProfile->createCommand('iNCR', Array)
#1 /home/forge/mutlumusteri.com/vendor/predis/predis/src/Client.php(314): Predis\Client->createCommand('incr', Array)
#2 /home/forge/mutlumusteri.com/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(96): Predis\Client->__call('incr', Array)
#3 /home/forge/mutlumusteri.com/vendor/laravel/framework/src/Illuminate/Redis/Connections/Connection.php(108): Illuminate\Redis\Connections\Connection->command('incr', Array)
#4 /home/forge/mutlumusteri.com/vendor/laravel/horizon/src/Repositories/RedisJobRepository.php(65): Illuminate\Redis\Connections\Connection->__call('incr', Array)
#5 /home/forge/mutlumusteri.com/vendor/laravel/horizon/src/JobId.php(27): Laravel\Horizon\Repositories\Redis in /home/forge/mutlumusteri.com/vendor/predis/predis/src/Profile/RedisProfile.php on line 88

16th September, 2018

SNaRe started a new conversation Forge Horizon Daemon Fail Notice • 1 month ago

Hi, Sometimes my horizon daemon fails due to lack of ram memory with error of

daemon-37304                     FATAL     Exited too quickly (process log may have details) 

and when it fails.

After restarting in forge panel it normally runs. So tried to simulate the restart of the deamon by terminating horizon. I check the status of horizon in App\Console\Kernel.php and when it fails I run

    shell_exec("cd /home/forge/my_domain.com && php artisan horizon:terminate");

this command. But the it doesn't works. How can I simulate restart daemon in forge's panel.

SNaRe started a new conversation How To Make A Script For Daemon • 1 month ago

Hi, I have a python script that should always run. Could I just add the script directly as new daemon or Daemon checks anything that I should add to my script? Thanks in advance.

11th September, 2018

SNaRe left a reply on Forge & Horizon: Process Exited Too Quickly • 1 month ago

Hi @eelcol I’am having the same issue. Sometimes horizon stops working and when I look at deamons status

‘’’ daemon-37304 FATAL Exited too quickly (process log may have details)’’’

And when I restart only the php artisan horizon deamon it works. How can I fix this?

1st August, 2018

SNaRe started a new conversation Sending Request To A Post Controller Function From Another Controller Function • 2 months ago

I have a controller like this.

public function barcode_approve(Request $request)
{
    $barcodes = $request->input('barcode_values');
    $upload_ids = $request->input('upload_id');
    ....
}

It is defined as post in route without any problem.

Route::post('my/url','[email protected]_approve');

I would like to use barcode_approve by sending request from controller like

public function push_approve(){

    $request = ['barcode_values' => '23ssdwe','upload_id'=>234234];

    $this->barcode_approve($request);
    .....

} 

But $reqeust->input doesn't give the value when I send it through controller function (push_approve)

How can I send values from another controller function as input in $request?

12th July, 2018

SNaRe started a new conversation ERR_SPDY_PING_FAILED Error With Uploader Chrome ( DropZone ) • 3 months ago

I have an uploader based on http://www.dropzonejs.com/

When I upload a file bigger than 3 MB ( 13 MB ) with Chrome, I recieve ERR_SPDY_PING_FAILED error in the console log.

When I upload the file, the progress bar stuck at a certain level. This is when we get this error.

I tried it with Safari, Firefox we don't have this problem.

I googled and found that others also complaining the same problem.

In this stackoverflow post, they proposed some solutions but I couldn't implement their solutions since they are based on other scripts.

https://stackoverflow.com/questions/27740692/request-stalled-for-a-long-time-occasionally-in-chrome/30772776#30772776

They proposed something like

$(document).ready(function() {
    $.keepalive =     
            setInterval(function() {
               $.ajax({
                  url: '/ping.html',
                  cache: false
               });         
            }, 60000);    
});

But I added this snippet to my file but it didn't work. Maybe I need a laravel solution rather than javascript.

I found this for laravel to keep alive.

https://github.com/Influendo/laravel-survivor

I am not sure how implement. Have you had any experience with it?

I just have a www.example.com/upload/document route.

I don't want to say visitors if they use chrome, you cannot upload bigger files than X MB...

11th July, 2018

SNaRe left a reply on Server Responded With 0 Code Error - Files Bigger Than 2MB • 3 months ago

server {

    listen 80;
    server_name .mu.tc;

    location = / {

        return 301 https://www.mutlumusteri.com/;
    }

    location / {

        try_files $uri $uri/ /index.php?$query_string;
    }

    root /home/forge/mutlumusteri.com/public;
    index index.html index.htm index.php;
    charset utf-8;
    include forge-conf/mutlumusteri.com/server/*;


    location = /favicon.ico {

        access_log off; log_not_found off;
    }
    location = /robots.txt {

        access_log off; log_not_found off;
    }
    error_page 404 /index.php;

    location ~ \.php$ {

        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {

        deny all;
    }


}

SNaRe left a reply on Server Responded With 0 Code Error - Files Bigger Than 2MB • 3 months ago

I didn't work @lostdreamer_nl

Where exactly should we put client_max_body_size 200M; in Forge nginx conf?

It is a little bit dynamic nginx file

SNaRe started a new conversation Server Responded With 0 Code Error • 3 months ago

I have been getting "Server responded with 0 code" error as I upload a big file.

My server is on Forge. ( I contacted with Forge team)

I have an upload form. It is working on DropZoneJs

I increased the php limits ( I restarted nginx I can see in phpinfo )

post_max_size=100M
upload_max_filesize=100M

I also played with Nginx settings by adding

    client_max_body_size 200M;

But I have been still getting the same error. I don't know what else to do?

9th July, 2018

SNaRe started a new conversation Getting Rid Of Error Log When Unauthenticated Redirect Fires • 3 months ago

If a user is not registered and tries to reach a page that needs authentication, I redirect the visitor to login with Bolierplate Laravel AuthCode.

However, when I check error log I receive and error. ( It works on client-side without any problems)

Illuminate\Auth\AuthenticationException: Unauthenticated. in /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/GuardHelpers.php:40 Stack trace: #0 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php(292): Illuminate\Auth\SessionGuard->authenticate() #1 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(57): Illuminate\Auth\AuthManager->__call('authenticate', Array) #2 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php(41): Illuminate\Auth\Middleware\Authenticate->authenticate(Array) #3 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Auth\Middleware\Authenticate->handle(Object(Illuminate\Http\Request), Object(Closure)) #4 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request)) #5 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(67): Illuminate\Routing\Pipeline->Illuminate\Routing\{closure}(Object(Illuminate\Http\Request)) #6 /home/forge/xyz.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(151): Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure)) #7 /home/forge/xyz.com/

Code: <?php

namespace App\Http\Controllers\Auth;

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

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

    use AuthenticatesUsers;

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

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

    public function logout()
    {
        $this->guard()->logout();

        return redirect()->route('login');
    }

}

5th July, 2018

SNaRe left a reply on SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column 'activation_key' In 'field List' • 3 months ago

Maybe it's about caching of configuration settings. If you changed settings in .env file this might be the reason. Did you tried php artisan config:cache command?

30th June, 2018

SNaRe started a new conversation Forge Nginx Configuration • 3 months ago

Hi,

First, I would like to redirect mydomain.com to www.mydomain.com

Secondly, I would like to host many subdomains in my project. For example when visitors visit asd.com and asd2.com they will all see the content in mydomain.com. Another problem is mydomain.com has default ssl that is provided by forge but asd.com and asd2.com doesn't have.

I added tried the code below but didn't work.

""" server { server_name mydomain.com; return 301 $scheme://www.mydomain.com$request_uri; } """

I added the code to projects nginx file after include forge-conf/mutlumusteri.com/before/*;

before server { proxy_connect_timeout 600; proxy_send_timeout 600; .......

SNaRe left a reply on Advice For Poor Api Services • 3 months ago

So sorry about my so late answer @lostdreamer_nl @CJJ I'm getting the data

7th June, 2018

SNaRe started a new conversation How To Use Laravel Collection GroupBy Along With Query Pagination? Ask Question • 4 months ago

I love using Laravel's groupBy function https://laravel.com/docs/5.6/collections#method-groupby

However, I cannot use it with paginate(x) function since it return a limited number of results. Groupby of SQL Query and Laravel Collections's GroupBy is totally different. If I use groupby in my query it doesn't give me what I want. For instance I just want to type and I got all I want.

$notifications = $notifications->groupBy('order_id');

For example this is my query

    $notifications = DB::table('sent_notifications as a')
        ->join('sent_notification_results as b', 'a.sent_notification_result_id', '=', 'b.sent_notification_result_id')
        ->join('orders as c', 'c.order_id', '=', 'a.order_id')
        ->join('sellers as d', 'c.seller_id', '=', 'd.seller_id')
        ->join('companies as e', 'd.company_id', '=', 'e.company_id')
        ->join('notification_templates as f', 'f.notification_template_id', '=', 'a.notification_template_id')
        ->join('notification_types as g', 'g.notification_type_id', '=', 'f.notification_type_id')
        ->join('default_notification_templates as h', 'h.default_notification_template_id', '=', 'f.default_notification_template_id')
        ->where('e.company_id', $company_id)
        ->select('e.company_id','d.name as seller_name', 'h.label', 'g.name as notification_type_name', 'b.name as notification_result_type','b.sent_notification_result_id', 'c.marketplace_order_number', 'a.created_at','a.notification_template_id','c.order_id','a.sent_notification_id')
        ->orderBy('a.created_at','DESC')
        ->paginate(20);
    $pagination_links = $notifications->links();

How can I use Collection's groupby method along with pagination?

5th June, 2018

SNaRe started a new conversation Disabiling View Cache&query Cache In Specific Controller With Laravel Ask Question • 4 months ago

I want to disable view cache for specific controllers since I need to see the latest data in the page.

I don't work with API's unfortunately so that I print some static data into my HTML.

When I render the page it shows me wrong values and I start to think like it is a bug.

How can I completely disable view,query whatever cache for specific controller?

27th May, 2018

SNaRe started a new conversation Notification When Deamon Fails • 4 months ago

Hi, I would like to get notification such as Slack, when an deamon fails i.e php artisan horizon.

How can I set it up? I searched so much but found no related content.

Thanks in advance

SNaRe left a reply on Dealing With Poor Api • 4 months ago

Any suggestions?

25th May, 2018

SNaRe started a new conversation Dealing With Poor Api • 4 months ago

Hi, I'm working with a very poor api. It's uptime is approximately %50 and in worst cases it decreases even more. I'm trying to get 100.000 api requests per day. The way api works is first I get the page then I get all items in page.

My question is what is the best way to deal with this this situation.

The solution I have reached so far is I have separated all api calls to different jobs to the queue. So if a job fails it retries again for 9 times but with this %5 of the jobs fails.

9th May, 2018

SNaRe started a new conversation Retrieving Old Input Even If Visitor Leaves The Page • 5 months ago

We can retrieve the old input with

But if I leave the page, the old "username" disappears.

I would like to show the "old" even user visits another page or comes back in the same session until the form is successfully posted.

The use case: Our website is dependent to 3rd party services and sometimes they crash. Our users type a long text and submit. But when it crashes it may take sometime(30 mins), they have to leave the page. But in this case the text disappears.

I don't want to save as draft or something for now. I would like to solve it on the fly like sessions maybe redis.

Please advise.

3rd May, 2018

SNaRe started a new conversation Getting Last Inserted ID With Laravel Ask Question • 5 months ago

I am trying to get the last inserted id when I create a new entry

I don't use ID as primary key, I use something called "notification_template_id" which is defined as protected $primaryKey ='notification_template_id'; in my model.

$create = [ 'subject' => isset($new_subject) ? $new_subject : '', 'body' => $new_body, 'is_active' => intval($new_status), 'default_notification_template_id' => (int)$default_info->default_notification_template_id, 'notification_type_id' => (int)$requested_info["notification_type_id"], 'company_id' => (int)$company_id, ];

$notification_template = NotificationTemplate::create($create); id = $notification_template->notification_template_id; When I try to get the last id it returns NULL,

I tried another way around,

$data = new NotificationTemplate;

$data->subject = isset($new_subject) ? $new_subject : '';
$data->body = $new_body;
$data->is_active = intval($new_status);
$data->default_notification_template_id = (int)$default_info->default_notification_template_id;
$data->notification_type_id = (int)$requested_info["notification_type_id"];
$data->company_id = (int)$company_id;
$data->save();

$id = $data->notification_template_id;

It returns NULL again

How can I solve this issue

SNaRe started a new conversation Advice For Poor Api Services • 5 months ago

I get information from an api services that crashes approximately every 5 minustes. And the amounth of data is very huge about 5gb per day. Could you give any advice from your experiexces? Thanks in advance.

MS7G.png

2nd May, 2018

SNaRe left a reply on Horizon Doesn't Show Failed Jobs On Forge • 5 months ago

Also I couldn't monitor tags. When I click "Monitor Tag" and wrote the tag name clicked "Monitor" nothing happens? Not: Horizon processes 8000 jobs per hour could the reason be related with this ?

SNaRe left a reply on Horizon Doesn't Show Failed Jobs On Forge • 5 months ago

Any thoughts what could be the reason?

30th April, 2018

SNaRe left a reply on Creating Public Url With Hashed Slug Parameter • 5 months ago

@Cronix the url is for customers and the page should be accessed without auth so with clicking url they could accessed the page

SNaRe started a new conversation Horizon Doesn't Show Failed Jobs On Forge • 5 months ago

In my local, horizon works perfectly and shows failed jobs.

Unfortunately, when I push on github and then forge. I couldn't see failed jobs on horizon dashboard.

When I look chrome developer tools I can see the failed jobs are coming but doesn't shown on the page. What could be the problem? Thanks in advance

I tried "composer dump-autoload -o" but nothing changed.

and my version: Laravel Framework 5.6.7

MoUg.png

28th April, 2018

SNaRe started a new conversation Creating Public Url With Hashed Slug Parameter • 5 months ago

I would like to have a page that can be reached by public but depending on the parameter on the URL, the access should be verified. Let me make it clear with an example.

compname.url.com/orderid/23424/{someHashedKey}

So orderid = 23424 is my DB primary key, compname is the unique name of order's company.

My plan is to create a hashed key with orderid and compname with some kind of salted hash.

So that when someone reaches to the page, I will create a hash(md5) from orderid,compname, and a salted hash and match with 'SomehashedKey'

Is this the best way or how should I do this?

25th April, 2018

SNaRe left a reply on Horizon Doesn't Retry Again • 5 months ago

Any help? Thanks in advance

22nd April, 2018

SNaRe left a reply on How To Dynamically Generate Queues In Laravel Horizon • 6 months ago

Thanks you all for your kind responses but if I set balance to auto user-2 can have 30 processes but it shouldnt be more than 1.

Do you have a solution for this?

And can I add dynamically queues array like the solution in middleware method?

Thanks a lot

SNaRe left a reply on How To Dynamically Generate Queues In Laravel Horizon • 6 months ago

Thanks for your reply :) You said that "I'm not a big fan of this" what could be other solutions ? In my case I have thousands of jobs for every user and these jobs should be processed one by one for every user

SNaRe started a new conversation How To Dynamically Generate Queues In Laravel Horizon • 6 months ago

My application requires to have dynamically generated queues with some prefix like

"process_user_1", "process_user_2", "process_user_n" The main idea is to separate execution of some jobs depends on model ID.

Because the api that I connect allows only 1 connection for a user

Normally I can configure in horizon.php but it should be dynamic e.g. I can have 1000 users so I must have 1000 different queues

What could be the solution?

This is my configuration

'User-1' => [ 'connection' => 'redis', 'queue' => ['User-1'], 'balance' => 'simple', 'processes' => 1, 'tries' => 10, ], 'User-2' => [ 'connection' => 'redis', 'queue' => ['User-2'], 'balance' => 'simple', 'processes' => 1, 'tries' => 10,

SNaRe started a new conversation Horizon Doesn't Retry Again • 6 months ago

Hi, I was trying to restart a failed job 2 days ago and it successfully completed the job. On the other hand now I try and doesn't retry the job only the circle turns around and nothing happens what could be the reason? Thanks in advance

19th April, 2018

SNaRe left a reply on Redirect With Session Doesn't Send Success Or Error • 6 months ago

Unfortunately this didn't work. I am wondering why this problem persists.

12th April, 2018

SNaRe left a reply on Passing A Model From A Function To Another • 6 months ago

Since the 1st one had return, I thought I don't need to return anything in the 2nd function. However, it seems that I am mistaken. @Joucke thank you

SNaRe started a new conversation Passing A Model From A Function To Another • 6 months ago

I have this Laravel snippet. I cal the function(1) from another function.

It gives me a "blank" page. I think it is something about model binding in here. Since the (1) function requires Request I have to send it inside the (2) But I think I am doing something wrong

function messages_without_product(Request $request,$message_type=0){ ...

}

function messages_without_product_answered(Request $request){ $this->messages_without_product($request,1); }

11th April, 2018

SNaRe started a new conversation Redirect With Session Doesn't Send Success Or Error • 6 months ago

I am on Laravel 5.6

I try to send success with session to show some success messages.

return redirect('templates')->with('success','Template added successfully'); It used to work perfectly. However, it stopped working now and I couldn't find the reasons why.

When I dd(redirect('templates')->with('success','Template added successfully');) I see success message inside it.

RedirectResponse {#438 ▼ #request: Request {#43 ▶} #session: Store {#279 ▼ #id: "9Qcvbynta2B3yrDPDGGj2UhPTjDsCgn1857UlQM0" #name: "laravel_session" #attributes: array:5 [▼ "_token" => "ngzN7cWaJIlYrQsCmfSdapbT1UnCJ7jxuld3VCeP" "_previous" => array:1 [▶] "_flash" => array:2 [▶] "login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 6 "success" => "Template Added Successfully" ] #handler: FileSessionHandler {#280 ▶} #started: true } But I try to read it in blade it doesn't show anything at all. As I said it used to work perfectly.

@if (\Session::has('success')) sdfsdf

<script>
    window.onload = function () {
        toastr.success("{{ \Session::get('success') }}");
    }
</script>

@endif I am thinking of my recent changes I put this 3 to middleware in kernel

    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \App\Http\Middleware\LimitDemoUser::class,

This is my full Kernel.php

9th April, 2018

SNaRe left a reply on UpdateOrCreate Always Create, Never Updates - Laravel Query Builder • 6 months ago

I found the problem. I didn't add default_notification_template_id to "insert" part of the query. So that it couldn't find any values. @m-rk thanks for investigating the problem with me.

SNaRe left a reply on UpdateOrCreate Always Create, Never Updates - Laravel Query Builder • 6 months ago

Yes notification_template_id is the primary key, default_notification_template_id is totally different something like a FK, but not.

SNaRe started a new conversation UpdateOrCreate Always Create, Never Updates - Laravel Query Builder • 6 months ago

I am trying to use updateOrCreate. However, although I don't change contents of my condition, it only creates, never updates an existing row.

  foreach($default_info as $default){
        $name = $default['notification_toggle_id'];

        $res = NotificationTemplate::updateOrCreate(
            [
                'notification_type_id' => (int)$requested_info["notification_type_id"],
                'company_id' => (int)$company_id,
                'default_notification_template_id' => (int)$default['default_notification_template_id']
            ],
            [
                'title' => 'foo',
                'body' => $requested_info[$name.'_description'],
                'is_active' => intval($requested_info[$name."_check"])
            ]
        );
    }

I even tried doing this to make sure nothing changes. But it doesn't update even this.

            'notification_type_id' => 66,
            'company_id' => 66,
            'default_notification_template_id' => 66

I tried this as well

public $incrementing = false; I dd() the result if it may give a hint. I couldn't find a trace to find the problem. It always create rather than updating the existing one with the condition in the first array

NotificationTemplate {#704 ▼ #dates: array:1 [▼ 0 => "deleted_at" ] #primaryKey: "notification_template_id" #fillable: array:5 [▼ 0 => "title" 1 => "body" 2 => "notification_type_id" 3 => "company_id" 4 => "is_active" ] #connection: "pgsql" #table: null #keyType: "int" +incrementing: true #with: [] #withCount: [] #perPage: 15 +exists: true +wasRecentlyCreated: true #attributes: array:8 [▼ "notification_type_id" => 1 "company_id" => 6 "title" => "foo" "body" => "bondy_content" "is_active" => 0 "updated_at" => "2018-04-09 18:59:34" "created_at" => "2018-04-09 18:59:34" "notification_template_id" => 42 ] #original: array:8 [▼ "notification_type_id" => 1 "company_id" => 6 "title" => "foo" "body" => "body_content" "is_active" => 0 "updated_at" => "2018-04-09 18:59:34" "created_at" => "2018-04-09 18:59:34" "notification_template_id" => 42 ] #changes: [] #casts: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] +timestamps: true #hidden: [] #visible: [] #guarded: array:1 [▼ 0 => "*" ] #forceDeleting: false }

SNaRe left a reply on Current User In Middleware • 6 months ago

It has been a year and still we have the same problem. I had to spend 3 hours to solve this issue @kennyS you rock!

8th April, 2018

SNaRe started a new conversation Restricting Access Of An User Based On A User Attribute Ask Question • 6 months ago

I have users table. These users table has company_id attribute.

I have some generic pages with ids for ex.

https://www.test.com/customer_question/p/4701/c/40960

This url needs to be access only if the logged in user has specific company_id. Otherwise some other people can just access to link by just incrementing IDS

So that in each controller ( index,store,update etc. ) I have to check with something like this

$company_id = Auth::user()->company_id;
$verify_seller = DB::table('sellers')
    ->select('*')
    ->where('company_id', '=', $company_id)
    ->get();

if ($verify_seller->isEmpty())
    return "This product neither belongs to your seller account nor another seller's product";

I think I can handle this by putting the code above to _construct function for each customer.

What is the best way to handle this kind of situation with Laravel?

Laravel version 5.6

6th April, 2018

SNaRe started a new conversation Laravel Builder Conditional Clauses That Can Return More Than 1 Condition Ask Question • 6 months ago

I want to add some extra clauses to my query only when I get a specific request

I can do it with https://laravel.com/docs/5.6/queries#conditional-clauses

->when($markeplace_id !=0, function ($query) use ($marketplace_id){
   return $query->join('seller b', 'a.seller_id', '=', 'b.seller_id')
});

->when($markeplace_id !=0, function ($query) use ($marketplace_id){
   return $query->join('marketplaces as c', 'c.marketplace_id', '=', 'b.marketplace_id')
});
->when($markeplace_id !=0, function ($query) use ($marketplace_id){
   return $query->where('c.marketplace_id','=',$marketplace_id)
});

Conditional-clauses only returns 1 clause. But I have 3. Should I use when 3 times or can I just bundle them in to 1 when ?

->join('sellers as b', 'a.seller_id', '=', 'b.seller_id')
->join('marketplaces as c', 'c.marketplace_id', '=', 'b.marketplace_id')
->where('c.marketplace_id','=',$marketplace_id)

3rd April, 2018

SNaRe started a new conversation Writing Better Query That Has WhereRaw • 6 months ago

I wrote a query like this. I thing whereRaw part could be written far better and eventually be more performant but I couldn't succeed.

DB::table('messages')
            ->select('*')
            ->where('message_type', '=', $message_type)
            ->whereIn('seller_id', $seller_id->pluck('seller_id'))
            ->whereNull('answer_id')
            ->whereRaw('market_place_id IN ( SELECT MAX(market_place_id) FROM messages GROUP BY product_id )', [], 'AND')
            ->orderBy('market_place_id', 'DESC')
            ->paginate(10);

30th March, 2018

SNaRe started a new conversation Best Practice To POST From Custom Route • 6 months ago

I have a custom route like this

questions/p/{product}/c/{customer}

The route is defined as

Route::get('questions/p/{product}/c/{customer}', '[email protected]');

In my page ( details ) questions/p/10/c/20 have an input box that I would like to post INSERT to DB by using variables {product} and {customer}

What is the best practice to deal with it? Adding PUT,PATCH,POST to Middleware or any other best practices? I don't want to do this in dirty way.

Thank you

27th March, 2018

SNaRe left a reply on How To Change Domain Name? • 6 months ago

I own a domain that I created on Forge. From now on I will be using another domain for my server. This is my case and I don't want to do it by redeploying :) I would have been great if I could just rename in forge, change NS in my Vultr account and ready to go

SNaRe left a reply on Search And Skip To Next Item In Collection • 6 months ago

@rin4ik it just find but doesn't find the next one.

@mdeorue What I couldn't understand about it is how does "current" knows the item that I set as current. Let's say for me 2 is the current one. But in your snippet it doesn't have a place?

BTW I solved like this but it doesn't seem to be the best way.

        $current_key =  $unanswered_messages_list->where('product_id',$product)->where('customer_id',$customer)->keys()->first();
        $next_key = $current_key +1;
        $next_page = $unanswered_messages_list->only($next_key)->first();

SNaRe started a new conversation Search And Skip To Next Item In Collection • 6 months ago

I have a collection below, which I would like to search and get the contents of the next items https://laravel.com/docs/5.6/collections#method-where

where() function would find for example. But I have 2 conditions.

$collection->where('product_id', '342')->toArray(); $collection->where('customer_id', '62')->toArray();

Let's say I figured out having 2 conditions inside collection

How can I get the contents of the next one? which is in this case +"product_id": 456 +"customer_id": 933

Collection {#630 ▼
  #items: array:14 [▼
    0 => {#638 ▼
      +"product_id": 378
      +"customer_id": 936
    }
    1 => {#635 ▼
      +"product_id": 342
      +"customer_id": 62
    }
    2 => {#597 ▼
      +"product_id": 456
      +"customer_id": 933
    }
    3 => {#632 ▼
      +"product_id": 450
      +"customer_id": 935
    }
    4 => {#633 ▼
      +"product_id": 435
      +"customer_id": 934
    }
  ]
}

26th March, 2018

SNaRe started a new conversation How To Change Domain Name? • 6 months ago

I want to change my domain name in forge.

I come up with a tweet of Taylor that Forge supports renaming servers.

https://twitter.com/taylorotwell/status/499656382417608706

Does that mean that it also changes the root domain name so that I can just enter my NS info to my new domain and change the domain name in Forge so ready to go?

The link in Taylor's tweet doesn't work so that I couldn't try renaming.

Can you please advise?

25th March, 2018

SNaRe left a reply on "prepareBindings() Must Be Of The Type Array, String Given" Problem • 6 months ago

Converting it to this solved my problem

        $unanswered_messages = DB::table('messages as yt')
            ->select('*')
            ->where('message_type', '=', 0)
            ->where('seller_id', '=', $seller_id)
            ->whereRaw('message_id = ( SELECT max(message_id) FROM messages st WHERE yt.customer_id = st.customer_id )', [], 'AND')
            ->get();
Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.