SilenceBringer

SilenceBringer

Member Since 4 Years Ago

Experience Points
91,460
Total
Experience

3,540 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
533
Lessons
Completed
Best Reply Awards
63
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 19
91,460 XP
Sep
18
14 hours ago
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

Sep
17
1 day ago
Activity icon

Replied to 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 How To Get Yearly And Daily Sales Of Product In Laravel?

@saurav77 no. If you want to sum by multiple years you'll need to use in or between

DB::raw('sum(if(year(sales.purchase_date) BETWEEN "' . $startFrom . '" AND "' . $endTo . '", quantity, 0)) AS yearly'))

// or


DB::raw('sum(if(year(sales.purchase_date) IN ("' . $startFrom . '", "' . $endTo . '"), quantity, 0)) AS yearly'))
Activity icon

Awarded Best Reply on How To Get Yearly And Daily Sales Of Product In Laravel?

@saurav77 of course

$date = now(); // or another Carbon instance

DB::table('products')
    ->select(
        'products.*',
        DB::raw('sum(if(sales.purchase_date = "' . $date->format('Y-m-d') . '", quantity, 0)) as today'),
        DB::raw('sum(if(year(sales.purchase_date) = "' . $date->format('Y') . '", quantity, 0)) AS yearly'))
    )
    ->leftJoin('sales', 'sales.product_id', '=', 'products.id')
    ->groupBy('products.id')
    ->get();
Activity icon

Replied to How To Get Yearly And Daily Sales Of Product In Laravel?

@saurav77 of course

$date = now(); // or another Carbon instance

DB::table('products')
    ->select(
        'products.*',
        DB::raw('sum(if(sales.purchase_date = "' . $date->format('Y-m-d') . '", quantity, 0)) as today'),
        DB::raw('sum(if(year(sales.purchase_date) = "' . $date->format('Y') . '", quantity, 0)) AS yearly'))
    )
    ->leftJoin('sales', 'sales.product_id', '=', 'products.id')
    ->groupBy('products.id')
    ->get();
Activity icon

Replied to How To Get Yearly And Daily Sales Of Product In Laravel?

@saurav77 do you need to output it in blade? try like so

<table>
<thead>
    <tr>
        <th></th>
        @foreach ($results as $result)
            <th>{{ $result->product }}</th>
        @endforeach
    </tr>
</thead>
<tbody>
    @foreach (['yearly', 'today'] as $period)
        <tr>
            <td>{{ $period }}</td>
            @foreach ($results as $result)
                <td>{{ $result->$period }}</td>
            @endforeach
        </tr>
    @endforeach
</tbody>
</table>
Activity icon

Awarded Best Reply on Show Just Not Active Language Mcamara

Hi @ethar

@foreach(LaravelLocalization::getSupportedLocales()->filter(fn ($props, $localeCode) => $localeCode != LaravelLocalization::getCurrentLocale()) as $localeCode => $properties)
    <li>
        <a rel="alternate" hreflang="{{ $localeCode }}"
            href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
            {{ $properties['native'] }}
        </a>
    </li>
@endforeach

or

@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
    @if ($localeCode != LaravelLocalization::getCurrentLocale())
        <li>
            <a rel="alternate" hreflang="{{ $localeCode }}"
                href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endif
@endforeach
Activity icon

Replied to How To Get Yearly And Daily Sales Of Product In Laravel?

Hi @saurav77 try like so:

DB::table('products')
    ->select(
        'products.*',
        DB::raw('sum(if(date(curdate()) = sales.purchase_date, quantity, 0)) as today'),
        DB::raw('sum(if(year(curdate()) = year(sales.purchase_date), quantity, 0)) AS yearly'))
    )
    ->leftJoin('sales', 'sales.product_id', '=', 'products.id)
    ->groupBy('products.id')
    ->get();
Activity icon

Awarded Best Reply on Filtering Eloquent With Multiple BelongsToMany Relationships

Hi @vitorenes I think whereHas condition is what you looking for.

So, you can grab all the contents which have specific subcategory like

App\Content::whereHas('subcategories', function ($query) {
    $query->where('id', 3);
})->get();

and even more filter by category and subcategory

App\Content::whereHas('subcategories', function ($query) {
    $query->where('id', 3);
})
    ->whereHas('categories', function ($query) {
        $query->where('id', 1);
    })
    ->get();
Activity icon

Replied to Trying To Setup Default Data Entry On Migration

@webfuelcode you can try like so:

// in controller
public function settings()
    {
        $settings = AdminSet::settings();

        return view('admin.settings', compact('settings'));
    }

class AdminSet extends Model
{
    public function settings()
    {
        $data = static::all();

        return $data->count() ? $data : collect([
            new static([
                'title' => 'SiteTITLE',
                // other fields
            ])
        ]);
    }
}

or (if really you'll have just 1 row), replace all with first

    public function settings()
    {
        return static::first() ?: new static([
            'title' => 'SiteTITLE',
            // other fields
        ]);
    }
Activity icon

Replied to How To Update And Create Multiple Product In Sell Table With UpdateOrCreate Method

@shuvobhai becuase in your code you try to put into products table. For working with pivot table you need to use sync, attach or detach methods

Can you show your migrations for sell table, pivot table and products table?

Activity icon

Replied to How To Update And Create Multiple Product In Sell Table With UpdateOrCreate Method

Hi @shuvobhai possible your key has name supplier_product_id, not product_id

 $sell->Products()->updateOrCreate(['supplier_product_id' => $request->product_id[$i]],
                [
                    'cartoon' => $request->cartoon[$i],
                    'qty' => $request->qty[$i],
                    'rate' => $request->rate[$i],
                    'total' => $request->total[$i],
                ]
            );

Activity icon

Replied to Trying To Setup Default Data Entry On Migration

Hi @webfuelcode can you explain little more? Do you have table like settings with key => value pairs, or it's model like description with title, keywords, etc?

Activity icon

Replied to Intercept Misstokenmissmatch In Laravel 8

Hi @yoman this way I think you can re-write the \App\Middleware\VerifyCsrfToken to redirect to previous page instead of throwing an exception

Activity icon

Replied to Migrate Without Lose Data

Hi @kikogyh you need to create separated migration for it

https://laravel.com/docs/8.x/migrations#creating-columns

Activity icon

Replied to Updating Normal User To Admin

Hi @mimiloca try something like

public function add(User $users, Request $request)
    {
        $users->update(['is_admin'=> $requist->is_admin == 0 ? 0 : 1]);
       
        return redirect('admin.users')->with('success', 'Admin Added!');
    }

Here i suggest that if your input == 0 user will not be an admin, and if any other value - it should

Activity icon

Replied to Getting The Category And Posts Inside It

Hi @webfuelcode If your target is to minimize the count of db calls, I can't imagine another way than using unions here, like so:

$postsQuery = null;

$categories = Category::take(5)->get();

$categories->each(function ($category) use (&$postsQuery) {
    $query = Post::where('category_id', $category->id)->take(5);

    $postsQuery = $postsQuery ? $postsQuery->union($query) : $query;
))

$posts = $postsQuery->get()->groupBy('category_id');

and then in your view file you can use it like

@foreach ($categories as $category)
    <div>{{ $category->name }}</div>

    @if ($posts->has($category->id))
        <ul>
            @foreach ($posts->get($category->id, []) as $post)
                <li><a href="{{ $post->url }}">{{ $post->title }}</a></li>
            @endforeach
        </ul>
    @endif
@endforeach

this way you'll have just 2 db calls

Activity icon

Replied to Data And Props Naming Conflicts

I do not think there is any convention about it, so, each developer selects his own solution. As for me, if I have a property like user, and I want to have editable user, I just prepend init to the property name. so

props: {
  initUser: Object
}
data () {
    return {
        user: {},
    }
}
Sep
16
2 days ago
Activity icon

Awarded Best Reply on Applying Additional Form Validation Rules To Selectively Required Fields

Hi @grozavule try this:

$validStatuses = array_keys(self::CUSTOMER_ORDER_STATUS);
            $validInput = $request->validate([
                'customer_id' => ['nullable', 'required_without_all:order_number,order_status', 'alpha_num'],
                'order_number' => ['nullable', 'required_without_all:customer_id,order_status', 'string'],
                'order_status' => ['nullable', 'required_without_all:order_number,customer_id', Rule::in($validStatuses)]
            ]);
Activity icon

Awarded Best Reply on Route From Variable

Hi @afoysal I think your problem is in space at the end of $last_word

<a href="{{route('start' . trim($last_word))}}">

because here

Route [startRun ] not defined.

I see space at the end of route name

Activity icon

Replied to Applying Additional Form Validation Rules To Selectively Required Fields

Hi @grozavule try this:

$validStatuses = array_keys(self::CUSTOMER_ORDER_STATUS);
            $validInput = $request->validate([
                'customer_id' => ['nullable', 'required_without_all:order_number,order_status', 'alpha_num'],
                'order_number' => ['nullable', 'required_without_all:customer_id,order_status', 'string'],
                'order_status' => ['nullable', 'required_without_all:order_number,customer_id', Rule::in($validStatuses)]
            ]);
Activity icon

Replied to Route From Variable

Hi @afoysal I think your problem is in space at the end of $last_word

<a href="{{route('start' . trim($last_word))}}">

because here

Route [startRun ] not defined.

I see space at the end of route name

Activity icon

Replied to Show Just Not Active Language Mcamara

Hi @ethar

@foreach(LaravelLocalization::getSupportedLocales()->filter(fn ($props, $localeCode) => $localeCode != LaravelLocalization::getCurrentLocale()) as $localeCode => $properties)
    <li>
        <a rel="alternate" hreflang="{{ $localeCode }}"
            href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
            {{ $properties['native'] }}
        </a>
    </li>
@endforeach

or

@foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
    @if ($localeCode != LaravelLocalization::getCurrentLocale())
        <li>
            <a rel="alternate" hreflang="{{ $localeCode }}"
                href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endif
@endforeach
Activity icon

Replied to Filtering Eloquent With Multiple BelongsToMany Relationships

Hi @vitorenes I think whereHas condition is what you looking for.

So, you can grab all the contents which have specific subcategory like

App\Content::whereHas('subcategories', function ($query) {
    $query->where('id', 3);
})->get();

and even more filter by category and subcategory

App\Content::whereHas('subcategories', function ($query) {
    $query->where('id', 3);
})
    ->whereHas('categories', function ($query) {
        $query->where('id', 1);
    })
    ->get();
Activity icon

Awarded Best Reply on Get Users From A Collection Of Follows

User::whereHas('follows', function ($query) use ($locationId) {
    $query->where('location_id', $locationId);
})->get();
Activity icon

Awarded Best Reply on Validation Of Array With Required If Adjacent Field Is Filled.

Hi @coola your validation rules should looks like

[
    'field.*.content' => 'nullable|required_with:field.*.name,field.*.alias'
]
Activity icon

Replied to Get Users From A Collection Of Follows

User::whereHas('follows', function ($query) use ($locationId) {
    $query->where('location_id', $locationId);
})->get();
Activity icon

Awarded Best Reply on Positive Query Result But No Database Update

@loomix oh... possible, DB::commit() is missing

Activity icon

Replied to Positive Query Result But No Database Update

@loomix oh... possible, DB::commit() is missing

Activity icon

Awarded Best Reply on Trying To Get Property Id Of A Non-object

Hi @pickab00 you have json encoded object. So, you need to decode it

you can set cast in your model like so

class Message extends Model
{
    protected $casts = [
        'body' => 'array',
    ];
}

then you'll be able to work with body as with array

$message->body['id'];
Activity icon

Replied to Positive Query Result But No Database Update

try{
    foreach($resources as $resource){
        dump('before: ' . DB::table('tool_user')
            ->where('tool_id', strval($resource['id'])) 
            ->where('user_id', Auth::id())
            ->first()
            ->tool_order);
        dump('New value: ' . $resource['order']);
        $query = DB::table('tool_user')
            ->where('tool_id', strval($resource['id'])) 
            ->where('user_id', Auth::id())
            ->update(['tool_order' => $resource['order']]);
        dump('after: ' . DB::table('tool_user')
            ->where('tool_id', strval($resource['id'])) 
            ->where('user_id', Auth::id())
            ->first()
            ->tool_order);
catch(\Exception $e){
    // ...
}
Activity icon

Replied to Positive Query Result But No Database Update

Hi @loomix try to dump number of rows which should be affected by every query, possible something wrong with your condition, so really 0 rows matches the query

try{
    foreach($resources as $resource){
        dump($resource['id'].' '.Auth::id().' '.$resource['order']);
        dump(DB::table('tool_user')
            ->where('tool_id', strval($resource['id'])) 
            ->where('user_id', Auth::id())
            ->count());
        $query = DB::table('tool_user')
            ->where('tool_id', strval($resource['id'])) 
            ->where('user_id', Auth::id())
            ->update(['tool_order' => $resource['order']]);
catch(\Exception $e){
    // ...
}
Activity icon

Replied to Inner Join On Json Contains

@codus you're welcome

Activity icon

Awarded Best Reply on Inner Join On Json Contains

@codus try raw

BooksSet::join('books', function ($join) {
    $join->on(function ($on) {
        $on->whereRaw('JSON_CONTAINS(books_sets.books, books.id)');
    });
});
Activity icon

Replied to Inner Join On Json Contains

@codus try raw

BooksSet::join('books', function ($join) {
    $join->on(function ($on) {
        $on->whereRaw('JSON_CONTAINS(books_sets.books, books.id)');
    });
});
Activity icon

Replied to Differences Between Mail::raw And Mail::to

@gianmarx no

to used to specify recipient name for all the methods raw|send|html|plain

raw used to specify the type of message - raw content

Activity icon

Replied to Trying To Get Property Id Of A Non-object

@pickab00 show the output of

dd($message->body);
Activity icon

Replied to Trying To Get Property Id Of A Non-object

Hi @pickab00 you have json encoded object. So, you need to decode it

you can set cast in your model like so

class Message extends Model
{
    protected $casts = [
        'body' => 'array',
    ];
}

then you'll be able to work with body as with array

$message->body['id'];