Laravel 6 Eloquent Global Scope Tutorial Example

Today, We want to share with you Laravel 6 Eloquent Global Scope Tutorial Example.In this post we will show you Lesson 6.2 Global Scopes and Traits, hear for Global Query Scopes And Pagination we will give you demo and example for implement.In this post, we will learn about laravel global scope with parameter with an example.

Laravel 6 Eloquent Global Scope Tutorial Example

There are the Following The simple About Creating and Using Query Scopes with Laravel 6.2 Full Information With Example and source code.

As I will cover this Post with live Working example to develop Re-using query constraints in Laravel Eloquent, so the laravel accessor date format is used for this example is following below.

Step 1: Applay Eloquent Global Scope

app/models/MovieUpcommingScope.php

getQualifiedPublishedColumn();

		$builder->where($column, '=', 1);

		$this->addWithDrafts($builder);
	}

	public function remove(Builder $builder, Model $model)
	{
		$query = $builder->getQuery();

		$column = $model->getQualifiedPublishedColumn();

		$bindingKey = 0;

		foreach ((array) $query->wheres as $key => $where)
		{
			if ($this->isPublishedConstraint($where, $column))
			{
				$this->removeWhere($query, $key);
				$this->removeBinding($query, $bindingKey);
			}
			if ( ! in_array($where['type'], ['Null', 'NotNull'])) $bindingKey++;
		}
	}

	protected function removeWhere(BaseBuilder $query, $key)
	{
		unset($query->wheres[$key]);

		$query->wheres = array_values($query->wheres);
	}

	protected function removeBinding(BaseBuilder $query, $key)
	{
		$bindings = $query->getRawBindings()['where'];
		unset($bindings[$key]);
		$query->setBindings($bindings);
	}

	protected function isPublishedConstraint(array $where, $column)
	{
		return ($where['type'] == 'Basic' && $where['column'] == $column && $where['value'] == 1);
	}

	protected function addWithDrafts(Builder $builder)
	{
		$builder->macro('withDrafts', function(Builder $builder)
		{
			$this->remove($builder, $builder->getModel());

			return $builder;
		});
	}
}

Step 2: Create a Laravel 6 Scope

app/models/MovieUpcommingTrait.php

getTable().'.'.$this->getPublishedColumn();
	}

	public static function withDrafts()
	{
		return with(new static)->newQueryWithoutScope(new MovieUpcommingScope);
	}
}

Step 3: Define a Laravel 6 Model

Laravel scope for the Movie model:



Step 4: Get All Records using Laravel 6 Eloquent


App\Movie::all();
App\Movie::first();

App\Movie::withDrafts()->get(); 

App\Movie::where('is_active', 'yes')->withDrafts()->get();

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel global scope with parameter.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment