princeoo7

princeoo7

Member Since 2 Years Ago

Experience Points
7,090
Total
Experience

2,910 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
16
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 2
7,090 XP
Aug
03
1 day ago
Activity icon

Replied to How To Search Result In Data Appended In Model ?

If I add $with to model then how will be the search function in controller ?

Aug
01
3 days ago
Activity icon

Started a new Conversation How To Search Result In Data Appended In Model ?

I have 2 tabled, First is category and second is categoryTrasnlation. As the name suggest. 1st table save based data for a category and the 2nd one save language translation data.

Now this data is always required in every query been made so it made sense for me to directory append this data in Model itself with,

    protected $appends = ['data'];
   
    public function getDataAttribute() {
        return $this->translations()->select(['lang_code', 'title'])->get();
    }

    public function translations() {
        return $this->hasMany(CategoryTranslation::class, 'category_id');
    }

My question is how to search for data from categoryTranslation table as it have the title field where different language title are stored.

currently what I am doing in the controller is as below:

$records = Category::paginate(config('app.rec_limit'));

Normally how I would have done this is as below:

$r = request()->input('s');
                $records = Category::whereHas('translations', function($q) use ($r){
                    return $q->where('title',  'LIKE', '%' . $r . '%');
                })->paginate(env('app.rec_limit'));

Please let me know where am I going wrong...

Jul
27
1 week ago
Activity icon

Commented on Style The Index Page With Tailwind CSS

Great Stuff Andre ! really loved how tailwind was explained in short with new functionality which I was not aware of :)

Activity icon

Replied to How To Refactor Below Query ?

status_id is not a foreign key but I am using ENUMS so need it.

Activity icon

Started a new Conversation How To Refactor Below Query ?

I am having so difficult time in developing an optimized query for the below code:

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations'])->latest('id')->limit(config('app.latest_limit'))->where('status_id', Status::Active)->get();

in my category and videos table i have below code:

public function scopeActive($q)
    {
        return $q->where('status_id', Status::Active);
    }

    public function getActive()
    {
        return $this->active()->get();
    }

but if i do this,

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations'])->latest('id')->limit(config('app.latest_limit'))->getActive();

I get the below error,

Call to undefined method Illuminate\Database\Eloquent\Builder::getActive()

what worked for me as of now is:

$categories = Category::with(['videos' => function($q) {
                return $q->active();
            } , 'videos.translations' => function($q) {
                return $q->active();
            } ])->latest('id')->limit(config('app.latest_limit'))->active()->get();

also want to know how to optimize this more further if possible ...

Jun
17
1 month ago
Activity icon

Replied to Changing Model Directory

Correct answer I would say :)

May
25
2 months ago
Activity icon

Replied to Shift Active Filter To Model For Record And Relationship

I was using it on only product model and that was the reason that I was not getting the right output. Now I have implemented that on all the models in relation and below is the code which is working for me.

public function scopeActive($q)
    {
        return $q->where('status_id', Status::Active)->whereHas('creator', function ($q) {
            $q->active();
        })->whereHas('category', function ($q) {
            $q->active();
        });
    }

Now this simple is repetative I suppose like for scopeActive I have to repeat code for all the models. should I make a helper function and use that instead as a global helper function ?

Activity icon

Replied to Cannot Construct An Instance Of Status Using The Value (NULL)

@bugsysha return $q->where('status_id', Status::Active); is simple for me as I can also access the label value in the api reducing the task ok maintaining the label on all frontend platforms. plus make changes at one place and update at all place sounds more good to me atleast.

Activity icon

Started a new Conversation Cannot Construct An Instance Of Status Using The Value (NULL)

I am using the Laravel Enum package and its working fine for most places. but for below code from product model I am facing below error. I have checked the db and all records have one category.


public function getCategoryAttribute () {
        return $this->category()->select('title')->get();
    }

    public function category() {
        return $this->belongsTo(Category::class, 'category_id');
    }    


"message": "Cannot construct an instance of Status using the value (NULL) ``. Possible values are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].",
    "exception": "BenSampo\Enum\Exceptions\InvalidEnumMemberException",
Activity icon

Replied to Shift Active Filter To Model For Record And Relationship

yes. you can see that in above code.

Activity icon

Started a new Conversation Shift Active Filter To Model For Record And Relationship

I was reading laravel best practices at https://github.com/alexeymezenin/laravel-best-practices and found the below example which is considered as good example.


public function scopeActive($q)
{
    return $q->where('verified', 1)->whereNotNull('deleted_at');
}

public function getActive()
{
    return $this->active()->get();
}

public function getArticles()
{
    return $this->whereHas('user', function ($q) {
            $q->active();
        })->get();
}


Now I tried to implement it in my product model and below is the code.

  // status based scopes below
    public function scopeActive($q)
    {
        return $q->where('status_id', Status::Active);
    }

    public function getActive()
    {
        return $this->active()->get();
    }


The above code does give me the active products record but every product have a user. How can I modify my code to check that the product as well and the user is active from model and then only return the result.

products table have creator_id as the link between users table and products table.

I have tried below code and its not working for me:



public function getActive()
    {
        return $this->active()->whereHas('user', function ($q) {
            $q->active();
        })->get();
    }

Activity icon

Replied to BelongsTo Relation Gets Null Output.

that api is to complex and product is just a piece of it. so Let me check with Api resource.

Activity icon

Replied to BelongsTo Relation Gets Null Output.

@nakov normally for web, I follow the same pattern but for api, I cannot do that. all data needs to be at the disposal at the frontend. any way we can only append this attributes for api and not for web request ?

Activity icon

Replied to BelongsTo Relation Gets Null Output.

I have to send data in api, thats why ...

Activity icon

Started a new Conversation BelongsTo Relation Gets Null Output.

I have brand_id in products table. Now that is related with id so I have used belongsTo relationship.

    public function getBrandAttribute () {
        return $this->belongsTo(Brand::class, 'brand_id');
    }

now the output should have been the data from brand table. but its null for me.

But if I do the below, I get the output.


   public function getBrandAttribute() {
        return $this->brand()->get();
    }

    public function brand() {
        return $this->belongsTo(Brand::class);
    }

Why can't I get it directly ?

Apr
20
3 months ago
Activity icon

Started a new Conversation Model Function Giving Empty Array As Output

As I am trying the ecom app, I was working it the attritbute table from db in Product Model.

protected $appends = [ 'product_attributes'];

public function getProductAttributesAttribute() {
        return $this->with(['attributes.value']);
    }
// OR

public function getProductAttributesAttribute() {
        return $this->attributes();
    }




    public function attributes() {
        return $this->hasMany(ProductAttribute::class, 'product_id');
    }

If I do Product::with(['attributes'])->active()->paginate(config('app.rec_limit')); I get the result.

but my product_attributes is empty for the same function which is called in WITH() in query.

What am I doing wrong here?

Apr
19
3 months ago
Activity icon

Replied to Need Help In Figuring Out How To Work With Laravel Socialite Api And Flutter App

yes I am stuck with the issue of invalid_credential :(

Activity icon

Replied to ECommerce From Scratch?

How much did you charged for such project, if you can share :)

Activity icon

Started a new Conversation Many To Many Relation In Ecom App

Well I was looking at this https://www.laravelsd.com/share/K5oG9a Its the db schema for the ecom app.

Now In normal ecom app we have dynamic properties / attributes. what I was doing is creating separate table for the attribute and using attach() due to many-to-many relation.

but I found the limitation and the above db schema solves most of the issue. I Implemented it but with some changes as I was not able to understand the Attribute_value Implementation they have shown.

Schema::create('attributes', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->tinyInteger('status_id')->default(Status::Active);
            $table->timestamps();
        });

Schema::create('attribute_product', function (Blueprint $table) {
            $table->bigInteger('attribute_id');
            $table->bigInteger('product_id');
            $table->string('value');
            $table->timestamps();
        });

in my product model, I have :

public function attributes() {
        return $this->belongsToMany(Attribute::class);
    }

    public function getProductAttributesAttribute() {
        return $this->attributes();
    }

Output is :

"product_attributes": {
                            "withTimestamps": false
                        },

I am lost here. Please let me know what is wrong and how to solve this issue.

Activity icon

Replied to Get Elquoent Data Directly From Auth::user() Instead Of Mentioned Way In Question

Auth::user()->load('profile') this seem good. this was what I was looking at :D but is this only One query performed on every request?

Activity icon

Replied to Get Elquoent Data Directly From Auth::user() Instead Of Mentioned Way In Question

already have that function / relation in user model and that is what I am trying to call as Auth::user()->profile().

Activity icon

Awarded Best Reply on Undefined Property Error In Model

Got the answer via stackoverflow: https://stackoverflow.com/questions/35184646/change-field-attribute-value-in-model-laravel

    public function getAccountTypeAttribute() {
        return ($this->attributes['account_type']) ? 'private' : 'public';
    }
Activity icon

Replied to Undefined Property Error In Model

Got the answer via stackoverflow: https://stackoverflow.com/questions/35184646/change-field-attribute-value-in-model-laravel

    public function getAccountTypeAttribute() {
        return ($this->attributes['account_type']) ? 'private' : 'public';
    }
Activity icon

Started a new Conversation Undefined Property Error In Model

Below is the error I am Facing.

"message": "Undefined property: App\Models\Profile::$account_type",

What I am trying to do is as below.

	public function getAccountTypeAttribute() {
        	return ($this->account_type) ? 'private' : 'public';
    	}

account_type value exist in db as boolean so based on true or false I need to provide the public or private text for the same attribute in API.

normally I do get the output as below in json format when the getAccountTypeAttribute is removed :

"account_type": 0,

What am I Missing ?

Activity icon

Started a new Conversation Get Elquoent Data Directly From Auth::user() Instead Of Mentioned Way In Question

Well the question is pretty simple to understand.

I have a profile table and so I want to provide the profile data with user data which we can access via a api.

Currently when we use Auth::user() we can only get the user base data..

To get the profile data, I normally get the user ID form Auth and query the DB for the user with with() to include the profile data.

Is there a Shorter version to do the same ?

Like Auth::user()->profile() some thing ???

Edit: Adding User model Code for more clarity to the question.

public function profile(){
        return $this->hasOne(Profile::class);        
    }

``
Apr
14
3 months ago
Activity icon

Replied to Will My Code Work For Storing Images On Aws S3, I Don't Have Access To S3 So Asking In General.

Its not a project for a client. I am trying to learn proper ways to reuse code and while doing that came across the traits example. so thought what if I can also have a AWS version for the same. I personally don't have access to AWS S3 as no projects of mine are currently under work on it.

Activity icon

Replied to API Authentication Via Social Networks For Your Laravel Application

this is the solution for web based implementation for socialite package which is working fine for me.

My main issue is with the api based package coderello / laravel-passport-social-grant.

link: https://github.com/coderello/laravel-passport-social-grant

below is the array which needs to be provided to the oauth/token link:

{
    'grant' => 'social',
    'client_id' => 'laravel Client id',
    'client_scret' => 'laravel Client secret',
    'provider' => 'google',
    'access_token' => 'google token',
}

and here is where I am facing the issue.

Apr
12
3 months ago
Activity icon

Started a new Conversation Will My Code Work For Storing Images On Aws S3, I Don't Have Access To S3 So Asking In General.

I was reading about how Trails can be used in Laravel to help us in reusability, so here is the below I came up but would it really work on AWS s3 I wonder :/

by the way I don't have access to aws s3 so asking for this assistance :)

public function verifyAndStoreImageAWS( Request $request, $fieldname = 'image', $directory = 'unknown' ) {
 
        if( $request->hasFile( $fieldname ) ) {
 
            if (!$request->file($fieldname)->isValid()) {
 
                flash('Invalid Image!')->error()->important();
 
                return redirect()->back()->withInput();
 
            }
            return Storage::disk('s3')->put($directory, file_get_contents($request->file($fieldname)));
 
        }
 
        return null;
 
    }


in the store function:

$formInput['image'] = $this->verifyAndStoreImage($request, 'image', 'post');

the article i was following was : https://www.develodesign.co.uk/news/laravel-traits-what-are-traits-and-how-to-create-a-laravel-trait/

Apr
08
3 months ago
Activity icon

Replied to API Authentication Via Social Networks For Your Laravel Application

@niyo @tisuchi Yes I have created a App on the Sever and if I use the web App method for verification, i.e. the socialite version, it works !

Apr
07
3 months ago
Activity icon

Replied to API Authentication Via Social Networks For Your Laravel Application

any update here ? I am just stucked here :(

Mar
30
4 months ago
Activity icon

Replied to API Authentication Via Social Networks For Your Laravel Application

I got that part but what is the access_token which needs to be provided for getting the token :/ that's the question on my mind :(

Activity icon

Started a new Conversation API Authentication Via Social Networks For Your Laravel Application

Well this title is copied from the medium blog and so if some one as crossed it, please don't complaint ;D

here is the link : https://medium.com/@hivokas/api-authentication-via-social-networks-for-your-laravel-application-d81cfc185e60

I have followed through the blog and the instruction but how should I use it in practical is something is have not able to figured out :(

in the Step 5: Ensure that all works perfectly, there are 3 things I cannot figure out which are as below:

  1. client id ( is it the google client id )
  2. client secret ( is it the google client secret )
  3. access token

error I am facing is :

{
“error”: “invalid_credentials”,
“error_description”: “The user credentials were incorrect.”,
“message”: “The user credentials were incorrect.”
}

has anyone used it ? can someone help me understand how this work ?

thank you for going through my thread / question / post :)

if the image is not available, please visit the article as that article have the same image at the end of article after point 5 as mentioned before.

1-IFr4-VGE-5-BWNr-U3k3gmf-Kw

Mar
22
4 months ago
Activity icon

Started a new Conversation How To Find Top Trending Or Selling Product From Product Table With Elquoent

I have a basic Products table. the order table is Orders table. Order table has BelongsToMany relation with Products table. So extract Top Selling products id from orders table and pass that to products table so that I can get the top Selling or Trending products from table.

I want to do something like this in product controller


public function topTrending(){
        $records = Product::latest('id')->topTrending()->paginate(config('app.rec_limit'));
        return response()->json([
            'collections' => [
                compact('records')
            ]
        ]);
    }

    public function topSelling(){
        $records = Product::latest('id')->topSelling()->paginate(config('app.rec_limit'));
        return response()->json([
            'collections' => [
                compact('records')
            ]
        ]);
    }

In Product Model is what I don't get what to do.

public function scopeTopTrending($q) {
	// no idea what to do        
}

public function scopeTopSelling($q) {
      // no idea what to do
}

Mar
19
4 months ago
Activity icon

Replied to Customize The Export To Excel In Laravel

What if I have to pass a complex condition ( multiple conditions ), should i declare all variables expected to be in construct or just las the request as query itself ?

Mar
15
4 months ago
Activity icon

Started a new Conversation Customize The Export To Excel In Laravel

I am trying to export the data to excel where data have eloquent and the below code work!

What Issue I have is, I am not able to figure out how to limit the data to current length, shown data on the page and how to filter data like if I have searched some database on a condition.

below code just export all to an excel sheet which as of now is ok, but in future, the length will give issue.


<?php

namespace App\Exports;

use App\User;
use Log;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromQuery, WithHeadings, ShouldAutoSize, WithEvents, WithMapping {

    public function query()
    {
        $user = User::query()->with(['vehicles', 'documents.docType']);
        return $user;
    }

    public function map($user): array
    {
        return [
            $user->id,
            $user->name,
            $user->email,
            $user->phone,
            $user->gender,
            implode(', ',$user->vehicles->pluck('rc_number')->toArray()),
            implode(', ',$user->documents->pluck('docType.name')->toArray()),
            date('dS M, Y', strtotime($user->created_at)),
            date('dS M, Y', strtotime($user->updated_at)),
        ];
    }

    public function headings(): array
    {
        return [
            '#',
            'Name',
            'Email',
            'Phone',
            'Gender',
            'Vehicles',
            'Documents',
            'Created On',
            'Updated On',
        ];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class    => function(AfterSheet $event) {
                $cellRange = 'A1:W1'; // All headers
                $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(12);
                $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setBold(true);
            },
        ];
    }
}


please don't tell me to export from FormView as that's not possible for me at this stage or later!

FormQuery is what I can use so to this how should I work with this?

Mar
11
4 months ago
Activity icon

Started a new Conversation Single User Record Fetch With Laravel Passport Token

I am using Laravel Passport to create / grant tokens to the user. Registration and login success. but the issue is the token which is received by the user after login ends up fetching the first user information. any account I tried, its the same result. The first Record from Users table is fetch. what can be the issue?

So I Did some Log:Debug and found that Auth::user() does indeed return the orniginal user for whom the token was assigned. But below query gets something else.


$records =  Auth::user()->with(['notifications'])->first(); // returns first user;

$records =  Auth::user()->with(['notifications')->get(); returns all users;

$records =  Auth::user()->with(['notifications']); // returns nothing.

Auth::user(); // returns current user info, correct one and required one.

So what am I doing wrong?

should I first do $id = Auth::user()->id and then use the whereId with User model ?

Mar
10
4 months ago
Activity icon

Replied to What Is The Logic Behind Following A User Like In Instagram In Laravel ?

Can you specify which lessons can answer my query or do I have to run the marathon to know ;)

With Job its a bit hard to get the time and so asking for in-depth.

Activity icon

Replied to What Is The Logic Behind Following A User Like In Instagram In Laravel ?

I have the knowledge of M-To-M, H-M, B-To-M, B-To. The issue is, can't find the right way to implement the functionality.

Let me give you an example.

I have users and profile table. in that, I might set up belongsToMany relation. fetch information as followers from the model. this gives me the list of users I am following.

So now, should I add a method to user model where when users data is fetched, it adds a column where is_following is boolean, or is there a better way to do the same?

Activity icon

Started a new Conversation What Is The Logic Behind Following A User Like In Instagram In Laravel ?

This question is something on my mind from along and at last, I want to try this thing out. The test case is as below:

  1. A user can follow other users.
  2. A user can block other users. The current user cannot be seen by the user who has blocked them.
  3. A user can unblock other users.
  4. Most Important, when the list of users is fetched, it can be anywhere, like the likes on a post where if we check the people who we have liked the post, it should show the name of the user as well as the following status telling us if we are following that particular user or not.

Most importantly this data should be manipulated in the model itself before we can provide this data to the frontend.

Any guidance is appriciated :)

Activity icon

Awarded Best Reply on WhereBetween Gives Null In Laravel Even When Data Exist !

there was an issue with the condition failing in the relation. so this as been solved. thank you for your valuable inputs :)

Activity icon

Replied to WhereBetween Gives Null In Laravel Even When Data Exist !

there was an issue with the condition failing in the relation. so this as been solved. thank you for your valuable inputs :)

Activity icon

Replied to Changing Model Directory

@michaelk do we create this command from terminal or manually create this file in the console folder !

Mar
07
4 months ago
Activity icon

Started a new Conversation WhereBetween Gives Null In Laravel Even When Data Exist !

I have the below code where I need to check if a document is expired or not.

Document::select(['id', 'title', 'type', 'valid_to', 'notification_status', 'user_id', 'status_id'])
            ->with(['owner'])
            ->whereNotificationStatus(Status::On)
            ->whereStatusId(Status::Active)
            ->whereBetween('valid_to', [$from, $to])
            ->get();

Now I have 2 records in DB for 2020-04-03 and 2020-04-06.

below is the log file I get from testing:

[2020-03-07 15:16:01] local.DEBUG: From 2020-04-02  
[2020-03-07 15:16:01] local.DEBUG: To 2020-04-07  
[2020-03-07 15:16:01] local.INFO: ---------------------------------------  
[2020-03-07 15:16:01] local.INFO: ExpiryNotification - MonthBeforeExpiry  
[2020-03-07 15:16:01] local.INFO: DateTime: 07th Mar, 2020 15:16:01 PM  
[2020-03-07 15:16:01] local.INFO: User : Non Found !  
[2020-03-07 15:16:01] local.INFO: ---------------------------------------  

SQL query is :


select `id`, `title`, `type`, `valid_to`, `notification_status`, `user_id`, `status_id` from `documents` 
where `notification_status` = ? and `status_id` = ? and `valid_to` between ? and ?  

Mar
02
5 months ago
Activity icon

Replied to Modify Column On The Fly In Api Output In Laravel

@sti3bas thank you for the assistance :)

Activity icon

Replied to Modify Column On The Fly In Api Output In Laravel

@sti3bas the above answer worked for me perfectly. Thank you for your assistance :D

One last request / help I need now.

as I told that the media file is in relation to user. now not every user have media file uploaded. so how to only get the records of user where they have media file record with them.

what I am doing is

User::with(['media'])->whereStatusId(2)->orderBy('order_id', 'ASC')->get(),

what should I do here to only get the Users, who have media records.