FareedR

FareedR

Member Since 2 Years Ago

Experience Points
11,330
Total
Experience

3,670 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
23
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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 3
11,330 XP
Jul
05
1 month ago
Activity icon

Started a new Conversation Proeng - JsValidation

i got an error during my index( ) "Undefined variable: validator" . How can I solve it ?

how can i return $validator in index method ?

protected $validationRules = [
        'state'         => 'required',
        'cost'          => 'required'
    ];
public function index ()
{
	return view('home');
}
public function store(Request $request)
    {
        $validation = Validator::make($request->all(), $this->validationRules);
    
        if ($validation->fails()) {
            return redirect()->back()->withErrors($validation->errors());
        }
    
        // do store stuff
    }
// blade
<form action="{{ route('project.store') }}" method="post" id="projectForm">
	<div class="form-group">
		<label for="input-cost">Total Cost of Project (RM) <span class="text-primary">*</span> </label>
		<input type="text" name="cost" class="form-control" >
	</div>
</form>

// my script
<script type="text/javascript" src="{{ asset('vendor/jsvalidation/js/jsvalidation.js')}}"></script>
{!! $validator->selector('#projectForm') !!}
Jun
30
1 month ago
Activity icon

Replied to How Can I Use This As A Helper?

@jlrdw i think i already did that in helpers.php ?

Activity icon

Replied to How Can I Use This As A Helper?

@jlrdw i tried .

// helpers.php
namespace App;

use App\User;

class Helpers {
   public static function generateLoginId() {
        $number = mt_rand(1000000000, 9999999999); // better than rand()
        if (loginIdExists($number)) {
            return generateLoginId();
        }

        return $number;
    }
    
    public static function loginIdExists($number) {
        $concated_number = 'MLI'.$number;
        return User::where('login_id',$concated_number)->exists();
    }
}

// composer.json
"autoload": {
        "psr-4": {
            "App\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/helpers.php"
        ]
    },

// controller 
use App\Helpers;

$test = Helpers::generateLoginId();
dd($test);
Activity icon

Replied to How Can I Use This As A Helper?

@jlrdw ya i put that static function in Helpers block

Activity icon

Replied to How Can I Use This As A Helper?

@jlrdw current script as below . but i got an error like above .

use App\Helpers;

$test = Helpers::generateLoginId();
dd($test);
Activity icon

Started a new Conversation How Can I Use This As A Helper?

I got an error "Call to undefined function App\loginIdExists()" anyone can show the right method ?

public static function generateLoginId() {
        $number = mt_rand(1000000000, 9999999999); // better than rand()
    
        // call the same function if the barcode exists already
        if (loginIdExists($number)) {
            return generateLoginId();
        }
        // otherwise, it's valid and can be used
        return $number;
    }
    
    public static function loginIdExists($number) {
        // query the database and return a boolean
        // for instance, it might look like this in Laravel
        $concated_number = 'COD'.$number;
        return User::where('login_id',$concated_number)->exists();
    }
Activity icon

Replied to Prevent Faker From Repeating The Same Number

@michaloravec thank you for your reply . but your method will not random the id right ?

Activity icon

Started a new Conversation Prevent Faker From Repeating The Same Number

How can I prevent faker to repeat the same number ?

for($d = 0; $d <= 3; $d++){
	$project_facilitation = new ProjectFacilitation([
		'company_project_id'        => $company_project->id,
                'setting_facilitation_id'      => $faker->numberBetween(1,4)
        ]);
       $project_facilitation->save();
}
Current Result
company_project_id | setting_facilitation_id
1						1
1						1
1						1
1						3

Expected result
company_project_id | setting_facilitation_id
1						1
1						3
1						2
1						4
Jun
07
2 months ago
Activity icon

Started a new Conversation Eloquent WhereDoesntHave()

how can i find company project that doesnt have any pics(person in charge) based on their category name yet ? am i doing it correctly?

$project = CompanyProject::whereHas('company', function ($query) use ($setting_industry){
                    $query->where('category',$setting_industry->name);
                })->whereDoesntHave('pics')->where('is_approved',1)->first();
Jun
06
2 months ago
Activity icon

Replied to Customize Authentication Process

solved already . thank you for your time

Jun
05
2 months ago
Activity icon

Started a new Conversation Customize Authentication Process

currently working on custom login which is user need to enter 'login_id' and 'password' , how can I customize?

$this->validate($request,[
            'login_id' => 'required|',
            'password' => 'required|min:8'
        ]);

May
20
2 months ago
Activity icon

Replied to List All Users That Has Guard_name "api" Spatie

so far it works . but im confused . how can superadmin ( web ) able to view all user ( api ) , you know what i mean ?

May
19
2 months ago
Activity icon

Started a new Conversation List All Users That Has Guard_name "api" Spatie

how can i list all users that has guard name "api" . laravel return " There is no role named user. "

//packages used spatie permission

        $users = User::role('user')->get();

May
15
2 months ago
Activity icon

Replied to Has Anyone Worked With Laravel, Socket.io And Flutter ?

@princeoo7 any luck on setup laravel , socketio and flutter ?

May
13
2 months ago
Activity icon

Started a new Conversation Return Filtered Data Using Hash Fragment

how can I achieve user journey as below

User select filter data > send to backend > processed data > return view with hash fragment with processed data

...

foreach($grouped as $group){
	$total_profit[] = isset($group['Profit']) ? count($group['Profit']) : 0;
	$total_loss[] = isset($group['Loss']) ? count($group['Loss']) : 0;
}
return redirect(route('home') . '#hash'); // how to compact above variable ? 

May
09
3 months ago
Activity icon

Replied to Count Data Based On Specific Data Set .

i tried

$characters = Character::all();

        foreach($characters as $key_character => $character){
            if(Str::startsWith($character->character, $dataset)){
		// how to count status that only profit ? 
            }
        }
Activity icon

Started a new Conversation Count Data Based On Specific Data Set .

how can i count data that has been imploded in database . Current method is only valid for single data like id number 2 and 3.

$dataset = ['A','B','C','D'];

//db
id | character | status |
1        A?B     Profit
2        A         Profit
3        B         Loss
4        C?B     Profit
5        B?A     Profit

//expected result 
         Profit      Loss
A           2           0
B           1           1
C           1           0

// current method
$a = Stock::whereIn('character',$dataset)->get();  
May
08
3 months ago
Activity icon

Replied to Sum Specific String

actually column 'activity' at table activities , not in table users .

Activity icon

Replied to Sum Specific String

i dont understand , can you show the method ?

Activity icon

Started a new Conversation Sum Specific String

How can I sum specific string from database for specific user and specific role . i managed to get all user based on their role . but i stuck to sum all specific string .

// current method
 $pickers = User::role('picker')->get();
        foreach($pickers as $key_picker => $picker){
            $stock_pickers[$key_picker] = DB::table('activities')->select(DB::raw('SUM(profit) as total_profit'), DB::raw('SUM(loss) as total_loss'))->where('user_id',$picker->id)->get();
        }
        dd($stock_pickers);
//db 
id | user_id | activity
1	1			Profit
2	1			Loss
3	1			Profit
4	1			A
5	1			C
6	1			Profit
7	1			Loss
8	1			Profit

// expected result
total_profit = 4
total_loss = 2
total_A = 1
total_C = 1
Apr
20
3 months ago
Activity icon

Replied to Display Only Profit Stocks

i tried that code before this . still no luck . i got this error

Unknown column 'SUM(profit) ' in 'having clause' .......
Apr
19
3 months ago
Activity icon

Started a new Conversation Display Only Profit Stocks

How can I eliminate stocks that have more total loss than total profit

$profit_stocks          = DB::table('stocks')->select('signal',DB::raw('SUM(profit) as total_profit'), DB::raw('SUM(loss) as total_loss'))->having('total_profit', '>', 'total_loss')->orderBy('total_profit','desc')->groupBy('signal')->get();


//current result 
0 =>  {
	total profit => 4
	total loss  => 11
}

1 =>  {
	total profit => 3
	total loss  => 2
}

2 = > {
	total profit => 11
	total loss  => 2
}
//expected result 
0 =>  {
	total profit => 3
	total loss  => 2
}

1 = > {
	total profit => 11
	total loss  => 2
}

Apr
09
4 months ago
Activity icon

Replied to How Can I Calculate Total In Relation Table

i've tried based on your way . somehow i get this error .

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'stocks.stocks.profit' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

$total_profit_earned = Stock::query()->leftJoin('earnings', 'stocks.id', '=', 'earnings.stock_id')
        ->select('stocks.signal', 'stocks.profit','earnings.earn')
        ->selectRaw('SUM(earnings.earn) as total_profit_earn')
        ->groupBy('stocks.signal')
        ->orderBy('stocks.profit','desc')
        ->get();
Activity icon

Started a new Conversation How Can I Calculate Total In Relation Table

Basically I need to calculate total profit that groupBy with signal . How can i achieve it ? https://pastebin.com/SLpLjhEM ( example db )

expected result
Signal CTH
Profit 200
Loss -100

Signal BTH
Profit 500
Loss 0
Apr
08
4 months ago
Activity icon

Replied to Using GroupBy On WhereColumn()

i tried this before but error occured " SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'stocks.stocks.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from stocks where profit > loss and stocks.deleted_at is null group by signal order by profit desc) " . is it best practices to change the strict status on mysql ?

Activity icon

Started a new Conversation Using GroupBy On WhereColumn()

how can i groupBy using whereColumn() ?

$profit_stocks = Stock::where(function($q){
	$q->whereColumn('profit','>','loss')->orderBy('profit','desc');
})->groupBy('signal')->get();

// database
id | profit | loss | signal |
1	4		2	ABC
2	4		3	ABC
// expected result 
ABC
Activity icon

Replied to In_array Key And List Of Data

my mistake on frontend . it solved now

Apr
07
4 months ago
Activity icon

Started a new Conversation In_array Key And List Of Data

so i got a form that need to tick (checkbox). and the tick(checkbox) is an array . am i missing somewhere ?

$is_contradicts    = $request->has('contradict');
$contradicts = [];

if($is_contradicts){
	$contradicts = $request->get('contradict');
}

foreach ($time_frames as $key => $time_frame){
	$analysis = new Analysis([
		'stock_id'      => $stock->id,
                'time_frame'    => $time_frame,
                'description'   => $descriptions[$key],
                'is_contradict' => in_array($key,$contradicts) ? 1 : 0
	]);
	$analysis->save();
}
//example contradicts
0 => '1'

dd(in_array($key,$contradicts); // false -- supposedly true right ??

//result
// db analyses
stock_id | time_frame | description | is_contradict
1			10			Week		0

// expected result
// db analyses
stock_id | time_frame | description | is_contradict
1			10			Week		1

Apr
01
4 months ago
Activity icon

Replied to How To Not Loop The Same Data In Foreach ?

actually the selection is for searching . and i already solved it by using this method ..

 $dates = $stocks->unique(function($item){
return Carbon::parse($item['created_at'])->format('Y-m-d');
});
Activity icon

Replied to How To Not Loop The Same Data In Foreach ?

actually created_at is timestamps . so it got date and time . how can i use unique method , wihout time ?

Activity icon

Started a new Conversation How To Not Loop The Same Data In Foreach ?

Currently I need to display selection of created_at for searching . How can I loop only ONE date . For an example

//db

id | title |created_at | 
1	A	2020-02-3
2	B	2020-02-3
3     	C	2020-02-3
4      D	2020-02-4

//current result
2020-02-3
2020-02-3
2020-02-3
2020-02-4

//expected result
2020-02-3
2020-02-4
Mar
19
4 months ago
Activity icon

Started a new Conversation Calculation On Data Array

How can I calculate total amount ?

$service_fee = 4
// deals
id | price | qty | 
1      100       1
2      100       1

        foreach($deals as $deal){
            $subTotal           = $deal->price*$deal->qty;
            $serviceCharge      = (100-$service_fee)/100;
            $seller_total_earn  = $subTotal*$serviceCharge;
        }
Mar
18
4 months ago
Activity icon

Started a new Conversation Error On Spatie/Browsershot

I already put puppeteer on global. But I still get this error . I google it still no luck . " No such file or directory ". The long error said "Exit Code: 1(General error)↵↵Working directory: MyPC/project/public↵↵Output:↵================↵↵↵Error Output:↵================↵{ Error: ENOENT: no such file or directory, open '/MyPC/project/storage/app/public/invoice/394787d3-c3fd-44cf-90a8-7bd9bcb60e1d/invoice_2020_3.pdf'↵ -- ASYNC --↵ at Page. "

The command "PATH=$PATH:/usr/local/bin NODE_PATH=


// Current Code
Browsershot::url(route('invoice',[$seller_id, $month, $year]))
        ->setNodeBinary(env('NODE_PATH'))
        ->setNpmBinary(env('NPM_PATH'))
        ->setOption('landscape', true)
        ->margins(10, 10, 10, 10)
        ->showBackground()
        ->emulateMedia("screen")
        ->format('A4')
        ->save(storage_path('app/public').'/invoice/'.$seller_id.'/'."invoice_".$year.'_'.$month.'.pdf');
Activity icon

Replied to Retrieve Data Based On Specific Date

I solved it by using this method . But how can i merge with year ?

Deal::whereHas('post',function ($q) use ($seller_id){
                    $q->withoutGlobalScopes(['activePost'])->where('user_id',$seller_id);
                })->whereIn('status',['Received','Completed'])->whereMonth('updated_at',$month)->get();
Activity icon

Started a new Conversation Retrieve Data Based On Specific Date

Currently make some feature for seller able to download invoice based on month. So seller can choose which month that they want . Somehow my query doesnt work and keep taking wrong data . Anyone can help ?

$month = "3" ( STRING ) 
$seller_id = 1
// database 
posts
id | title | user_id |
1       test	1
2      test2	2
deals
id | post_id | status |updated_at 
1	1		Received	2020-03-01
2	1		Received	2020-03-01
3	2		Completed	2020-02-01
4	2		Dealing		2020-03-01
$deal = Deal::whereHas('post',function ($q) use ($seller_id){
	$q->where('user_id',$seller_id);
	})->whereMonth('updated_at',$month)->where('status','Received')->orWhere('status','Completed')->get();

expected result 
$deal = 2 ( id => 1,2 )

current result = 3  ( id => 1,2,4 )
Activity icon

Started a new Conversation Add Custom Blade In Markdown

Currently working on with Markdown. And I added custom view for "image". But laravel.log sent me " View [image] not found. Anyone know how to fix it ? The reason i add new custom view for "image" because i want image that align center.

// vendor/mail/html/image.blade.php
<table class="action" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
    <tr>
        <td align="center">
            <table width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation">
                <tr>
                    <td align="center">
                        <table border="0" cellpadding="0" cellspacing="0" role="presentation">
                            <tr>
                                <td>
                                    <img style="width:100px;" src="{{ $url }}">{{ $slot }}
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
// Markdown Notification
@component('mail::message')
@component('mail::image', ['url' => asset('/mailing_images/mail.png')])
@endcomponent

Hey {{ strtoupper($user->name) }},

Yahoooooo! Thanks for registering an account with us! 

Before we get started, we'll need to verify your email.

@component('mail::button', ['url' => $url, 'color' => 'amazon', 'transform' => 'text-uppercase'])
Verify Email
@endcomponent

Thanks, <br/>
{{ config('app.name') }} TEAM
@endcomponent

Mar
17
4 months ago
Activity icon

Started a new Conversation How To Make 2nd Row Align Right In Markdown ?

@component('mail::message')
@component('mail::image', ['url' => asset('/mailing_images/invoice.png')])
@endcomponent

Hey {{ strtoupper($deal->buyer->name) }},

Thank you for purchasing at ********! This is a copy of your receipt.

@component('mail::image', ['url' => asset('/mailing_images/invoice.png')])
@endcomponent

Purchase Details

@component('mail::table')
|  #            | Qty          | 	Price ($) 
| :----------  |:-------------:| 	--------: 
|Left Align|Center Align |Right Align
|Left Align|Right Align    |Right Align
@endcomponent


Thanks,<br>
{{ config('app.name') }} TEAM
@endcomponent

Mar
16
4 months ago
Activity icon

Replied to How Can I Put Space In .env ?

thankyou for your quick response . i didnt know .env can do that . lol

Activity icon

Started a new Conversation How Can I Put Space In .env ?

How can I change APP_NAME = MY RECIPE instead of APP_NAME = MY_RECIPE ?

Mar
10
5 months ago
Activity icon

Replied to How Can I Ignore Data That Equal With Another Field ?

instead of using "where" , im using "whereColumn" . didnt realized about that ..

$profit_stocks = Stock::whereColumn('profit','>','loss')->orderBy('profit','desc')->get();
$loss_stocks   = Stock::whereColumn('loss','>','profit')->orderBy('loss','desc')->get();	

// current result == expected result 
Activity icon

Replied to How Can I Ignore Data That Equal With Another Field ?

yes . im trying to get a single profit row .

use case : if profit equal to loss / loss equal to profit = dont display it if profit greater than loss / loss greater than profit = display it

Activity icon

Replied to How Can I Ignore Data That Equal With Another Field ?

oh wait sir , i tried to play around with the data

id | profit | loss |  name 
1        100        1	abc
2        1          100	abcd

// expected result 
Profit = abc
Loss = abcd

// current result 
Empty 

how can I change query on ->where('profit',0) ? 
Activity icon

Replied to How Can I Ignore Data That Equal With Another Field ?

thankyou for your time . is this the best practices to make a query ? what i mean is more readable point -> to the next line ?

Stock::where('loss','>','0')
                         ->where('profit', 0)
                         ->orderBy('loss','desc')
                         ->get();
Activity icon

Replied to How Can I Ignore Data That Equal With Another Field ?

im using the 2nd option . For loss , i get it right . Somehow for profit . i get it wrong . I fixed few LoC on your option

// controller 

$profit_stocks  = Stock::where('profit','>','0')->where('loss', '<>', 0)->orderBy('profit','desc')->get();
$loss_stocks    = Stock::where('loss','>','0')->whereNotIn('id',[$profit_stocks->pluck('id')])->orderBy('loss','desc')->get();

// current result 

Profit = abc, abcde
Loss   = abcd
Activity icon

Started a new Conversation How Can I Ignore Data That Equal With Another Field ?

// controller
$loss_stocks            = Stock::where('profit','>','0')->orderBy('profit','desc')->get();
$loss_stocks            = Stock::where('loss','>','0')->orderBy('loss','desc')->get();

// database

id | profit | loss | name |
1	1		1	abc
2	0		1	abcd
2	1		0	abcde

//expected result
Profit = abcde
Loss   = abcd

//current result
Profit = abc , abcde
Loss   = abc, abcd, abcde

Activity icon

Replied to Intersect Value In Array

its done . thank you !

Activity icon

Started a new Conversation Intersect Value In Array

How can i merge if the value is same

// controller 
foreach($stocks as $stock){
            $signals[] = explode('+',$stock->signal);
            $time_frames[] = explode(',',$stock->time_frame);
        }
return view('stocks.custom',compact('stocks','signals','time_frames'));

//database 

id | timeframe | signal |
1      300,300,3     PLT+SLT+TNT

// expected result in blade
300 : 3
PLT   TNT
+
SLT

// current result in blade
300 : 300 : 3
PLT   SLT    TNT
Activity icon

Replied to How Can I Iterate Imploded Data With Another Imploded Data ?

sorry for the late reply . all is good now . thank you for your time sir

Mar
09
5 months ago
Activity icon

Replied to How Can I Iterate Imploded Data With Another Imploded Data ?

im using the first one because more readable , but somehow the foreach doesnt work . what i get is " 5: test2" , only trigger the last index .

@foreach(array_combine(explode(',', $stock->time_frame), explode(',', $stock->signal)) as $key => $value)
	{{ $key }}: {{ $value}}
	@unless($loop->last)
	<br /> <span style="padding-left:10px;">+</span> <br />
	@endunless
@endforeach