SilenceBringer

SilenceBringer

Member Since 4 Years Ago

Experience Points
100,270
Total
Experience

4,730 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
555
Lessons
Completed
Best Reply Awards
75
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 21
100,270 XP
Sep
27
23 hours ago
Activity icon

Awarded Best Reply on Get All Possible Elements From BelongsToMany Relationship

Hi @manojow

$products = Product::whereHas('categories', function ($query) {
    $query->whereIn('id', [1, 2]);
});
Activity icon

Awarded Best Reply on Testing Ability To Like A Post

@bjbt99 the problem is in your method

public function isLikedBy(User $user)
    {
        return (bool) $user->likes
            ->where('post_id', $this->id)
            ->where('liked', true)
            ->count();
    }

first one, possible likes relation not defined on User model

second one, I think it should be related to Post model, not User. So, I think, it should be something like

public function isLikedBy(User $user)
    {
        return $this // $this is a post instance
            ->likes()
            ->where('user_id', $user->id)
            ->where('liked', true)
            ->exists(); // you do not really need the count, use exists instead
    }
Activity icon

Replied to Testing Ability To Like A Post

@bjbt99 the problem is in your method

public function isLikedBy(User $user)
    {
        return (bool) $user->likes
            ->where('post_id', $this->id)
            ->where('liked', true)
            ->count();
    }

first one, possible likes relation not defined on User model

second one, I think it should be related to Post model, not User. So, I think, it should be something like

public function isLikedBy(User $user)
    {
        return $this // $this is a post instance
            ->likes()
            ->where('user_id', $user->id)
            ->where('liked', true)
            ->exists(); // you do not really need the count, use exists instead
    }
Activity icon

Replied to Index.php In Public Folder Is Not Loading Js And Css Files

Hi @zool if previously your index was in root (which is wrong at all), I think you have links to your css/js like /public/js/my.js. Then you move index file back to public, so, really links should be now like /js/my.js (without public prefix)

Activity icon

Replied to Testing Ability To Like A Post

Hi @bjbt99 I think something like:

/** @test */
    public function an_authenticated_user_can_like_a_post()
    {
        $this->withExceptionHandling();

        $this->signIn();

        $post = factory(Post::class)->create();

        // $like = factory(Like::class)->create(); // why you do that?

        $this->assertFalse($post->isLikedBy(auth()->user()); // check post is not liked by the current user user

        $post->like();

        $this->assertTrue($post->isLikedBy(auth()->user()); // check post is liked by the current user
    }
Activity icon

Replied to Sum For Loop Values

Hi @felicia00 if $sum is collection, you can use sum method

$total = $sum->sum('amount');

if it's array, you can create collection and then use sum method

$total = collect($sum)->sum('amount');
Activity icon

Replied to Get All Possible Elements From BelongsToMany Relationship

Hi @manojow

$products = Product::whereHas('categories', function ($query) {
    $query->whereIn('id', [1, 2]);
});
Sep
24
3 days ago
Activity icon

Awarded Best Reply on Laravel Upgrade From V7 To V8 Problem

Hi @monstajamss look here

https://github.com/laravel-frontend-presets/now-ui-dashboard/releases/tag/v1.0.4

looks like really you need version 1.0.4 of laravel-frontend-presets/now-ui-dashboard

Activity icon

Replied to Laravel Belongstomany With Pivot - Save One Row At A Time

Hi @mephisto really not understand you question. Here

foreach(Student::all() as $student) {

you ger all the students, and here

$subjects = Subject::all()->pluck('id');

you get all the subjects, and then

$student->subjects()->attach($subjects);

attach all the subjects step by step to every student. So, in total, of course, all students have all subjects.

you need to specify The exact student and exact subject you want to attach, like

Students::first()->subjects(Subject::first()->id);

this example will attach first subject to first user. Or if you have specified student id and subject id

Student::find($sudentId)->subjects()->attach(Subject::find($subjectId)->id);
Activity icon

Replied to Why My Date Input Doesn't Show The Initial Value Of The Model?

Hi @meaulnes possible, you initial value of beg_date is in different format compare to mm/dd/yyyy?

Activity icon

Replied to Laravel Upgrade From V7 To V8 Problem

Hi @monstajamss look here

https://github.com/laravel-frontend-presets/now-ui-dashboard/releases/tag/v1.0.4

looks like really you need version 1.0.4 of laravel-frontend-presets/now-ui-dashboard

Activity icon

Awarded Best Reply on Where Clause In Polymorphic Relationship

Hi @pickab00

$post->views()->where('uuid', 'someuuid')->exists();
Activity icon

Replied to Where Clause In Polymorphic Relationship

Hi @pickab00

$post->views()->where('uuid', 'someuuid')->exists();
Activity icon

Awarded Best Reply on Eloquent Modify DB Data Before Comparing Them With Where()

Hi @andyandy I think you can use LOWER and REGEX_REPLACE mysql functions, like so:

$record = Record::where(
    \DB::raw('LOWER(REGEXP_REPLACE(`text`, "[^a-z0-9]+", ""))') 
    preg_replace('/[^a-z0-9]+/u', '', strtolower(request('text')))
)->...

possible contains some mistakes, but should give you an idea how to do it

Activity icon

Replied to Eloquent Modify DB Data Before Comparing Them With Where()

Hi @andyandy I think you can use LOWER and REGEX_REPLACE mysql functions, like so:

$record = Record::where(
    \DB::raw('LOWER(REGEXP_REPLACE(`text`, "[^a-z0-9]+", ""))') 
    preg_replace('/[^a-z0-9]+/u', '', strtolower(request('text')))
)->...

possible contains some mistakes, but should give you an idea how to do it

Sep
22
5 days ago
Activity icon

Awarded Best Reply on Retrieve A Single Column With A Peculiar ID From A Database And Put It In At A Different Table

Hi @obink try something like

public function store(Request $request)
    {
        $invoice = invoice::create($request->all());

        $inputProducts = $request->input('products', []);
        $inputQuantities = $request->input('quantities', []);

        $products = DB::table('products')->whereIn('id', $inputProducts)->get()->keyBy('id');

        foreach ($inputProducts as $index => $productId) {
            if ($products->has($productId) && Arr::has($inputQuantities, $index)) {
                $invoice->products()->attach([
                    $productId => [
                        'quantity' => $inputQuantities[$index ],
                        'subtotal' => $inputQuantities[$index] * $products->get($productId)->price,
                    ]
                ]);
        
                Product::where('id', $productId)->decrement('qty', $inputQuantities[$index]);
            }
        }
    
        return redirect()->route('productsOut.index');
    }
Activity icon

Awarded Best Reply on Remove ?page=1 From Paginate()

Hi @andyandy I think the problem is that you search for string like ?page=1, but with append params to the links it can be ?foo=bar&page=1, so, no leading ? before page param

I think you need to look for ?page=1$ (at the end of string) OR &page=1 OR page=1&

Activity icon

Replied to Remove ?page=1 From Paginate()

Hi @andyandy I think the problem is that you search for string like ?page=1, but with append params to the links it can be ?foo=bar&page=1, so, no leading ? before page param

I think you need to look for ?page=1$ (at the end of string) OR &page=1 OR page=1&

Activity icon

Awarded Best Reply on Conditional Validate A Filled If A Certain Condition Is Met

Hi @loyd

'g-recaptcha-response' => config('services.recaptcha.key') ? 'required|recaptcha' : 'nullable',
Activity icon

Replied to Date Rules

@roffdaniel just checked - it works correctly for me. Can you dump validation data?

public function rules()
{
    dd($this->validationData());
}
Activity icon

Replied to Conditional Validate A Filled If A Certain Condition Is Met

Hi @loyd

'g-recaptcha-response' => config('services.recaptcha.key') ? 'required|recaptcha' : 'nullable',
Activity icon

Replied to Retrieve A Single Column With A Peculiar ID From A Database And Put It In At A Different Table

@obink and about your problem: value method returns specific value for the first item. You can grab the price for current product, but you'll need to use current product id

$pricePoint = DB::table('products')->where('id', $products[$product])->value('price');

or you pluck the result to have collection of product id => price pairs

$productPrices = DB::table('products')->whereIn('id', $products)->pluck('price', 'id');
Activity icon

Replied to Retrieve A Single Column With A Peculiar ID From A Database And Put It In At A Different Table

Hi @obink try something like

public function store(Request $request)
    {
        $invoice = invoice::create($request->all());

        $inputProducts = $request->input('products', []);
        $inputQuantities = $request->input('quantities', []);

        $products = DB::table('products')->whereIn('id', $inputProducts)->get()->keyBy('id');

        foreach ($inputProducts as $index => $productId) {
            if ($products->has($productId) && Arr::has($inputQuantities, $index)) {
                $invoice->products()->attach([
                    $productId => [
                        'quantity' => $inputQuantities[$index ],
                        'subtotal' => $inputQuantities[$index] * $products->get($productId)->price,
                    ]
                ]);
        
                Product::where('id', $productId)->decrement('qty', $inputQuantities[$index]);
            }
        }
    
        return redirect()->route('productsOut.index');
    }
Activity icon

Replied to Date Rules

@roffdaniel can you show your request data and exact error message you have?

Activity icon

Replied to Date Rules

Activity icon

Replied to Date Rules

Hi @roffdaniel you need to pass date in the same format (d.m.Y) to after_or_equal and before_od_equal rules, not the timestamp

Activity icon

Replied to Given An Array Of Usernames, How Do I Retrieve All The User Details From A Model?

@simonangatia method get() returns collection, even if just 1 record match the criteria. so, if you will do

dd(Model::whereIn('username',$users)->get());

and you will see just 1 item in collection - so, just 1 matching username found.

Activity icon

Replied to Count Items With 'sold' Status

@kikogyh they, of course, are not equal. $sold will be the total number of sold items, while $data contains collection of buildings with attached count of sold items for every specific building.

I can't understand what do you want to do, Can you explain more?

Activity icon

Replied to Count Items With 'sold' Status

Hi @kikogyh to calculate total items with status sold

$sold = DB::table('items')->where('status', 'sold')->count();

related to building

$data = DB::table('buildings')->addSelect ('sold_items' => function ($query) {
    DB::table('items')
        ->selectRaw('count(*)')
        ->where('buildings.id', 'items.building_id')
        ->where('status', 'sold')
})
    ->get();
Sep
21
6 days ago
Activity icon

Awarded Best Reply on Subquery In Eloquent

Hi @andyandy you don't give us table name, so, imagine it's called records. I think it should be something like

$result = Record::addSelect([
    'count' => Records::select(DB::raw('count(*)')
        ->from('records', 'records2')
        ->where('records2.sub_id', 'records.id')
])->get();
Activity icon

Replied to How To Update Data Of Specific User With One To Many Relationship

@lilo this

    $project = Projects::first();
    dd($project->dev_expense);
    $project->developers()->update(['debt' => $project->dev_expense]);

what returns null? the last statement? or dd returns null? if dd - it can't find anything.

About your second question: you can gett all developers of the project by calling

dd($project->developers);
Activity icon

Replied to How To Update Data Of Specific User With One To Many Relationship

@lilo really confused with what yuo try to do. So, set debt column in developers table equal to dev_expense value from projects table? If so, try something like

in you Project model

public function developers()
{
    return $this->belongsToMany(Developer::class);
}

then in you controller (or where you process the data)

// select first project - as example
$project = Projects::first();

$project->developers()->update(['debt' => $project->dev_expense]);
Activity icon

Replied to How To Update Data Of Specific User With One To Many Relationship

@lilo to clear details: you have dev_name column in products table and it can be many developers with the same dev_name in developers table?

Activity icon

Replied to Subquery In Eloquent

Hi @andyandy you don't give us table name, so, imagine it's called records. I think it should be something like

$result = Record::addSelect([
    'count' => Records::select(DB::raw('count(*)')
        ->from('records', 'records2')
        ->where('records2.sub_id', 'records.id')
])->get();
Sep
20
1 week ago
Activity icon

Replied to Get 500 Internal Error In Submit

Hi @anonymouse703 500 means you have an error in your controller side. Please, provide your controller method code

Activity icon

Awarded Best Reply on Update Field Unique

Hi @datanorte I think your problem is in id you try to exclude from validation. Try like so:

'name_category' => "required|unique:categories,name_category," . $this->route('category'),

instead of category put your attribute name from route, so, if your route like

Route::put('/category/{category}', [CategoryController::class, 'update']);

param name will be category

Sep
18
1 week ago
Activity icon

Awarded Best Reply on (SQLSTATE[HY000]: General Error: 1364) , After Adding Another Pivot Column

Hi @obink you use attach method wrong. In case you have additional fields in pivot table, it should looks like:

for ($product=0; $product < count($products); $product++) {
    if ($products[$product] != '') {
        $order->products()->attach([
            $products[$product] => [
                'quantity' => $quantities[$product],
                'orderPrice' => $pricing[$product],
            ]
        ]);

        Product::where('id', $products[$product])->increment('qty',$quantities[$product]);
    }
}

also, possible it should decrement instead of increment? It make more sence to reduce product quantity after order creation

Activity icon

Awarded Best Reply on SyncWithoutDetaching Update Timestamp On Polymorphic Many-To-Many Table

Hi @coola you can try something like:

$post->contributors()->syncWithoutDetaching([
    $request->user()->id => ['updated_at' => now()]
]);
Activity icon

Awarded Best Reply on Router Prefix

Hi @extjac

Route::group(['prefix' => '{organization}'], function () {
	Route::get('/invoices, '[email protected]');
});
class InoviceController extends Controller
{
    public function index($organization)
    {
        dd($organization);
    }
}

this will returns organization id. Or, if you use model binding

class InoviceController extends Controller
{
    public function index(Organization $organization)
    {
        dd($organization);
    }
}

this should returns Organization model

Activity icon

Replied to Change Time_zone Not Working.

@letmeknow you use date_default_timezone_get() function, which returns current timezone and accepts no arguments. If you want to set specific, timezone, you need to use date_default_timezone_set, which accepts argument

date_default_timezone_set('Asia/Jakarta');
Activity icon

Replied to (SQLSTATE[HY000]: General Error: 1364) , After Adding Another Pivot Column

Hi @obink you use attach method wrong. In case you have additional fields in pivot table, it should looks like:

for ($product=0; $product < count($products); $product++) {
    if ($products[$product] != '') {
        $order->products()->attach([
            $products[$product] => [
                'quantity' => $quantities[$product],
                'orderPrice' => $pricing[$product],
            ]
        ]);

        Product::where('id', $products[$product])->increment('qty',$quantities[$product]);
    }
}

also, possible it should decrement instead of increment? It make more sence to reduce product quantity after order creation

Activity icon

Awarded Best Reply on Trying To Get Property 'name' Of Non-object

@loyd ok, this way dump

dd($p->subcategory);

possible, you have wrong defined relations, possible it should be named subCategory (because of _ in sub_categories table name), or you need to define foreign keys explicitly

Activity icon

Replied to Trying To Get Property 'name' Of Non-object

@loyd ok, this way dump

dd($p->subcategory);

possible, you have wrong defined relations, possible it should be named subCategory (because of _ in sub_categories table name), or you need to define foreign keys explicitly

Activity icon

Replied to Trying To Get Property 'name' Of Non-object

@loyd check that your subcategory exists. In controller

dd(SubCategory::find(2));

possible it's soft deleted?

Activity icon

Replied to Trying To Get Property 'name' Of Non-object

Hi @loyd do

@dd($p->subcategory)

and check waht you have. Possible, subcategory can be null? this way

{{ optional($p->subcategory)->name }}
Activity icon

Replied to Request Validate

@kikogyh

        $request->validate([
            'news' => ['required', 'string', 'max:2500', 'min:30'],
            'terms' => ['required'],
        ]);
Activity icon

Replied to Vue V-for Loop Doesnt Always Work

Hi @pveltrop at least show waht response you have from the server

fetch(pageUrl).then(response => response.json()).then(response => {
    console.log(response);
})
Activity icon

Replied to SyncWithoutDetaching Update Timestamp On Polymorphic Many-To-Many Table

Hi @coola you can try something like:

$post->contributors()->syncWithoutDetaching([
    $request->user()->id => ['updated_at' => now()]
]);
Activity icon

Replied to How To Catch A User Who Sent A Message In Chat

Hi @mvnobrega you cn use eager loading (assuming you have defined belongsTo deUser relations on your Message model)

public function msgs(Request $request) {

      $msg = Message::with('deUser')->where('para_user_id', $request->user()->id)->get();

      return view('msgs',compact('msg'));
        
    }

this way 1 additional call will be executed to the database and user who sent the message will be attached to every message, so, you'll be able to access it.

Activity icon

Replied to Update Field Unique

Hi @datanorte I think your problem is in id you try to exclude from validation. Try like so:

'name_category' => "required|unique:categories,name_category," . $this->route('category'),

instead of category put your attribute name from route, so, if your route like

Route::put('/category/{category}', [CategoryController::class, 'update']);

param name will be category