How to get jsonencode data in laravel? - javascript

controller
public function rooms_detail(Request $request)
{
$data['room_id'] = $request->id;
$data['result'] = Rooms::find($request->id);
echo $data['result'];
return view('rooms.rooms_detail', $data);
}
view:rooms/rooms_detail
#foreach($result as $row)
<div class="hero-text">{{ $row->name }}</div>
#endforeach
In this code I have a controller function where I am run a query inside the Rooms Model which works fine and my data look like {"id":16,"user_id":10088,"name":"5 \u2b50 RESORT RETREAT W\/HEATED POOL SPRAWLING GROUNDS"}. but I am unable to fetch this data in my view file. So, How can I ndo this? Please help me.
Thank You

In Docs of Laravel, you may also retrieve single records using find or first: https://laravel.com/docs/5.8/eloquent#retrieving-single-models
So
$data['result'] = Rooms::find($request->id);
return a single model not collection of models.
You should change your code in view:rooms/rooms_detail
//#foreach($result as $row) => remove foreach
<div class="hero-text">{{ $result->name }}</div>
//#endforeach

I think you don't need to loop it. since you are using find function. Just call it directly on your view
<div class="hero-text">{{ $result->name }}</div>
find function will give you the Model if it find something or it will return null
or if you want change you eloquent query.
$data['result'] = Rooms::where('id', $request->id)->get();

I would return the data like this in your controller:
return response()->view('rooms.rooms_detail', [
$result => $data['result'],
$roomID => $data['room_id']
]);
It's the recommended correct way to return responses https://laravel.com/docs/5.8/responses
And then in your blade:
<div class="hero-text">{{ $result->name }}</div>

You don't need to convert collection to array since you are using eloquents find method which will return a collection not an array
You can simply use the below code
public function rooms_detail(Request $request)
{
$room_id = $request->id;
$data = Rooms::find($request->id);
echo $data['result'];
return view('rooms.rooms_detail', $data);
}
and then in your view
<div class="hero-text">{{ $data->name }}</div>

public function rooms_detail(Request $request)
{
$room = Rooms::find($request->id);
return view('rooms.rooms_detail')->with('room',$room);
}
At View data page
<div class="hero-text">{{ $room->name }}</div>
you are fetching only one data so do not need to loop

Related

Laravel- How to "catch" a variable with Javascript passed to a blade.php view

so i'm currently working on a project and i want to add a calendar to one view, i'm using FullCalendar, the calendar is shown in the view but i'm currently trying to add events to that calendar, those events are going to be "pulled" from my database into the calendar to be displayed, now the problem is that when i pass the array with the events to the blade.php view that contains the calendar a error comes up saying that the variable "events" is undefined and i don't know if i'm doing something wrong, here's the code:
RegisteredUserController.php
$events = array();
$citas = Cita::all();
foreach($citas as $cita){
$events[] = [
'title' => $cita->paciente_id,
'start' => $cita->hora_de_inicio,
'end' => $cita->hora_de_finalizacion
];
}
return redirect(RouteServiceProvider::HOME)->with(['events' => $events]);
RouteServiceProvider.php
public const HOME = '/home';
homeView.blade.php (This is where i get the error, in the line where i assign it to citas)
<div id="calendar">
</div>
<script>
$(document).ready(function(){
var citas = #json($events);
$('#calendar').fullCalendar({
header: {
left: 'month, agendaWeek, agendaDay',
},
events: citas
})
});
</script>
routes / web.php
Route::get('/home', function (){
return view('homeView');
})->name('homeView');
Not sure if it's helpful but i'm using Laravel's Breeze to handle the authentication of users, so when an user is aunthenticated they're redirected to the page where the calendar is.
i've tried the following
RegisteredUserController.php
return redirect(RouteServiceProvider::HOME, compact('events));
This one makes the whole calendar disappear:
homeView.blade.php
var citas = {{ Session::get('events') }};
Thank you in advance.
the return should be like this
return view('path_of_the_blade', compact('events'));
So then in View, you can use
<script>
var citas = #json($events);
</script>
On you controller, why don't you just simply use:
return view('homeView')->with(['events' => $events]);
or simplier:
return view('homeView', compact('events'));
This would surely pass the variable events on the blade file.
Then on your blade file, you will just reference it as:
var citas = {{ $events }};

Filtration data by category in Laravel

Index Controller
public function index()
{
$blogs = Blog::all();
$categories = Category:all();
return view('blog', compact('blogs', 'categories'));
}
We have something like the following code on the blog page. First we get all the available categories, then a list of all blogs.
#extends('layouts.app')
#section('content')
<div class="container">
<div class="category-filter" id="filter">
<div class="category-filter_item active">All</div>
#foreach($categories as $category)
<div class="category-filter_item">{{ $category->title }}</div>
#endforeach
</div>
#foreach($blogs as $blog)
<div class="blog-list {{ $blog->category_id}}">
<h2 class="blog_title">{{ $blog->title }}</h2>
</div>
#endforeach
</div>
#endsection
Can you please help to suggest a filtering function that, when choosing a specific category, will pull up all blogs from this category by ID?
JavaScript
document.querySelectorAll('.category-filter_item').forEach(el => {
el.addEventListener('click', () => {
document
.querySelector('.category-filter_item.active')
.classList.remove('active');
el.classList.add('active');
You could use ajax in your case by sending an ajax request to your backend and you handle the data, then you return a response, this an example of a function in controller.
public function ajaxResponse(Request $request){
if ($request->ajax()) {
$cat_id = $request->input('cat');
$blogs = Blog::query();
if ($cat_id != null) {
$blogs->whereHas("categories", function ($query) use ($cat_id) {
$query->whereIn('category_id', explode(',', $cat_id));
})->get();
}
$blogs = $blogs->get();
$blog = view('articles.ajaxblogs', ['blogs' => $blogs])->render();
}
return response()->json(['blog' => $blog]);
}
Make sure to include category id in request.

How can I succssefully acces an Global Variable from PHP in HTML

Pre Info:
In the PHP I declare a global array ($GLOBALS[]), in it I stow the data for the blade.
On the Blade i have a dropdown. If the dropdown changes, i send via AJAX the value to the Controller.
With the new data i calculate the new information, i want to show on the Blade.
But when I try to get the data in HTML like {{$GLOBALS['MyNumber']}} I only get the initialization value.
<?php
.
.
.
$GLOBALS = array(
'MyNumber' => 1,
'companyCode' => 0
);
class MyClass extends Controller
{
public function getData(){
$GLOBALS['companyCode'] = #$_POST['companyCode'];
if ($GLOBALS['companyCode'] == 902){
$GLOBALS['MyNumber'] = 100; //for the example, I set the data fix
}else{
$GLOBALS['MyNumber'] = 20; //for the example, I set the data fix
}
return response()->json(array('AJAX succses' => $response), 200);
}
.
.
.
In HTML i wanna show an dashboard-card with the new data like this:
I have 4 Cards and 7 Tables with data from SQL.
#section('page_content')
<div class="card #if($GLOBALS['MyNumber'] >95) dashboard-card-success #else card-anger-#endif" id="bkfI">
<div class="dashboard-title">
{{ __('bkf_usage') }} {{ today()->year }}
</div>
<div class="dashboard-content">
<div class="dashboard-number" id="bkf_usage">{{$GLOBALS['MyNumber'] }} %</div>
<div class="dashboard-description"></div>
</div>
</div>
But every time i reload the div (so the color can change) the $GLOBALS['MyNumber'] stays on the init of 1.
But the internal use (if $GLOBALS['companyCode']) works fine. How can i solve this issue? Or can you help me to find a work-around?
Maybe pass all the Vars back via ajax to JS and store tem in an JS variable? So i can still access from HTML to them?
Thank You!

how to load the content of a show method in laravel on the index method using jquery

i have two methods show and index
i have a list of items on the index method that when a user clicks it takes her to another page containing some data that belongs to that id. instead of doing it such way i want to use jquery to achieve this, to make the data load on the same page. i have the following on my index.blade.php view, please how do i achieve this in laravel
#foreach ($categories as $category)
<div class="body">
<h4><a style="text-decoration: none; " href="{{ URL::route('category.show', $category->id) }}">{{$category->name}}</a></h4>
</div>
#endforeach
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use illuminate\HttpResponse;
use App\Http\Requests\todolistRequest;
use App\Http\Requests\CreateCategoryRequest;
use App\Http\Requests;
use App\Companylist;
use App\Category;
use Illuminate\Support\Facades\DB;
class CategoryController extends Controller
{
public function create(){
return view('category.create');
}
public function index(){
$categories=Category::all();
return view('category.index',compact('categories'));
}
public function store(CreateCategoryRequest $request){
$category = new Category($request->all());
$category->save();
return \Redirect::route('category.create')->with('message', 'Your list has been created!');
}
public function show($id)
{
$category = Category::findOrFail($id)->companylist()->get();
$cat=Category::findOrFail($id);
// this my route
Route::resource('category','CategoryController');
return view('category.show')->with('category', $category)->with('cat',$cat);
}
//
}
To show details data on index page without page refreshing , you should use ajax , in ajax return data and show it in index page ( i.e. under each list )
In ajax you have to pass the id and depending on id return corresponding data.
Hope it helps

Angulrjs: A controller doesn't send a value via a factory with the "as" statement

I've been teaching myself how to use the as statement of Angularjs's controller, but struggling to make controllers communicate with others, using the as syntax.
<script type="text/javascript">
angular.module('angularApp', [])
.factory('MessageService', function(){
var message = {
addedItem: "initialMessge"
};
return {
returnMessage: message//This is supposed to be the "var message" defined above
};
})
.controller('DiaplayingProductController', function(MessageService){
var instance = this;
this.data = {
message: MessageService.returnMessage.addedItem
};
})
.controller('ProductController', function($scope, $http, MessageService) {
var instance = this;
this.data = {
message: MessageService.message,
//There are other stuff here
};
this.addItem = function(productName) {
$http({
//other tasks
}).then(function addSucces(response) {
instance.data.message.addedItem = productName;
});
};
});
<span ng-controller="DiaplayingProductController as dpc" ng-bind="dpc.data.message"></span>
<div ng-controller="ProductController as pc">
#foreach ($products as $index => $product)
<div class="product">
<button ng-click="pc.addItem({{$product->name}})>
Add it to Cart
</button>
</div>
#endforeach
</div>
I use Laravel, so {{$product->name}} and #foreach are Laravel's expression.
In a nutshell,
There are one <span> and multiple <button>s, based on the result of #foreach (Again, I use Laravel, so this is basically the same thing as php's foreach)
When one of the <button> is pressed, the content of <span> is supposed to be updated.
The event is triggered in ProductController, which is supposed to update message of DiaplayingProductController, via MessageService.
The message is not going to be sent to the span tag.
This question may be silly. However, there are not many information resources out there which deal with this as statements, so I'd like to ask some advice here. Thank you in advance!
What's this #foreach?
There's a coma in your attributes. Shouldn't be there.
The expression in your ng-click has a missing parenthesis. Also, it should be an expression, therefore the {{}} have nothing to do here.
The data object are not shared between the controllers. You should:
use directives and pass the data using attributes ('=').
set the data in the $scope, which is not as good a solution
use a service as an intermediary (each controller can set/get the value
from that service)

Categories

Resources