Pagination in laravel for displaying awkwardly - html

I have the following code to display unsolved questions from the database
<h2> Unsolved Questions </h2>
#if(!$questions)
<p> There are no Unsolved Questions </p>
#else
<ul>
#foreach($questions as $question)
<li> {{ $question->questions }}</li>
#endforeach
</ul>
{{ $questions->links() }}
#endif
The result displays properly however the pagination results shows like this
«
1
2
»
Where could the problem be?
Controller
public function create()
{
return View::make('questions.create')
->with('title', 'Q&A ask/Answer question')
->with('questions', Question::unsolved());
}
Model
public static function unsolved()
{
return static::where('solved', '=', 0)->orderBy('id', 'DESC')->paginate(5);
}

I have been able to change this by editing apps/config/view.php
and changed pagination from 'pagination' => 'pagination::slider-3',
to 'pagination' => 'pagination::slider',
this gave me a pagination that looks like this `
« 1 2 »

Related

Bootstrap button with a badge counter not working

I have a Bootstrap button with a badge counter (a numerical indicator of how many items are associated with the link).
Events <span class="badge badge-light">{{ $events = Event::where(['status' => 0])->count() }}</span>
The link works OK, but the badge counter isn't working. It should check how many events are in the database and show that number on the badge counter. So, something is wrong with this line:
{{ $events = Event::where(['status' => 0])->count() }}
I tried adding to my Events controller
public function events()
{
return view('groups.index', [
'count' => Event::where(['status' => 0])->count(),
]);
}
and calling {{ $count }}
but I get this error
Call to a member function count() on null (View: C:\laragon\www\version2\resources\views\groups\index.blade.php)
Note: The button needs to count the number of event, but the button itself shows on the groups.index page (mentioned for clarity)!
Extract logic in controller.
use \App\Event; // use your model
public function someMethod()
{
// other code
return view('some.view', [
'count' => Event::where(['status' => 0])->count(),
]);
}
view:
Events <span class="badge badge-light">{{ $count }}</span>

php printf 5 digit but show extra 1 digit

I found a problem about printf('%50d',33) As title,
I just want it to show 00033, but it shows 000335.
i try printf('%50d-',33) it become 00033-6,
if not wrong last number is total digit count.
May I know how to remove that?
EDITED
Model/Product.php
class Product extends Model
{
protected $appends = ['code'];
public function getCodeAttribute(){
return $this->attributes['code'] = sprintf("A%'.05d",$this->id);
}
}
View/home.blade.php
<ul class='codeList'>
#foreach($products as $product)
<li>
<div class='name'>{{ $product->name }}</div>
<div class='code'>{{ $product->code }}</div> {{-- This Part Show A00033 --}}
</li>
#endforeach
</ul>
Looks like your format string is not in the right order as mentioned by Matt.
Should be printf("%'.05d\n",33);
Problem Solved.
use sprintf("A%'.05d",$this->id); instent of printf("A%'.05d",$this->id);
Thanks #Matt for the link.
Update Answer to question post.

Retrieving data from junction table via foreign key - Laravel

I'm trying to get data from a junction table and display it, so I have a users table and my junction table prescription_user. Prescription_user table has a user_id and prescription_id.
So what I'm trying to do is on this userdetails page, show all of this users prescriptions and access the prescription name and description etc, however when I try any of this I get "Trying to get property of non-object"
The models are set up to eager load correctly I think, the user model has a hasMany relation with the prescription_user model, and the prescription_user model has a belongsTo the user model.
Controller
function viewUserDetails($userId)
{
$logged_user_id = Auth::user()->id;
$user = User::find($logged_user_id);
$prescriptions = Auth::user()->prescription_user;
$fullname = $user->firstname ." ". $user->surname;
$email = $user->email;
$address = $user->address;
$postcode = $user->postcode;
$dob = $user->dateofbirth;
$uniquepatientnumber = $user->uniquepatientnumber;
$data = [];
$data['fullname'] = $fullname;
$data['email'] = $email;
$data['address'] = $address;
$data['postcode'] = $postcode;
$data['dateofbirth'] = $dob;
$data['uniquenumber'] = $uniquepatientnumber;
$data['prescriptions'] = $prescriptions;
return view('user/userdetails')->withData($data);`
userdetails blade
#extends('layouts.master')
#section('title', 'My Details')
#section('content')
<h1>My Details </h1>
<ul>
<li>Name: {{ $data['fullname'] }}</li>
<li>Email: {{ $data['email'] }}</li>
<li>Address: {{ $data['address'] }}</li>
<li>Postcode: {{ $data['postcode'] }}</li>
<li>Date of Birth: {{ $data['dateofbirth'] }}</li>
<li>Your Unique number is: {{ $data['uniquenumber'] }}</li>
<li>Your are currently prescribed {{$data['prescriptions']}}</li>
<p>Note: If you believe any of these are incorrect please contact a receptionist</p>
</ul>
#endsection``
There are some design flaws in what you have explained. You have a User model and a Prescription model. That means prescription_user is your pivot table (not junction table). If so far I'm correct, it means User and Prescription have a Many to many relationship. To prove my point, you said
Prescription_user table has a user_id and prescription_id.
That means prescription_user is the pivot table.
In your user model, define a many to many relationship with prescription. And vice versa.
User model
public function prescriptions() {
return $this->belongsToMany(Prescription::class, 'prescription_user', 'user_id', 'prescription_id');
}
Then you can change your controller function like this
public function viewUserDetails()
{
$user = Auth::user();
$prescriptions = $user->prescriptions;
return view('user/userdetails', compact('user', 'prescriptions'));
}
And your view
#extends('layouts.master')
#section('title', 'My Details')
#section('content')
<h1>My Details </h1>
<ul>
<li>Name: {{ $user->firstname }} {{ $user->surname }}</li>
<li>Email: {{ $user->email }}</li>
<li>Address: {{ $user->address }}</li>
<li>Postcode: {{ $user->postcode }}</li>
<li>Date of Birth: {{ $user->dateofbirth }}</li>
<li>Your Unique number is: {{ $user->uniquepatientnumber }}</li>
</ul>
Your are currently prescribed
<ul>
#foreach($prescriptions as $prescription)
<li>{{ $prescription->name }}
#endforeach
</ul>
<p>Note: If you believe any of these are incorrect please contact a receptionist</p>
#endsection
Your code would be neater and working great
Update
Getting data from the pivot table is relatively simple. Define those columns in the relationship
public function prescriptions() {
return $this->belongsToMany(Prescription::class, 'prescription_user', 'user_id', 'prescription_id')->withPivot('column1', 'column2');
}
In your view, you display it like this
{{ $prescription->pivot->column1 }} {{ $prescription->pivot->column2 }}
First I'm not sure that withData() is a thing. Just ->with($data).
Second, there is some confusion at the beginning of your function. You pass in a $userId, that you never use. Then you get the id from Auth::user(), then get a user with that id, which you already had. So just $user = Auth::user();
Third, you only get that error trying to use the -> operator on a non-object, and you only use it on $user-> and Auth::user()->
Since you got the user from Auth::user in the first place, I'm guessing it failed right out of the box at Auth::user()->id, and there is no Auth::user, but you would have to post a little more data, either from the error in the browser or from storage/logs/laravel.log.
BUT, if I use this code
Route::get('/', function () {
$user = \Auth::user();
die($user->name);
return view('welcome');
}
where there clearly is no Auth::user() (I haven't even got to a login yet) I get this output:
ErrorException in web.php line 16:
Trying to get property of non-object
1. in web.php line 16
2. at HandleExceptions-> ... array('user'=>null)
So it's probaby that.

Pulling records from MySQL Db using Laravel 5.1 Pagination

Someone please help me! How Do I render the records of a DB using pagination? When I tried using this code based on the tutorial I'm using I'm getting this error below. I'd thought the results is a method in Paginate class.
<div id="questions">
<h2>Unsolved Questions</h2>
#if(!$questions->results)
<p>No questions have been asked</p>
#else{
<ul>
#foreach($questions->results as $question)
<li>{!! e($question->question) !!}</li>
#endforeach
</ul>
{!! $questions->links !!}
}
#endif
</div>
from ur controller e.g
$question_model = Questions::where('answer_count','=','0')->orderby('created_at','desc')->paginate(5);
in ur front end for pagination
{!! $question_model->render() !!}
This is the resolve to the question I posted as a response comment to #ujwal dhakal. What I wanted is to append the username of the user that asks a question.
The first thing I did is to add the user collection to the index.blade.php view of the question, then iterate through it and pick the username that matches the username of the Auth user that posted the question.
#if(!count($questions) > 0)
<p>No questions have been asked</p>
#else
<ul>
#foreach($questions as $question)
<li>{!! e(str_limit($question->questions, 35)) !!} by
#if(count($users) > 0)
#foreach($users as $user)
#if($user->id === $question->userid)
{!! $user->username !!}
#endif
#endforeach
#endif
</li>
#endforeach
</ul>
{!! $questions->render() !!}
#endif

twig striptags and html special chars

I am using twig to render a view and I am using the striptags filter to remove html tags.
However, html special chars are now rendered as text as the whole element is surrounded by "".
How can I either strip special chars or render them, while still using the striptags function ?
Example :
{{ organization.content|striptags(" >")|truncate(200, '...') }}
or
{{ organization.content|striptags|truncate(200, '...') }}
Output:
"QUI SOMMES NOUS ? > NOS LOCAUXNOS LOCAUXDepuis 1995, Ce lieu chargé d’histoire et de tradition s’inscrit dans les valeurs"
If it could help someone else, here is my solution
{{ organization.content|striptags|convert_encoding('UTF-8', 'HTML-ENTITIES') }}
You can also add a trim filter to remove spaces before and after.
And then, you truncate or slice your organization.content
EDIT November 2017
If you want to keep the "\n" break lines combined with a truncate, you can do
{{ organization.content|striptags|truncate(140, true, '...')|raw|nl2br }}
I had a similar issue, this worked for me:
{{ variable |convert_encoding('UTF-8', 'HTML-ENTITIES') | raw }}
I was trying some of, among others, these answers:
{{ organization.content|striptags|truncate(200, true) }}
{{ organization.content|raw|striptags|truncate(200, true) }}
{{ organization.content|striptags|raw|truncate(200, true) }}
etc.
And still got strange characters in the final form. What helped me, is putting the raw filter on the end of all operations, i.e:
{{ organization.content|striptags|truncate(200, '...')|raw }}
Arf, I finally found it :
I am using a custom twig filter that just applies a php function:
<span>{{ organization.shortDescription ?: php('html_entity_decode',organization.content|striptags|truncate(200, '...')) }}</span>
Now it renders correctly
My php extension:
<?php
namespace AppBundle\Extension;
class phpExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('php', array($this, 'getPhp')),
);
}
public function getPhp($function, $variable)
{
return $function($variable);
}
public function getName()
{
return 'php_extension';
}
}
2022 update | tested with Drupal 8.6.16
I tried the top voted recommendation. It worked ok with some symbols but not with others.
raw filter seems to be working ok with all special characters.
like so
{{ organization.content|striptags|raw }}
The best way to do this is :
{{ organization.content|striptags|truncate(200, '...')|raw }}
With |raw always at the end.
Don't use convert_encoding('UTF-8', 'HTML-ENTITIES'), you will encounter iconv issues.
When I thought none of the above answers were working for me (convert_encoding running into iconv() issues in Drupal 9, and I thought raw, but because applying it on the argument side of an {% embed %} — as opposed to in the embedded template itself — didn't seem to help), another approach that seemed to work for me was:
{% autoescape false %}
{{ organization.content|striptags|truncate(200, '...') }}
{% endautoescape %}
with that false part being key.
I had the same problem, I resolved it byt this function below, using strip_tags.
<?php
namespace AppBundle\Extension;
class filterHtmlExtension extends \Twig_Extension
{
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('stripHtmlTags', array($this, 'stripHtmlTags')),
);
}
public function stripHtmlTags($value)
{
$value_displayed = strip_tags($value);
return $value_displayed ;
}
public function getName()
{
return 'filter_html_extension';
}
}