Return data to the view in LARAVEL - php

So I do have a table "words" and it has 2 columns "word" and "countofletters"
When I get them in the controller, how can I return them to the view based on the count, basically the view should contain something like:
4 letter words:
1- climb
2- Play
3 letter words:
1- put
2- cut
And so on..

Return from controller
You can send data to the view with compact instruction :
$yourDataFetchedFromDB = "";
return view('myviews.view', compact('yourDataFetchedFromDB'));
In your view
You can now access the value of $yourDataFetchedFromDB in your view as if you were in your controller.
Now you can use something like :
<ul>
#foreach($yourDataFetchedFromDB as $row)
<li>$row->word</li>
#endforeach
</ul>
And to use count columns you can use :
$yourDataFetchedFromDB[0]->countofletters
Full view code
<h2>{{ $yourDataFetchedFromDB[0]->countofletters }}</h2>
<ul>
#foreach($yourDataFetchedFromDB as $row)
<li>$row->word</li>
#endforeach
</ul>
Note : Obviously you should check if $yourDataFetchedFromDB[0] is not empty before using it

Related

How to comma separate properties from a Laravel returned object

First, my apologies if the issue has been resolved. I read a lot of similar posts, but not quite the right one for my case.
I am setting up a simple project in Laravel 5.8. I want to create a simple bookstore and I need a book to have multiple authors so each title is followed by the author, or authors - if many - separated by commas and the last one by the word 'and'.
I have set up two Models, 'Author' and 'Book' and their respective tables, as well as a pivot table since they are in a relation belongsToMany. Everything works like a charm, I get my results as expected. However, I cannot get to format the results as I need. In the case of multiple authors, I always get an extra comma in the end. Since I cannot get the commas right I haven't yet tried to add the last 'and' in the case of the last author.
In the case of a single author the solution is easy, I just use a conditional.
However in the case of multiple authors, thing get complicated.
The most popular method to similar problems was the use of implode() in various similar ways. The problem with this method is since Eloquent is using its internal logic to perform the query, when I loop through 'books', there is no author column, just a reference to the pivot table. In addition, the authors' include first name and last name in different columns. So, when I try to manually create an 'implodable()' array by fetching the respective data otherwise, I get double the item size, since each name consists of the first name and theist name. And on top of that, the whole thing runs inside a double loop, making things even more complicated for me.
I am sure there is a simple way around this.
This is a sample of my blade code as of now. Of course the conditionals should be rearranged accordingly when the problem will be solved, to implement the 'and' case:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#if (count($book->author) == 1)
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
#endforeach
#else
#foreach ($book->author as $name)
{{ $name->last_name }}
{{ $name->first_name }}
{{-- print a comma here if there are other names, or an 'and' if it the last one. Problem seems that it needs to be solved outside the conditional, but how? --}}
#endforeach
#endif
</li>
#endforeach
</ul>
My DB structure:
'authors': 'id', 'last_name', 'first_name','created_at', 'updated_at'
'books': 'id', 'title', 'created_at', 'updated_at'
'author_book': 'id', 'author_id', 'book_id','created_at', 'updated_at'
Expected result:
Title 1, by Author 1
Title 2, by Author 1 and 2
Title 3, by Author 1, 2 and 3
Actual Result:
Title 1, by Author 1
Title 2, by Author 1 and 2 and
Title 3, by Author 1 and 2 and 3 and
If you didn't need the "and" mechanism, then implode with comma would do the job. For "and" mechanism use below code:
<ul>
#foreach ($books as $book)
<li>{{ $book->title }} by
#for ($i = 0; $i < count($book->author); $i++)
{{ $book->author[$i]->last_name }}
{{ $book->author[$i]->first_name }}
#if ($i == count($book->author) - 2)
and
#endif
#if ($i < count($book->author) - 2)
,
#endif
#endfor
</li>
#endforeach
</ul>
added non-breaking-space &nbsp wherever necessary to not get them linked to each other
Delete #if (count($book->author) == 1), if you use foreach inside.
You can't use #else, when before you close condition with #endif.
This #else has wrong construction, use #elseif instead.
If you want check authors count and show extra value, do it inside foreach with $book->author()->count().
What relation u have for book -> author? One book can have many authors or not?
Just display implode(', ', $book->author), based on your actual result you don't need to do complicated checking if/else anymore.
#foreach ($books as $book)
<li>{{ $book->title }} by {{print implode(', ', $book->author)}}</li>
#endforeach

Laravel get div without ajax

Hi I am trying to get the content within a div element that also happens to be within a form into my controller. I dont want to use ajax. How may I get that done ?
<div id="editorcontents" name="editorcontents">
</div>
Then in controller
Use Input;
$content = Input::get('editorcontents');
In your controller, do something like this. Look up the correct way in the docs (https://laravel.com/docs/5.4/eloquent#retrieving-models). For example, if you want ALL input, you would do Input::all();, instead of Input::where('editorcontents')->get();
public function index() {
$content = Input::where('editorcontents')->get();
return view('your_view.blade.file', compact('content'));
}
Then in your view your would now have $content, that you passed from your controller.
start of by looking at it, add this at top of your view: {{ dd($content) }}. This will die dump $content.
Go ahead and remove that line and do something like (docs here https://laravel.com/docs/5.4/blade#loops):
<div id="editorcontents" name="editorcontents">
#forelse ($content as $value)
<li>{{ $value->body }}</li>
#empty
<p>No content</p>
#endforelse
</div>

Laravel 5.3 Blade foreach loop : show data in loop from two different database eloquent queries

I have two tables.
contenttype
content
contenttype returns me list of content types and I show them on page with foreach. e.g. Ambulance service, Blood Bank , clinic etc. as shown in snapshot.
At the same time I am fetching total number of contents of each type from another table(contents).
I was successful to get total number of contents of each type and show on the blade with foreach.
But situation is I want to show the number of contents on every content type.
Like this
Ambulance sevice 8,
Blood Bank 7,
Clinic 4.
My controller method is:
public function index()
{
if (Gate::allows('edit-content', auth()->user())) {
// below line returns list of content type e.g Ambulance service
$type = DB::table('contenttype')->distinct('label')->orderBy('label', 'asc')->paginate(10);
//below line counts the number of each content type e.g. Ambulance service 10.
$count = Content::selectRaw('type, count(*)total')->groupBy('type')->get();
return view('admin.content_listing', compact('type', 'count'));
} else {
abort(403, "Unauthorized");
}
}
This is blade code:
#foreach ($count as $c)
<span class="label label-danger">{{ $c->total }} </span>
#endforeach
This red number list is output:
#foreach ($type as $t)
<div class="list-group-item">
<a href="{{ route('content.type.listing', $t->type ) }}" > {{ $t->label }}
<span class=" pull-right glyphicon glyphicon-search"></span></a>
<span class="col-md-1 glyphicon glyphicon-plus-sign"></span>
</div>
#endforeach
Output is:
If I place above loop in second loop then Of course it will become nested loop that I don't want.
I need to show Ambulance 8,
Beauty clinic 8,
Blood Bank 1,
etc.
If anybody knows the solution kindly share it!
I have tried different ways but no success.
Rather than creating two queries and attempting to combine their results in the view, have you tried performing a join in a single query? Making certain assumptions about your column names and leaving aside the pagination, the actual SQL would be something akin to:
SELECT contenttype.*, count(content.id) FROM contenttype LEFT JOIN content ON contenttype.id = content.type GROUP BY contenttype.label ORDER BY contenttype.label ASC;
The code necessary to implement this query with Laravel's query builder functionality is pretty well documented in the documentation.

Laravel VentureCraft/revisionable returned name record with databse

Hello in my project I using VentureCraft/revisionable https://github.com/VentureCraft/revisionable This is addition to recording the history of changes to records in databse. Everything works fine, but when I returned the history on page, the script returns the results in the form of id. This is my table "products" products_table and this is table "revisions" revisions_table This table is connected to the tables: articles, users and categories. Now the history change looks like this:
"User 1 change name article from 2 to 1"
I want to the history change looked like:
"User JACK change name article from SHOES to BALL"
I try using this link.
method identifiableName() with file Revisionable.php looks like this:
public function identifiableName()
{
return $this->getKey();
}
In model product.php I added:
public function identifiableName(){
return $this->article_name;
}
or this:
public function identifiableName(){
return $this->article()->article_name;
}
but it does not work.
OK I found solution to this problem:
Only just use:
whereId or find or faindOrFail
example:
article::whereId( $hist->old_value )->first()->article_name
or
article::find( $hist->old_value )->article_name
or
article::findOrFail( $hist->old_value )->article_name
Where article:name is name column in articles table.
you can use
$history->userResponsible()->first_name
like the documentation says
#foreach($resource->revisionHistory as $history)
#if($history->key == 'created_at' && !$history->old_value)
<li>{{ $history->userResponsible()->first_name }} created this resource at {{ $history->newValue() }}</li>
#else
<li>{{ $history->userResponsible()->first_name }} changed {{ $history->fieldName() }} from {{ $history->oldValue() }} to {{ $history->newValue() }}</li>
#endif
#endforeach
or if you want to use it as response api, you can manipulate the response to get their relations
$response = $question->revisionHistory->map(function($history) {
return ['history' => $history, 'users' => $history->userResponsible()];
});
return response()->json($response);

How to include a controller method's view as a part of another controller view in Laravel PHP Framework

Halo here is my need;
i want to include different view as apart of different view in laravel php frame work.
class DashboardController extends BaseController {
public function comments( $level_1=''){
// process data according to $lavel_1
return View::make('dashboard.comments', $array_of_all_comments);
}
public function replys( $level_2=''){
// process data according to $lavel_1
return View::make('dashboard.replys', $array_of_all_replys);
}
these both data can now accessed from
www.abc.com/dashboard/comments
www.abc.com/dashboard/replys
And in my view what i need is to generate replys according to the comments id ($lavel_2)
// dashboard/comments.blade.php
#extends('layout.main')
#section('content')
#foreach($array_of_all_comments as $comment)
comment {{ $comment->data }},
//here is what i need to load reply according to the current data;
//need to do something like this below
#include('dashboard.replys', $comment->lavel_2) //<--just for demo
.................
#stop
and in replys also got
#extends('layout.main')
#section('content')
// dashboard/replys.blade.php
#foreach($array_of_all_replys as $reply)
You got a reply {{ $reply->data }},
...........
#stop
is there any way i can achieve this on laravel 4?
Please help me i wanted to load both comments and replays in one go and later need to access them individually via ajax also
please help me thank you very much in advance
halo i found the solution here
all we need is to use App::make('DashboardController')->reply();
and remove all #extends and #sections from including view file
the change are like this
// dashboard/comments.blade.php
#extends('layout.main')
#section('content')
#foreach($array_of_all_comments as $comment)
comment {{ $comment->data }},
//<-- here is the hack to include them
{{-- */echo App::make('DashboardController')->reply($comment->lavel_2);/* --}}
.................
#stop
.............
and in replys is now changed to
// dashboard/replys.blade.php
#foreach($array_of_all_replys as $reply)
You got a reply {{ $reply->data }},
...........
#endforeach
-------------
thanks
You probably want to rework your views and normalise your data. Comments and replies are (probably) the same.
If you make a Comment model which belongsTo "parent" (another Comment model) and hasMany "children" (many Comment models), then simply set parent_id to 0 for a top-level Comment, and set it to the ID of another Comment to make it a Reply.
Then your Blade views do something like:
comments.blade.php
#foreach ($comments AS $comment)
#include( 'comment', [ 'comment' => $comment ] )
#endforeach
comment.blade.php
<div>
<p>{{{ $comment->message }}}</p>
#if( $comment->children->count() )
<ul>
#foreach( $comment->children AS $comment )
<li>
#include( 'comment', [ 'comment' => $comment ] )
</li>
#endforeach
</ul>
#endif
</div>

Categories