Laravel Form - Sent as an email in a table - laravel

I have a form on my website, which has required fields, and non required fields. The user fills in there details and submits the form. This is then emailed to the owner, and the data is then presented in a table.
However is it possible to show only the data that has been filled in and then remove the fields where no data was entered.
So far I have:
Blade Template:
div class="col-md-6">
<div class="row">
<div class="col-md-6">
<p><b>First Names</b></p>
</div>
<div class="col-md-6">
<p>{{ $first_names }}</p>
</div>
</div>
Which is then sent and is outputted as a table below:
<?php
if (!empty($titles)) {?>
<td class="tg-031e">Title:</td>
<td class="tg-031e">{{ $titles }}</td>
<?php }
?>
But I am assuming an else or else if statement would be required. So how would I have it so that only the fields that where filled in where shown in the table please.
Thanks

If you want to return nothing when there is no title the code below shoud make it work.
#if (isset($titles))
<td class="tg-031e">Title:</td>
<td class="tg-031e">{{ $titles }}</td>
#endif
Let me know if this worls :)
ps: #if(isset($titles)) does not work try #if($titles == NULL)

You can also try something like this:
http://laravel.com/docs/4.2/templates#other-blade-control-structures
Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. Basically, you want to do this:
{{{ isset($name) ? $name : 'Default' }}}
However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut:
{{{ $name or 'Default' }}}

Related

How do I use a row count in an #if in a Laravel view?

I am brand new to Laravel and I'm running Version 6.
I want my view to display a button if one of my MySQL tables has rows that meet a specific condition but I'm having trouble figuring out how to code it - and even WHERE to code it - within my Laravel application.
My MySQL table is called diary_entries and various users of the system will contribute zero to n rows to it. Each row of the table contains a user id called client. When a given user goes to the Welcome view, I want the view to determine if that user currently has any rows in the diary_entries table. If he does, I want to display a button that will take him to another page where the entries can be displayed or edited or deleted.
I think I want to construct an #if that counts the number of records for that user; if the count is greater than zero, I want to display the button, otherwise the button is not displayed.
The problem is that I can't figure out how to code this. I've looked at the examples in the Eloquent section of the manual but they aren't particularly clear to me. I found a note near the top that said the count() function expects a Collection as an argument and that the result of an Eloquent statement is always a Collection so I guessed that I just have to execute an Eloquent query, then apply count() to the resulting Collection. But every variation of that idea which I've tried has thrown exceptions.
Here was the guess that seemed most logical to me:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1> Sleep Diary </h1>
</div>
<div>
<h3>{{Auth::user()->name }}</h3>
</div>
<div>
#if (count(App\DiaryEntry::select('*')->where('client', Auth::user()->name) > 0))
<p>
<a class="btn btn-primary"> View / edit existing sleep diary entries </a>
</p>
#endif
</div>
<div>
<p>
<a class="btn btn-primary" href="/diaryEntries"> Create a new sleep diary entry </a>
</div>
</div>
#endsection
This is obviously wrong because it throws an exception so how do I make it right? Does the building of the collection have to move into the Controller? If so, how do I invoke the method and see its result? Or can I do something like I have already done but just adjust the syntax a bit?
EDIT
I've imitated Sehdev's suggestion but I get this error:
$count is undefined
Make the variable optional in the blade template. Replace {{ $count }} with {{ $count ?? '' }}
Here is my welcome view:
#extends('layout');
#section('content');
<div class="content">
<img class="centered" src="/images/sleeping-cat.jpg" alt="sleeping cat" height="250">
<div class="title m-b-md">
<h1>Sleep Diary</h1>
</div>
<div>
<h3>{{ Auth::user()->name }}</h3>
</div>
<div>
#if ($count) > 0))
<p>
<a class="btn btn-primary">View/edit existing sleep diary entries</a>
</p>
#endif
</div>
<div>
<p><a class="btn btn-primary" href="/diaryEntries">Create a new sleep diary entry</a>
</div>
</div>
#endsection
And this is the relevant function from DiaryEntryController:
public function countEntriesOneUser()
{
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count();
view("welcome", compact("count"));
}
Should the compact function be returning $count instead of count? I can't find the compact function in the manual with the search function so I'm not clear what it does or what the proper syntax is. I just tried changing the last line of the function to
view("welcome", $count);
but that produced the same error.
Try this,
#php
$count=\App\DiaryEntry::where('client', Auth::user()->name)->count();
#endphp
#if($count>1)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
Using App\DiaryEntry::select('*')->where('client', Auth::user()->name) directly on your blade template is a bad practise.
You can execute your question in your controllers method and then pass the result on your view file
Your function
function test(){
$count = DiaryEntry::select('*')->where('client', Auth::user()->name)->count(); // get the total no of records using count
view("index", compact("count")) // pass your count variable here
}
then you can directly use $count in your #if condition
Your blade template
<div>
#if ($count > 0)
<p><a class="btn btn-primary">View/edit existing sleep diary entries</a></p>
#endif
</div>

How can I filter the data of foreach?

I have this design:
I need to say: last post that I add it put it in the head of design then other put them down.
My shut :) Html and foreach code:
#if ($user->projects->count() > 0)
<section class="latest section shadow-sm">
<h1>Projects</h1>
<div class="section-inner">
#foreach ($user->projects->sortByDesc('id')->take(1) as $project)
<div class="item featured text-center ">
// head post
</div>
#endforeach
#foreach ($projects_last->sortByDesc('id') as $project)
<div class="item row">
// other post
</div>
#endforeach
</div><!--//section-inner-->
</section><!--//section-->
#endif
Code of controller for $projects_last:
$projects_last = $user->projects;
$projects_last->pop();
return view('frontend.user_profile',compact('user','projects_last'));
I have the problem with when I say if the #if ($user->projects->count() > 0) do not show any thing but still show me the <h1>Projects</h1> even it is empty!
And if you have any suggest to making my code better pls do it with thankful :)
To iterate Collections you have to get them. So you have to use get() to get the results.
...
#foreach ($user->projects->sortByDesc('id')->take(1)->get() as $project)
...
and
...
#foreach ($projects_last->sortByDesc('id')->get() as $project)
...
You can see here the documentation: Laravel query documentation
Note: if you want to get just one element in your first foreach loop you can use first() instead of take(1). You code will be like that:
#php($first_project = $user->projects->sortByDesc('id')->first())
#if (!is_null($first_project))
// Use $first_project as $project variable
#enif

Eloquent query to blade on view styled better?

I'm doing an assignment (never ending assignments).
I have a query in my controller that sums up certain table items by month and then I show them in a view.
However, I feel I could have done this in a better way as the output looks not great and I'm not sure how to style it.
Controller method
public function monthly()
{
$activity = DB::table('activities')
->select(
DB::raw("Month(date) as Month"),
DB::raw("SUM(minutes) as total_minutes"),
DB::raw("SUM(distance) as total_distance"))
->orderBy("month")
->groupBy(DB::raw("month"))
->get();
return view ('summary/monthly',compact('activity')); }
* View *
#extends('layouts.app')
#section('content')
{{$activity}}
#endsection
Output in view
Any tips on what I could do better?
Edit
Oh man I was definitely over thinking my approach and thought it was an error with my controller. Thank you for the help!
You need something like this:
#foreach($activity as $singleActivity)
{{$singleActivity->Month}}
{{$singleActivity->total_minutes}}
{{$singleActivity->total_distance}}
#endforeach
You need to iterate the loop on your blade file.
#extends('layouts.app')
#section('content')
#foreach($activity as $acti )
<div class="activity">
<div class="month">{{ $acti->Month }}
</div>
<div class="minutes">{{ $acti->total_minutes }}
</div>
<div class="distance">{{ $acti->total_distance }}
</div>
</div>
#endforeach
#endsection
You can iterate your data using #forelse and displa it with table
#forelse ($activity as $act)
<li>
Month: {{ $act->Month }} Total Minutes: {{ $act->total_minutes}} Total Distance: {{ $act->total_distance}}
</li>
#empty
<p>No Activities</p>
#endforelse
I don't know what you like, but how is it?
<table>
<thead>
<tr>
<th>Month</th>
<th>TotalMinutes</th>
<th>TotalDistance</th>
</thead>
<tbody>
#foreach($activity as $act)
{{$act->Month}}
{{$act->total_minutes}}
{{$act->total_distance}}
#endforeach
</tbody>
</table>

Laravel: How to create link buttons on a view dynamically?

I'm making a College Administration website where a professor can log in.
I have a dashboard, where my dynamically generated button should be placed: (right now it just has dummy buttons!)
Generated by this view file, which I will have to modify soon:
<div class="container d-flex flex-column align-items-center justify-content-center">
<h1>IA DASHBOARD</h1>
<br>
<div class="grid2">
SUBCODE 1</button>
SUBCODE 2</button>
SUBCODE 3</button>
</div>
Tables in the Database:
the table iamarks contains the data (student info, and marks) that is to be displayed after /subcode/{subcode} narrows it down to records of just the students that are in the class assigned to current logged-in professor.
classroom_mappers is a table used to map a professor to a classroom with a subject. It makes sure that one classroom only has one professor for a particular subject.
the routes currently in my web.php:
route::get('/ia', 'IAController#show')->middleware('auth');
Route::get('/subcode/{subcode}', 'IAController#showTable')->middleware('auth');
...and these are the methods inside my controller:
//shows buttons to the user:
public function show(){
$subcodes = DB::table('classroom_mappers')
->select('subcode')
->where([['PID','=', auth()->user()->PID]])
->get();
return view('ia',compact('subcodes'));
}
//when user clicks a button, subcode is to be generated and a table is to be shown:
//it works, I tried it by manually typing in subcode value in URL.
public function showTable($subcode){
$sem = DB::table('classroom_mappers')
->where([['PID','=', auth()->user()->PID],
['subcode','=',$subcode]])
->pluck('semester');
$division = DB::table('classroom_mappers')
->where([['PID','=', auth()->user()->PID],
['semester','=',$sem],
['subcode','=',$subcode]])
->pluck('division');
$data = DB::table('iamarks')
->where([['semester','=',$sem],
['division','=',$division],
['subcode','=',$subcode]])
->get();
return view('subcode',compact('data'));
}
My Problem:
To be able to generate the {subcode} in the URL dynamically, I want to create buttons in the dashboard using the data $subcodes. The controller hands over the $subcodes (an array of subject codes which belong to logged in professor) which are to be made into buttons from the show() method.
The buttons should have the name {subcode} and when clicked, should append the same subject code in the URL as {subcode}.
How do I make use of $subcodes and make the buttons dynamically?
How do I make sure the buttons made for one user are not visible to another user?
I managed to find the solution, thanks to Air Petr.
Apparently, you can't nest blade syntax like {{some_stuff {{ more_stuff }} }} and it generates a wrong php code. I modified the solution by Air Petr to:
<div class="grid2">
#foreach ($subcodes as $subcode)
<a href="<?php echo e(url('/subcode/'.$subcode->subcode));?>">
<button class="btn btn-outline-primary btn-custom-outline-primary btn-custom">
<?php
echo e($subcode->subcode);
?>
</button>
</a>
#endforeach
</div>
It generates the buttons perfectly. The buttons for one user are not visible to another, since I'm using PID constraint in a query (['PID','=', auth()->user()->PID]).
Pass the passcodes array to view:
$subcodes = []; // Array retrieved from DB
return view('subcode', compact('subcodes'));
And in subcode.blade.php, loop through each subcode:
<div class="grid2">
#foreach($subcodes as $subcode)
<a href="{{ url('/subcode/' . $subcode->subcode) }}">
<button class="btn btn-outline-primary btn-custom-outline-primary btn-custom">SUBCODE {{ $subcode->subcode }}</button>
</a>
#endforeach
</div>
You can loop your codes to create buttons. Something like this (it's for "blade" template engine):
<div class="grid2">
#foreach ($subcodes as $subcode)
{{ $subcode->subcode }}</button>
#endforeach
</div>
Since you're using PID constrain in a query (['PID','=', auth()->user()->PID]), you'll get buttons for that specific PID. So there's no problem.

Retrieve unique entries from DB using Eloquent Laravel 4

I am using Laravel-4 to build an application. I am trying to make the best use of Eloquent ORM. Currently I am displaying a list of db entries which all have a number of tags associated with them
To the right I display a grid of all the tags however it is showing duplicate tags. I would only like to show unique tags
This is my code:
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::distinct()->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
Does Eloquent provide a way of only retrieving distinct entries from the db?
Try using Tag::groupBy('field_name')->get()
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::groupBy('field_name')->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
To use the distinct()-function you have either have a select() in your chain, or use a field as an argument in your get()-function. For example:
$tags = Tag::distinct()->get(array('field'));
or
$tags = Tag::select('field')->distinct()->get();
You could also instead use groupBy('field') if you don't want to supply field names:
$tags = Tag::groupBy('field')->get();

Resources