kingmaker_bgp

kingmaker_bgp

Member Since 1 Year Ago

Kanyakumari

Experience Points
14,150
Total
Experience

850 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
101
Lessons
Completed
Best Reply Awards
6
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
14,150 XP
Apr
01
3 days ago
Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

Just return the Collection or Model instance from the Controller.

public function someAction()
{
	$collection = Model::conditions()
		->get();
	$model = Model::conditions()
		->first();

	return $collection;
	// OR
	return $model;
}

If you want to Transform the JSON in some particular way, use API Resource (Docs)

Mar
27
1 week ago
Activity icon

Replied to Eloquent WhereHas Relationship With Constraint On Particular Related Entity

That's right @bobbybouwmann, I agree with that...

But is there any way it is possible to achieve in Eloquent? I mean does Eloquent have any support for these type of Queries?

Activity icon

Awarded Best Reply on Update Eloquent Data

You are using the wrong method. ->get() method will return the Collection Instance (Laravel wrapper over Array). To get the Model instance, you have to use ->first() method.

private static function getUserStatusById($id_user,$select='*'){
        return UserStatus::where('id_user',$id_user)
                            ->select($select)
                            ->limit(1)
                            ->first();
    }

Activity icon

Replied to Update Eloquent Data

You are using the wrong method. ->get() method will return the Collection Instance (Laravel wrapper over Array). To get the Model instance, you have to use ->first() method.

private static function getUserStatusById($id_user,$select='*'){
        return UserStatus::where('id_user',$id_user)
                            ->select($select)
                            ->limit(1)
                            ->first();
    }

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

@yassineqoraiche, The Problem seem to be in the MySQL version....

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

It works on my Local Development Setup, which has an installation of mysql 5.7.

But on MariaDB 10.1.44 (on temporary cloud VM) is not supporting this Query :-(

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

Hi @yassineqoraiche, Let me try to make it into Eloquent Builder (I am not sure of the Performance in this)

return $userQuery->whereHas('books', function (Builder $bookQuery) {
	return $bookQuery->where('status', 'deleted')
		->whereRaw(
			"`books`.`id` = (
				SELECT 
					nested_book.`id` 
				FROM 
					`books` AS nested_book
				WHERE 
					nested_book.`user_id` = `users`.`id`
				ORDER BY 
					nested_book.`created_at` DESC
				LIMIT 1
			)"
		);
});

If I were you, I will try to create a Local Query Scope on the User Model as below

class User extends Model {
	public function books() {
		return $this->hasMany(Book::class);
	}

	public function scopeWithLastBook(Builder $query, callable $lastBookConstraint)
	{
		return $query->whereHas('books', function (Builder $bookQuery) use ($lastBookConstraint) {
			// using a Nested WHERE condition --> such that grouping (provided constraint + last book row) doesn't pollute $bookQuery
			return $bookQuery->where(function (Builder $bookQuery) use ($lastBookConstraint) {
				return $lastBookConstraint(
					$bookQuery->whereRaw("`books`.`id` = (
						SELECT nested_book.`id` FROM `books` AS nested_book
						WHERE nested_book.`user_id` = `users`.`id`
						ORDER BY nested_book.`created_at` DESC
						LIMIT 1
					)")
				);
			});
		});
	} 
}

And would use it like this

return $user->withLastBook(function($q) {
		return $q->where('status', 'deleted');
	});

If the code it not clear (due to space limitation in Laracast), you can get that Code Here

Mar
26
1 week ago
Activity icon

Replied to Eloquent WhereHas Relationship With Constraint On Particular Related Entity

@design_studio That will not work.

Your code will return User that has any Book with status = 'deleted' associated with him.

Your code was the exact first Instinct I had, but it doesn't do what we think it does

Challenging part

The Query has a Where Exists condition such that one Constraint has to be validated against Table Column (Field) and another Constraint that has to be validated against related Table Rows (Records)

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

The Raw SQL works well regardless of the Laravel version (No one is still using Laravel 4)

The above Answer will work on Laravel v.5+

Be careful when using Raw SQL... especially when using user submitted data (you are vulnerable to SQL Injection).

In our query, we are not using user-submitted data, so No worries

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

Hi @yassineqoraiche. For the Time being, you can run the Raw Query using DB facade and populate into the Model instance like below

use App\User;
use Illuminate\Support\Facades\DB;

$collection = DB::select(
	DB::raw(
		"SELECT
            		*
	        FROM
        	    `users`
	        WHERE EXISTS
        	    (
	            SELECT
	                *
        	    FROM
                	`books`
	            WHERE
        	        `books`.`user_id` = `users`.`id` AND `books`.`status` = 'deleted' AND `books`.`id` =
			(
                		SELECT
		                    nested.`id`
                		FROM
		                    `books` AS nested
                		WHERE
		                    nested.`user_id` = `users`.`id`
                		ORDER BY
		                    nested.`created_at` DESC
                		LIMIT 1
	            	)
        	)"
	)
);

$filteredUsers = User::hydrate($collection);
return $filteredUsers;
Activity icon

Replied to Eloquent Get Data Using Last Relation Value

Hi @yassineqoraiche, I too don't knew how to achieve this.

I have created a Laracast Question and tagged two of the most well-know guys on the Question.

Once They reply, I will let you know..... You can watch the Discussion here...

P.S: I didn't mean to steal / take credit for your question, But your question intrigued me and I too couldn't find a Solution via Google... So, I created a separate Question with neat context for the Experts to answer.

Activity icon

Started a new Conversation Eloquent WhereHas Relationship With Constraint On Particular Related Entity

Hello Web Artisans and Laravel Enthusiasts,

I had a very interesting and challenging question while browsing through Laracasts

What If we need to have a whereHas constraint on a Many mapping (HasMany, BelongToMany) Relation such that "Related Entity is also subjected to a Constraint"?

Example 1

Original Question

consider having two models User, and Book the last one has a status column that can obtain different string values "active", "inactive", "deleted", so the user can have multiple books and the book belongs to the user.

how could I get only users that have the last book with status deleted?

class User extends Model {
	public function books() {
		return $this->hasMany(Book::class);
	}
}
class Book extends Model {
	public function user() {
		return $this->belongsTo(User::class);
	}
}

The Intuitive thought (which doesn't work) would be like

return $user->whereHas('books', function (Builder $query) {
	$query->latest()
		->where('status', '=', 'deleted');
});

This gives Users that has atleast one (among many Books) that has status = 'deleted'. But what we expected to achieve is to get Users that has last (created_at) Book with status = 'deleted'

The SQL Query for the behavior is given below

SELECT
    *
FROM
    `users`
WHERE EXISTS
    (
    SELECT
        *
    FROM
        `books`
    WHERE
        `books`.`user_id` = `users`.`id` AND `books`.`status` = 'deleted' AND `books`.`id` =(
        SELECT
            nested.`id`
        FROM
            `books` AS nested
        WHERE
            nested.`user_id` = `users`.`id`
        ORDER BY
            nested.`created_at` DESC
        LIMIT 1
    )
)

Example 2

Original Link

Question

How to achieve this query in the Eloquent?

Activity icon

Replied to Eloquent Get Data Using Last Relation Value

Hi @yassineqoraiche,

Your Question is clearly ambiguous. can you please explain what you mean by latest book status = 'deleted' ?

with these words, I could able to infer only the following scenarios.

  1. Last created book with the status = 'deleted'
  2. last Book with the status = 'deleted' belonging to each User.
  3. Users whose Last (latest created_at) Book (among many books) has a status = 'deleted'

Case 1 : Last created book with status = 'deleted'

return Book::latest()
	->where('status', 'deleted')
	->with('user')
	->limit(1)
	->get()
	->user;

Case 2 : last book with status = 'deleted' for each User

return User::with([
	'books' => function($bookQuery) {
		/** @var \Illuminate\Database\Eloquent\Builder $bookQuery */
		return $bookQuery->latest()
			->where('status', 'deleted')
			->limit(1);
	}
])
	->get();

Case 3 : Users who has their last Book status = 'deleted'

This can't be achieved with Laravel Eloquent Builder (as far as my knowledge). You were supposed to do a Raw Query if you want to achieve this.

SELECT
    *
FROM
    `users`
WHERE EXISTS
    (
    SELECT
        *
    FROM
        `books`
    WHERE
        `books`.`user_id` = `users`.`id` AND `books`.`status` = 'deleted' AND `books`.`id` =(
        SELECT
            nested.`id`
        FROM
            `books` AS nested
        WHERE
            nested.`user_id` = `users`.`id`
        ORDER BY
            nested.`created_at` DESC
        LIMIT 1
    )
)
Activity icon

Replied to Eloquent Get Data Using Last Relation Value

From the below citation and the code implementation, it is little bit confusing

how could I get only users that have the last book with status deleted.

  1. Do you want to get the User (only one user) that has the last deleted book? If the above statement is what you wish to achieve, you can use the below code
return Book::latest()
	->where('status', 'deleted')
	->with('user')
	->limit(1)
	->get()
	->user;

// To Access that User
$book->user;
  1. Do you want all users along with thier deleted Book? If the above statement is what you wish to achieve, you can use the below code
return User::with([
	'books' => function($bookQuery) {
		/** @var \Illuminate\Database\Eloquent\Builder $bookQuery */
		return $bookQuery->latest()
			->where('status', 'deleted')
			->limit(1);
	}
])
	->get();

This will attach the last deleted Book as the Collection at $user->books. Please note that the last deleted Book is within the Collection, so to access it you need to call $user->books->first()

Mar
25
1 week ago
Activity icon

Replied to Custom Validation Rule For Update

This is the expected behavior, because the update operation will not always change the Name.

Just have a look at the Docs for the Rule::unique()... Why do it have an additional chaining like ->ignore($id) or ->ignoreModel($instance)?

Laravel Validation Doc

Mar
22
1 week ago
Activity icon

Awarded Best Reply on How To Insert Into Pivot Table

Oopsie, my bad. I didn't go through the code thoroughly. You Controller Action is creating the Service Model incorectly

$service = Service::create([
			'description' => $request->description,
			'carSize' => $request->carSize,
			'price' => $request->price,
			'visible' => $request->visible
		]);

The Service Model doesn't have a column named price. I hope the prices table is used to hold the Price value.

public function create(Request $request)
	{
		$validator = $request->validate([
			'description' => 'required',
			'carSize' => 'required',
			'price' => 'required',
			'visible' => 'required'
		]);
		
		$service = Service::create([
			'description' => $request->description,
			'carSize' => $request->carSize,
			// 'price' => $request->price, --> This doesn't belong here
			'visible' => $request->visible
		]);

		if (!empty($request->price)) {
			$service->price()->create($request->only('price'));
		}

		// Further Actions
	}
Activity icon

Awarded Best Reply on Mmap() Failed: [12] Cannot Allocate Memory

Server RAM was Low

Hi @boyjarv, It seems that you were running a Server with 512 MB RAM

RAM Calculation

I too once had this Problem with some specific version of PHP 7.3. But didn't remember the Solution I found out :-(

Try Googling

Activity icon

Replied to How To Insert Into Pivot Table

Oopsie, my bad. I didn't go through the code thoroughly. You Controller Action is creating the Service Model incorectly

$service = Service::create([
			'description' => $request->description,
			'carSize' => $request->carSize,
			'price' => $request->price,
			'visible' => $request->visible
		]);

The Service Model doesn't have a column named price. I hope the prices table is used to hold the Price value.

public function create(Request $request)
	{
		$validator = $request->validate([
			'description' => 'required',
			'carSize' => 'required',
			'price' => 'required',
			'visible' => 'required'
		]);
		
		$service = Service::create([
			'description' => $request->description,
			'carSize' => $request->carSize,
			// 'price' => $request->price, --> This doesn't belong here
			'visible' => $request->visible
		]);

		if (!empty($request->price)) {
			$service->price()->create($request->only('price'));
		}

		// Further Actions
	}
Activity icon

Replied to How To Insert Into Pivot Table

FYI, ->attach() method is only available on Many to Many Relationship which has a Pivot Table.

Activity icon

Replied to How To Insert Into Pivot Table

Hi @hjortur17,

I am afraid There is no attach() method in the HasOne Relationship. You have to use the create() method on HasOne Relationship.

if(!empty($request->price))
{
	$service->price()->create([
		'price' => $request->price
	]);
}
Activity icon

Replied to Mmap() Failed: [12] Cannot Allocate Memory

Server RAM was Low

Hi @boyjarv, It seems that you were running a Server with 512 MB RAM

RAM Calculation

I too once had this Problem with some specific version of PHP 7.3. But didn't remember the Solution I found out :-(

Try Googling

Mar
21
2 weeks ago
Activity icon

Awarded Best Reply on Access The Different Brands Of The Product Collection

You already have implemented One of a Performance factor in your Query (with/without Knowledge).

To make the Query even more performant, we can do two things (These are not Performant, see last):

1. Eager Load Brands

public function show($gender,$c_slug){
   $products = Product::whereHas('categories',function($query) use ($c_slug){
        $query->where('slug',$c_slug);
    })->where('gender',$gender)
    ->with('brand')
    ->get();

    // ........
}

2. Get the Unique Brands from the Collection

public function show($gender,$c_slug){
   $products = Product::whereHas('categories',function($query) use ($c_slug){
        $query->where('slug',$c_slug);
    })->where('gender',$gender)
    ->with("brand")
    ->get();

   $brands = $products
         ->map->brands // Mapping to get all Brands
         ->flatten() // convert Collection of Collections to flattened Collection of all Brands (repeated)
         ->unique();

   return ['brands' => $brands];
}

Performant Solution

If you only want to sent the Brands in the Response, Why don't get it alone?

public function show($gender,$c_slug){
   $brands = Brand::whereHas("products", function($productQuery) use($gender, $c_slug) {
       return $productQuery->whereHas('categories', function($query) use ($c_slug) {
              return $query->where('slug',$c_slug);
           })->where('gender',$gender);
   })
   ->get();

   return ['brands' => $brands];
}

This Solution requires an Inverse Relation on the Brand model

class Brand extends Model {
   public function products() {
       return $this->hasMany(\App\Product::class);
    }
}

By pushing the Relationship conditions into the Database layer, PHP will avoid creating numerous Collection and Model Instances. You will see the Performance Issues when you started to have 100+ Entities(Model)

Activity icon

Replied to Access The Different Brands Of The Product Collection

You already have implemented One of a Performance factor in your Query (with/without Knowledge).

To make the Query even more performant, we can do two things (These are not Performant, see last):

1. Eager Load Brands

public function show($gender,$c_slug){
   $products = Product::whereHas('categories',function($query) use ($c_slug){
        $query->where('slug',$c_slug);
    })->where('gender',$gender)
    ->with('brand')
    ->get();

    // ........
}

2. Get the Unique Brands from the Collection

public function show($gender,$c_slug){
   $products = Product::whereHas('categories',function($query) use ($c_slug){
        $query->where('slug',$c_slug);
    })->where('gender',$gender)
    ->with("brand")
    ->get();

   $brands = $products
         ->map->brands // Mapping to get all Brands
         ->flatten() // convert Collection of Collections to flattened Collection of all Brands (repeated)
         ->unique();

   return ['brands' => $brands];
}

Performant Solution

If you only want to sent the Brands in the Response, Why don't get it alone?

public function show($gender,$c_slug){
   $brands = Brand::whereHas("products", function($productQuery) use($gender, $c_slug) {
       return $productQuery->whereHas('categories', function($query) use ($c_slug) {
              return $query->where('slug',$c_slug);
           })->where('gender',$gender);
   })
   ->get();

   return ['brands' => $brands];
}

This Solution requires an Inverse Relation on the Brand model

class Brand extends Model {
   public function products() {
       return $this->hasMany(\App\Product::class);
    }
}

By pushing the Relationship conditions into the Database layer, PHP will avoid creating numerous Collection and Model Instances. You will see the Performance Issues when you started to have 100+ Entities(Model)

Feb
24
1 month ago
Activity icon

Replied to Missing Required Parameters For [Route: Student.destroy] [URI: Student/{student}]

Just this one sir Route::resource('student', 'StudentController');

@bosspogs This should have added the DELETE Route for the Resource.

Just check whether the Route is listed with the following Artisan Command

php artisan route:list
Feb
13
1 month ago
Activity icon

Replied to Save Multiple Checkboxes To The Database

If you wish to save those checkbox values as Comma separated string in the Database, you can use the following code.

public function store(Request $request) {
    // TODO do the validation
    Coordenador::create([
        "q9" => $request->q9 ? implode(',', $request->q9) : null,
        "user_id" => auth()->id()
        // Other Stuffs
    ]);

    // TODO send Response
}
Activity icon

Replied to Laravel Auth Login Error

I just spin up a new fresh laravel installation (v.6.0)

composer create-project laravel/laravel="6.0"

and created basic Auth Scaffolding (Bootstap)

composer require laravel/ui --dev
php artisan ui bootstrap --auth

Then I created an Account and logged in with wrong Credential. I didn't get any errors as you said. Wrong Credential Login Screen

If you could provide the following details, It would be helpful to assist & Figure Out the Issue

  1. What laravel/laravel version are you using?
  2. which Auth Scaffolding you were using?
  3. Screenshots
  4. Blade file code