Skip to content

Instantly share code, notes, and snippets.

@lokmanm
Last active December 30, 2019 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lokmanm/e95786bc3fa8ba659cb859f614aafab2 to your computer and use it in GitHub Desktop.
Save lokmanm/e95786bc3fa8ba659cb859f614aafab2 to your computer and use it in GitHub Desktop.
Laravel Snippets
<?php
/**
* How to properly iterate a relationship
* and map only select fields.
*
*/
$organizations => Auth::user()->account->organizations()
->orderBy('name')
->get()
->map
->only('id', 'name');
/**
* Filter only some requests
*
*/
$filters => Request::all('search', 'trashed');
/**
* How to save data on a relationship model
*
*/
public function addTask($body)
{
return $this->tasks()->create(compact('body'));
}
/**
* Chaining methods to one Model.
*
*/
public function create(User $user)
{
return tap($user)
->update($request->all())
->roles()->sync($request->input('roles', []));
}
/**
* Filtering with relationships
*
*/
public function scopeFilterTickets($query)
{
$query->when(request()->input('priority'), function($query) {
$query->whereHas('priority', function($query) {
$query->whereId(request()->input('priority'));
});
})
->when(request()->input('category'), function($query) {
$query->whereHas('category', function($query) {
$query->whereId(request()->input('category'));
});
})
->when(request()->input('status'), function($query) {
$query->whereHas('status', function($query) {
$query->whereId(request()->input('status'));
});
});
}
/**
* Use the same form for Edit and Create
*
*/
<form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" method="POST" action="/projects">
@csrf
@include('projects._form',[
'buttonText' => 'Create',
'project' => new App\Project,
])
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment