Laravel Change background from database information - php

I am making a Crud application. i have a database table called 'tag' in here is a column called 'color'
In my index.blade.php (for the crud) i want my table row to be the color i put in my database, by string.
Data example;
[id = '1', name = 'dutch', color = 'red']
code i currently have in my blade file:
#foreach($tags as $tag)
<tr>
<td>{{$tag->id}}</td>
<td>{{$tag->name}} </td>
<td style="background:{{$tag['color']}} ;">{{$tag->color}} </td>

You should Add background-color, It would be Much better if you can save Color codes instead of strings in DB.
<td style="background-color:{{$tag['color']}} ;">{{$tag->color}</td>

Related

list multiple in one row in one column

I am sorry but I don't even know how to title this question since I have no clue what to look for.
Here is my problem: I have the following list:
name
word
hit
Bill
performance
2
Anna
performance
5
John
performance
3
Bill
java
0
Anna
java
1
John
java
3
Bill
test
4
Anna
test
5
John
test
1
What I am trying to get is the following:
name
sum(hit)
words_count
Bill
6
performance = 2 java = 0, test = 4
Anna
11
performance = 5 java = 1, test = 5
John
7
performance = 3 java = 3, test = 1
I could sum all hits and group by words and so but I only need one dataset each name.
I think I need a subquery or so. How can I get the words_count column in that way?
Actually I need it a Laravel controller to display it in a datatable but an SQl statement would help me a lot also.
Appreciate your help.
Hi guys i thank you a lot for your answers.
I could manage it in SQL. So the statement is the following:
SELECT name, sum(hit) as points,
GROUP_CONCAT(concat(word, '->'), concat(hit, ' ') separator ' ' ) as words
FROM results
GROUP BY name;
This gives me exactly what i need.
I am display my data in a datatable (yajra). I will now "translate" this code to "laravel / php" code to feed my datatable.
Let's consider, you have a model named UserPerformance
$userPerformance = UserPerformance::all();
$result = $userPerformance->groupBy('name');
And in your blade template:
<table>
<thead>
<tr>
<th>name</th>
<th>sum(hit)</th>
<th>words_count</th>
</tr>
</thead>
<tbody>
#foreach($userPerformance as $name => $performance)
<tr>
<td>{{ $name }}</td>
<td>{{ $performance->sum('hit') }}</td>
<td>
{{ $performance->map(function($p) { return $p->word.' = '.$p->hit; })->implode(', ') }}
</td>
</tr>
#endforeach
</tbody>
</table>
You can also add your map() code to your model using an accessor to keep the blade template clean:
class UserPerformance extends Model
{
public function getWordCountAttribute()
{
return $performance->map(function($p) {
return $p->word.' = '.$p->hit;
})->implode(', ');
}
}
You can access it like this: $userPerformanceModel->word_count;
That also enables you, to re-use the code. You can also append this accessor during serialization to use it client-side.

Store specific value in PHP

I am trying to store specific value in laravel. Here Select User not required field but in foreach loop hidden field proj_id must has value. Suppose there are 5 rows and I want to store only 2nd and 5th user along with proj_id from hidden field. Here I want to mention that in controller I also kept delete operation so that I can remove previously inserted SAME PROJECT ID related record. For example If I want to store 2nd and 3rd user, that time only 2nd and 3rd users record will remove first then insert. In my code there are logical error but could not find solution. Thanks in advance
<form action="{{ url('/save-project') }}" method="POST">
<tr>
#foreach($projects as $val)
<td>
<input type="hidden" name="proj_id[]" value="{{$val->id}}">
<select name="user_id[]">
<option value="">Select User</option>
<option value="2">x</option>
<option value="4">y</option>
</select>
</td>
#endforeach
</tr>
<input type="submit">
</form>
Controller
$countUserID = count($user_id);
assign_project::where('flag','Y')
->WhereIn('proj_id',$request->proj_id)
->delete();
for($i=0;$i<$countUserID;$i++){
$assign_project = new assign_project();
$assign_project->proj_id = $request->proj_id[$i];
$assign_project->user_id = $request->user_id[$i];
$assign_project->save();
}
JSON fields are gaining more popularity since they became officially supported in MySQL 5.7.8. Even the popular Spatie Laravel Medialibrary package use them, so why shouldn’t we?
To create a JSON field, all we need to do in Laravel migration is use ->json() method:
$table->json('array_data');
Next, you need to tell your model to cast that column from JSON to an array automatically:
class Product extends Model
{
protected $casts = [
'array_data' => 'array'
];
}
This way, you will receive $array_data as array and don’t need to do json_decode() at all.

Table data formatting ( Data from database)

Fetching the array data and using explode i have separated the content. Now, i want to print those data in the list. But products are printing in the line. I tried using "break tag" And "list tag" Every possible ways.
Here is the code
<tbody id="test">
#foreach ($data['samplingData'] as $key => $samplingData)
<tr> <td>{{$samplingData->doctor_name}}</td>
<td>{{$samplingData->date}}</td>
#foreach(explode(',', $samplingData->products) as $product)
<td> {{$product}} </td>
#endforeach
<td>{{$samplingData->quantity}}</td> </tr>
#endforeach
</tbody>
Data is printing in this way
Name date products quantity
a 12-12-12 a a a a 1 1 1 1
I want to print like this
Name date products quantity
a 12-12-12 a 1
a 1
a 1
I tried adding tr inside td and as well as list inside the td.
Please help me in formatting the data.
Basically you were creating <td> for-each $product.
<td>#foreach(explode(',', $samplingData->products) as $product) {{$product}} <BR/> #endforeach</td>

Laravel - Append row id to form name attribute inside each row of a dynamic table

I send two variable to my view $abilities, and $users. $abilities is an array of key-value pairs containing data in the following format:
["1"=>"create_user","2"=>"delete_user","3"=>"ban_user"]
$users is an array in the following format:
["1"=>"John Doe","2"=>"Jane Doe"]
Both are taken from their respective databases abilities (columns: ID, name) and users (columns: ID, name).
In the view, I have a table which contains a multiple select for each row against the $user->id:
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>
{{Form::select("takenabilities[]",$abilities, null, ['id'=>'system-abilities','multiple','class'=>'form-control' ])}}
</td>
</tr>
#endforeach
Problem is that when I receive the request in my controller, I only see one takenabilities[] array, and I want to save data from each multiple select in each row generated dynamically, if that makes sense?
You can't do that using multiple selects with the same name. The value of the last one overrides all previous selects' values. In addition you'd better assign different id to every select. Try to add another level to the array:
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>
{{Form::select("takenabilities[$user->id][]", $abilities, null, ['id'=>'system-abilities-' . $user->id,'multiple','class'=>'form-control' ])}}
</td>
</tr>
#endforeach
And in controller:
$takenabilities = [];
foreach(Request::input('takenabilities') as $userId => $userAbilities) {
$takenabilities = array_merge($takenabilities, $userAbilities);
}
$takenabilities = array_unique($takenabilities);

Populate table in Laravel with ajax?

I have a Laravel application where I create a page layout, adding a table to it as a "content" variable (pretty much all from tutorials I found). Here's the controller action:
public function getMain() {
$js_config = Category::all();
$resources = Resource::all()->take(100);
$this->layout->content = View::make('categories.show')->with('js_config', $js_config)->with('resources', $resources);
}
This uses the main layout template and inserts this table using the content variable:
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
</thead>
<tbody>
#foreach($resources as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->title }}</td>
</tr>
#endforeach
</tbody>
</table>
But then comes the problem: I have a jstree where the user can select nodes, triggering a jQuery method:
$('#jstree2').on("changed.jstree", function (e, data) {
console.log(data.selected);
$.get("filter", { category: data.selected })
.done(function (resultdata) {
//Test only, this returns the data wanted in json, which I stringify just to display in test
alert("Data Loaded: " + JSON.stringify(resultdata));
});
});
The jQuery calls this action method in the controller:
public function getFilter()
{
$input = Input::get('category.0');
$categories = Category::find($input);
//category is the name from the model below
return Response::json(array(
'error' => false,
'category' => $categories->toArray()),
200
);
}
(The reason there's an array as input is I eventually want to be able to allow picking multiple nodes in the tree)
This action gets the data from the DB correctly and returns it as json. The callback in the jQuery above then alerts this at the moment, just as a test.
But what I really want to do, of course, is to repopulate the table. Now, as you can see I have used Bootstrap to create a pretty table and all, and I just want to be able to let the user repopulate it at will, without refreshing the page.
But I don't know how to do that, except by painstakingly recreate this table in some sort of string return value, but that doesn't seem like a good idea.
I'm hoping there's some way of passing the return value back to the view and have it reload the values in the table, utilizing the same "sub view" that I loaded in the php variable "content" as described above?
Any help greatly appreciated!
EDIT:
As requested, here's a sample of the json (taken from the browser console output, and it's actually not the categories table, but the same format):
[{"id":"1","title":"Transportation AC 4494","created_by":"4","modified_by":null},{"id":"2","title":"Safety First AC 4294","created_by":"3","modified_by":null},{"id":"3","title":"Warranty AC 34066","created_by":"4","modified_by":null}]
EDIT 2 (Just realized there was some crap from the controller in the previous edit of the json, so I changed it to a cleaner sample now)
EDIT 3:
I have made this work by creating the table rows in jQuery:
var trHTML = '';
$.each(resultdata, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.title + '</tr>';
});
$('#ajaxtable').html(trHTML);
But mainly I'm hoping this might explain my question better: this is not what I wanted to do. What I would have wanted was to just create a partial view and then load that ready-made view with the jquery:
A partial view like this:
<table class="table table-striped table-bordered" id="resultstable">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
</thead>
<tbody id="ajaxtable">
#foreach($resources as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->title }}</td>
</tr>
#endforeach
</tbody>
</table>
I tested this by creating and calling a new function in the controller from the jquery code:
public function getTable()
{
$resources = Resource::all()->take(5);
return View::make('categories.results')->with('resources', $resources);
}
But it doesn't work. Although it does indeed give me the html of that view, it is unprocessed. I.e, the foreach loop is not resolved, but still there as code in the table. See the image:
So how can I load this view with the jquery code? It feels to me that even if the jquery creation of table rows works, doing the view in php and then just loading it with jquery should be the more correct way of doing it...?
Have you looked into the Datatables jQuery plugin? There is actually a nice package for Laravel that helps integrate Laravel and Datatables. The Laravel package generates the json and you can use Datables+AJAX to repopulate the data. Might be working checking out...
https://github.com/Chumper/datatable
http://datatables.net/
Otherwise, you'll just need to use AJAX to repopulate the table.
As Sirago answered, using jQuery Datatables is a good option to load data into tables in ajax manner.
In addition to what Sirago suggested, here is another great Laravel 4 package which is dedicated to generate JSON data from server side.
https://github.com/bllim/laravel4-datatables-package
But apart from server side configuration(modifying files like composer.json, config/app.php etc.), you need to code in Javascript, utilizing Datatables as well.

Categories