Laravel eager model loading with custom attribute - laravel

Is there any possible way to get a custom attribute value through eager load
For instance, given this custom attribute on a model:
class User extends Model {
protected $appends = ['is_member'];
public function getIsMemberAttribute() {
return 'yes';
}
}
and related model
class Awards extends Model {
public function owner(){
return $this->belongsTo('App\User');
}
}
I would love to be able to get is_member attribute in collection using request below:
$users=Awards::orderBy('created_at')->with('owner')->get();

According to Laravel's documentations, $appends is used for appending in array and JSON only...
Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms.
So, when you do something like dd($user). You will not be able to see the is_member field, but when you do something like $user->toArray() or $user->toJson() you will.
Basically, for places wherever is_member field is always present. All you need to do to access it is (say in Page View/Blade etc)
public function show($id) {
$user = User::get($id);
return view('users.show', ['user' => $user->toArray()]);
}
And then do,
Is Member? : {{ $user['is_member'] }}
// Or if you don't like blade you can do this
// Is Member? : <?php echo $user['is_member'] ?>
But as written in the comments by #Amit, there is no use case of this until you are using it for the sole purpose of APIs. For blade etc, you should prefer doing this
Is Member? : {{ $user->is_member ? 'Yes' : 'No' }}
// Again if you don't like blade you can do this
// Is Member? : <?php echo $user['is_member'] ? 'Yes' : 'No'; ?>
Hope this clears your doubts :)

Related

How to return an int variable from controller to view in Laravel?

I have created a global variable in my CartController for the quantity of an item, here is the declaration:
class CartController extends Controller
{
// defining global quantity variable
private $quantity = 1;
Then in my index() function on the same controller, where I return the view, I pass through the quantity variable like so:
public function index()
{
$this->quantity;
return view('cart.cart', ['quantity' => $this]);
}
But when I call it in the cart.blade.php file like this:
<div class="display-quantity">
{{-- Shows Quantity --}}
<span class="item-quantity" id="item-quantity">{{ $quantity }}</span>
</div>
It gives me the following error:
TypeError
htmlspecialchars(): Argument #1 ($string) must be of type string, App\Http\Controllers\CartController given (View: /Users/rosscurrie/mobile-mastery-latest/resources/views/cart/cart.blade.php)
I think I need to convert it to a string but I need to work with it as an integer so how do I get around this? Thanks!
It look like you're passing in $this as the quantity.
Try changing your controller's index() code to something like:
public function index()
{
$myQuantity = $this->quantity;
return view('cart.cart', ['quantity' => $myQuantity]);
}
It looks like the confusion here is with the -> operator which in php is used to call on object's method or access an object's property the same way . works in Javascript. This statement $this->quantity; accesses the quantity property of $this, so to use it - you need to assign it to a variable (or use it directly). This would have also worked:
public function index()
{
return view('cart.cart', ['quantity' => $this->quantity]);
}
You can always do things like dd($this->quantity); to ensure you are working with the correct information.

Laravel passing data to page

I am trying to pass data to Controller of Laravel. here is how I do that :
in PagesController::
class PagesController extends Controller
{
public function contact(){
$data="some random ";
return view('contact',compact("data"));
}
}
now in contact.blade.php :
contact pages {{ $data }}
and it s hows
Whoops, looks like something went wrong.
What may be a problam?
try this
public function contact()
{
$data = 'some random';
return View('contact')->with('data' , $data );
}
make sure that the view works fine (if its inside a folder use return View('foldername.contact')
make sure that your view name is contact.blade.php (check uppercase letters)
and inside your view
this is my {{ $data }}

how to check if a model is tagged by a specific tag

I have model Entity and related model Tag. The later serves as tags, so the relation is serviced by a pivot table
I guess it is quite easy, but I am lost.
public function tags()
{
return $this->belongsToMany('App\Models\Tag', 'entity_tags', 'entity_id', 'tag_id');
}
Now, in my view I can list all tags:
They are defined
{!!
join(', ',
array_map(function($o) {
return link_to_route('entities.profile',
$o->name,
[$o->id],
['class' => 'ui blue tag button']
);},
$object->tags->all())
) !!}
My question:
how in BLADE I can check if the Entity object has a specific capacity?
in my controller SHOW method I get one single Entity:
$object = Entity::find(34);
and then i wish to do sth if the entity is tagged by a certain tag
#if($object->capacities .... has tag= 3
// do things here
#endif
Thx
You can check if an Entity has a certain tag like this:
#if($entity->tags()->where('id', 3)->exists()) //.... has tag= 3
// do things here
#endif
You could add a public method to your Entity class wich would let you check for an existing tag on this entity :
<?php
public function hasTag($tagToMatch)
{
foreach ($this->tags as $tag)
{
if ($tag->id == $tagToMatch)
return (true);
}
return (false);
}
This would allow you to use the following code in your views :
#if ($entity->hasTag(3))
Do something
#endif

How to implement a generic view presenter in Laravel

I am currently using laracasts/Presenter to handle logic related to my views, this implementation is connected to a model. But I also have some generic view logic that I would like to implement, what is the best practice for creating this?
I have tried two methods, but neither feels right:
Custom class ViewHelper with static functions, called with ViewHelper::Method.
Blade include files, called with #include('includes.navicon')
Is there a better way of doing this? Or is one (or both) of the above acceptable?
Edit: We're talking simple stuff here like insert page title, run text though Markdown parser. This is an example of a function that I use on all pages, it just creates and returns a page header.
public static function PageTitle($level, $title, $small = null)
{
if ($small != null) $title = $title . " <small>" . $small . "</small>";
$html = "<div class=\"page-header\" style=\"margin-top: 0px\"><h%1\$d>%2\$s</h%1\$d></div>";
return sprintf($html, $level, $title);
}
The view presenter that I have installed makes use of the model, so to get a formatted URL for example I would use the command: {{ $article->present()->url }}, while this generic view logic should be available in all views without having to add it to all the models.
I ended up creating a base class that all view presenters extend, and move everything generic there. Functions that is required on views that do not have a model I simply added as static.
Model, I added $presenterInfo to pass information to load the correct view(s) and use as a title prefix. The rest is required by the view presenter.
use Laracasts\Presenter\PresentableTrait;
...
use PresentableTrait;
protected $presenter = 'ArticlePresenter';
public $presenterInfo = ['view' =>'articles', 'category' => 'Article'];
Baseclass, everything generic goes here. So basically everything that might be useful on multiple classes and their views.
use Laracasts\Presenter\Presenter;
class BasePresenter extends Presenter {
public static function pageHeader($level, $title, $small = null)
{
if ($small != null) $title .= " <small>" . $small . "</small>";
$html = "<div class=\"page-header\" style=\"margin-top: 0px\"><h%1\$d>$this->presenterInfo['category']: %2\$s</h%1\$d></div>";
return sprintf($html, $level, $title);
}
public function url()
{
return URL::route($this->presenterInfo['view'] . '.show', array('id' => $this->id, 'slug' => Str::slug($this->title)));
}
}
Viewclass, functions that will only be available for the selected class; in this case Article.
class ArticlePresenter extends BasePresenter {
// Example function only needed by the article class.
public function stump()
{
return Str::limit($this->content, 500);
}
}
Examples, loading view presenter data:
// Show page header level 2
{{ BasePresenter::pageHeader(2, 'Articles') }}
// Enumerate the articles and show title, stump and read more link
#foreach($articles as $article)
<article>
<h3>{{ HTML::link($article->present()->url, $article->title) }}</h3>
<div class="body">
<p>{{ $article->present()->stump }}</p>
<p>Read more...
</div>
</article>
#endforeach

Laravel form select poulated by eloquent model

I am currently making an edit page for some data in my database, and on the edit page I am trying to make a Form::select which lists the people in my users table.
controller-which-makes-the-edit-view.php
<?php
class AdminController extends BaseController
{
public $restful = true;
public function getUpdatePage($id)
{
return View::make('data_edit')
->with('title', 'Rediger måling/oppgave')
->with('data', Routine::find($id))
->with('emp', Emp::lists('user_name', 'id'));
}
data_edit.blade.php
{{ Form::label('emp', 'Ansatt') }}
{{ Form::select('emp', $emp, $data->emps->user_name) }}
Now my question is how would I go about making the default value for the select the person that saved the row which is currently being edited?
I do apologize if this already is answered, I couldn't seem to find it (neither here nor google).
This is Form::select() definition:
public function select($name, $list = array(), $selected = null, $options = array())
{
}
The third parameter is the item to be selected. You are currently passing
$data->emps->user_name
To it, but it depends on the data you have on $emp, because you must pass to it the array key, not the value.
Note that for now (Laravel 5.3+), ::lists is obsolete, use ::pluck instead.

Resources