Laravel templating, don't check if relation exists - laravel

I have a relationship between two models which is define by :
class Appartement extends Eloquent {
public function lang()
{
return $this->hasOne('AppartementLang')->where('language_id', '=', '2');
}
}
So nothing big.
When I try to do something like :
#foreach ($appartements as $appartement)
{{$appartement->lang->title}}<br/>
{{$appartement->lang->subtitle}}<br/>
{{link_to('/appartements/'.$appartement->link_rewrite, Lang::get('Discover'))}}<br/>
#endforeach
And that the lang does not exists, then laravel throws an error, which is pretty logical.
I wanted to know if there is some magical way which would allow me not to automate the verification that the relation exists. Basically not turn it into a big "if exists then use" for each property of the class like that :
#foreach ($appartements as $appartement)
#if($appartement->lang){{$appartement->lang->title}}<br/>#endif
#if($appartement->lang){{$appartement->lang->subtitle}}<br/>#endif
{{link_to('/appartements/'.$appartement->link_rewrite, Lang::get('Discover'))}}<br/>
#endforeach
Thanks for the advice on that.

I am sure there are lots of ways to do it (or at least try)
There is this option to check for existing and supply default if none, that I think is new in 4.1 (or at least it is new to me):
#foreach ($appartements as $appartement)
{{ $appartement->lang->title or "default if doesn't exist" }}<br/>
{{ $appartement->lang->subtitle or "default text if doesn't exist" }}<br/>
{{ link_to('/appartements/'.$appartement->link_rewrite, Lang::get('Discover')) }}<br/>
#endforeach
or you could try one of these three if statements if you don't want anything to display for that particular record depending on existance of lang...
#foreach ($appartements as $appartement)
#if ($appartement->lang)
// or maybe:
// #if ($appartement::has('lang'))
// or also maybe:
// #if ($appartement->lang->count())
{{ $appartement->lang->title or "default if doesn't exist" }}<br/>
{{ $appartement->lang->subtitle or "default text if doesn't exist" }}<br/>
{{ link_to('/appartements/'.$appartement->link_rewrite, Lang::get('Discover')) }}
<br/>
#endif
#endforeach

Related

Laravel Blade Helpers not pulling in columns with spaces

I have a table with many columns and some of those columns have spaces in their names (i.e. 'Provider First Name'). I know the syntax to use these in Blade helpers and am using this in other parts of my app: {{$provider->{'Provider First Name'} }}. This works fine in other parts.
I have the following in my ProviderController:
public function show($id)
{
$provider = NPIData::where('NPI', $id)->first();
$providers = NPIData::all();
return view ('profiles.provider', compact('provider', 'providers'));
}
I have brought in the NPIData Model to the controller.
I have the following in my provide.blade.php file:
#extends('layouts.profiles')
#section('content')
<div>
{{ $provider->NPI }}
{{$provider->{'Provider First Name'} }}
</div>
#endsection
Oddly, the NPI will pull in, but the 'Provider First Name' does not. I have tried many other columns with spaces and none of them work. I even copied and pasted from other parts of my app where the syntax to pull these in works and it does not work here.
Instead of:
{{$provider->{'Provider First Name'} }}
Try this:
#php
$providerFirstName = $provider->{'Provider First Name'};
#endphp
{{ $providerFirstName }}
UPDATE
If not you can always go with array access:
{{ $provider['Provider First Name'] }}

get value by name in relational database

by using this code in resource file
#forelse($teachers as $teacher)
{{$teacher->name}} {{$teacher->subjects}}<br>
#empty
Nothing
#endforelse
getting this value
helooo [{"id":3,"name":"Hindi","created_at":"2017-11-18 12:43:33","updated_at":"2017-11-18 12:43:33","pivot":{"teacher_id":16,"subject_id":3}}]
malik [{"id":2,"name":"English","created_at":"2017-11-18 12:43:12","updated_at":"2017-11-18 12:43:12","pivot":{"teacher_id":17,"subject_id":2}}]
hello [{"id":1,"name":"Maths","created_at":"2017-11-18 12:42:34","updated_at":"2017-11-18 12:42:34","pivot":{"teacher_id":18,"subject_id":1}}]
but by using
{{$teacher->name}} {{$teacher->subjects->name}}
getting error
Property [name] does not exist on this collection instance
how can i get just the name value in laravel
Since it's many to many, you need to iterate over subjects of each teacher:
#forelse($teachers as $teacher)
{{ $teacher->name }}<br>
#foreach ($teacher->subjects as $subject)
{{ $subject->name }}<br>
#endforeach
#empty
Nothing
#endforelse
Looks like the data that is being returned is an object in an array. Try adding a zero to select the first obj in this arr. Like this:
$teacher->subjects[0]->name
Good luck!

How to check if used paginate in laravel

I have a custom view and in some functions, I used paginate and other functions I don't use paginate. now how can I check if I used paginate or not ?
#if($products->links())
{{$products->links()}}
#endif // not work
of course that I know I can use a variable as true false to will check it, But is there any native function to check it ?
This works perfectly. Check if $products is an instance of Illuminate\Pagination\LengthAwarePaginator then display the pagination links.
#if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
#endif
#if($threads->hasPages())
{{ $threads->links() }}
#endif
Simple one!
Try like this
#if($products instanceof \Illuminate\Pagination\AbstractPaginator)
{{$products->links()}}
#endif
You need to check wheater the $products is instance of Illuminate\Pagination\AbstractPaginator. It can be an array or Laravel's Collection as well.
As of laravel 7 you can now do this:
#if( $vehicles->hasPages() )
{{ $vehicles->links() }}
#endif
The beautiful way:
#if ($products->hasMorePages())
{{ $products->links() }}
#endif
Click here to see the official documentation
Don't use a check on the base class of the variable. This could lead to problems with changing base classes in future Laravel versions. Simply check whether the method links exists:
#if(method_exists($products, 'links'))
{{ $products->links() }}
#endif
Corrected code (add "isset"):
#if(isset($products->links()))
{{$products->links()}}
#endif
Shorter version:
{{$products->links() ?? ''}}
It will work for paginate, simplePaginate and when there is no pagination. The solution with "$products->hasMorePages()" will not display pagination links on the last page.
Another way:
#if (class_basename($products) !== 'Collection')
{{ $products->links() }}
#endif
You can use PHP function: get_class($products) - to get full class name.
Laravel should have some function to check ->paginate() is in use.
just write paginate(0) instead of get()
Blade Template: simply use {{$products->links}}. no #if #endif needed.
laravel paginate have 2 type :
simplePaginate() will return \Illuminate\Pagination\Paginator
paginate() will return Illuminate\Pagination\LengthAwarePaginator
Based on the above conditions, you can try this solution :
#if(
$products instanceof \Illuminate\Pagination\Paginator ||
$products instanceof Illuminate\Pagination\LengthAwarePaginator
)
{{ $products->links() }}
#endif
Juse use below format
#if($products instanceof \Illuminate\Pagination\LengthAwarePaginator )
{{$products->links()}}
#endif
#if($products->currentPage() > 1)
{{$products->links()}}
#endif

Keeping revision history using VentureCraft/revisionable

I have to display history of changes that are made in my app (like update, insert->who did it , what field changed and when). I am using laravel 4 and I also downloaded this. But the problem is that I am not clear of how to use it. Where to put the folder VentureCraft ? and how to get username or id of the person who did the action. Is there any other way to keep track of history in laravel?
EDIT:
Car model
namespace MyApp\Models;
class Car extends Eloquent {
use \Venturecraft\Revisionable\RevisionableTrait;
}
View
#foreach($description->revisionHistory as $history )
<li>{{ $history->userResponsible()->username }} changed {{ $history->fieldName() }} from {{ $history->oldValue() }} to {{ $history->newValue() }}</li>
#endforeach
and it shows :
Undefined variable: description
Am i missing something in controller?
Check out the README, it looks fairly self explanatory. Install with composer, migrate, then use the RevisionableTrait in your models that you wish to keep the update history of. You can should then be able to get the history of an object with:
$object->revisionHistory;
They even have a simple example of usage within a blade template:
#foreach($account->revisionHistory as $history )
<li>{{ $history->userResponsible()->first_name }} changed {{ $history->fieldName() }} from {{ $history->oldValue() }} to {{ $history->newValue() }}</li>
#endforeach

model relationship and routes get model id

i have the following route:
Route::get('notes/main', function(){
$destinations = Destination::where('show', '=','1')->get();
$notes = Destination::find($destination->id)->notes()->get();
return View::make('notes.main')
->with('destinations', $destinations);
});
//the relationship models:
<?php
class Destination extends Eloquent {
public function notes()
{
return $this->has_many('Note');
}
}
<?php
class Note extends Eloquent
{
public function destination()
{
return $this->belongs_to('Destination');
}
}
//View:
#foreach( $destinations as $destination)
{{ $destination->name}}<br>
{ $notes->destination->text }} // this isn't echoed
#endforeach
what's the correct way to filter this and define $destination->id
thanks
How would i Filter the notes in an if statement inside the loop ?
#if (isset($note->title) != 'shorttext')
#else
<p> {{ $note->text }} </p>
#endif
#endforeach
You use $destination->id in your Route but it seems to be not defined yet. The question is, what do you want to achieve with your code?
With:
$destinations = Destination::where('show', '=','1')->get();
$notes = Destination::find($destination->id)->notes()->get();
you are getting only the Notes of one specific destination (so far, $destination is not defined. You could use Destination::all()->first() to get the first, or Destination::find(id), with ID being replaced with the primary key value of the destination you need).
But I guess you don't want it that way. From your Output it seems like you want to have an output with each destination and below each destination the corresponding Notes.
Controller:
//gets all the destinations
$destinations = Destination::where('show', '=','1')->get();
return View::make('notes.main')
->with('destinations', $destinations);
View:
#foreach( $destinations as $destination)
{{ $destination->name}}<br>
#foreach($destination->notes as $note)
{{ $note->text }} <br>
#endforeach
<hr>
#endforeach
Didn't test this, but this way your View would show you all your Destinations and for each Destination all the Notes.
In your route, your not sending $notes variable to the view.
How I would do it:
$destinations = Destination::where('show', '=','1')->get();
$destinations->notes = Destination::find($destination->id)->notes()->get();
Then in view:
#foreach( $destinations as $destination)
{{ $destination->name}}<br>
{{ $destination->notes->text }}
#endforeach
So first you asked a question, I gave you a correct answer.
You marked my answer as accepted, but later on you edit your initial question to add another question (for which you should create a new thread instead).
Then you create your own answer which is only answering part of your initial question and mark that as the good solution?
I could tell you why your isset and empty did not work, but why should I if you don't value my help at all?
OK
for the last part this worked out at the end
function isset and empty didn't work , strange:
#if ($note->title == 'shorttext')

Resources