I'm working on yii old version i need to write model function in view file this file is html format i don't know how to call model function. I need to send this value {{ $model->customers_charge->shop_id }} to model function
My code is :
{{foreach $models model}}
<tr>
<td>{{date('M/d/Y H:i', strtotime($model.created))}}</td>
<td>{{if $model->deposit>0}}{{$model->deposit}}{{/if}}</td>
<td>{{if $model->deposit<0}}{{$model->deposit*-1}}{{/if}}</td>
<td>
{{if $model->memo eq Order}}
Shopping Order
{{else}}
{{$model->memo|ucwords}}
{{/if}}
</td>
</tr>
{{/foreach}}
How to get model function in Yii framework.can any one kindly guide me. I'm looking forward your valuable reply.
Can't you just do this ?
YourModelName::model()->YourFunction($arg1,$arg2);
Or
$model = new YourModelName();
$model->YourFunction($arg1,$arg2);
Or I'm missing something?
Related
First, i have the component file, located at resources/views/component.
game-card.blade.php
#props(['game'])
<div class = 'games'>
<a href = 'game/{{$game->id}}'> view page </a>
<p> game: {{$game->name}} </p> <br>
<p> genre: {{$game->genre}} </p> <br>
</div>
Then this component is called at my view, located in resources/views
listing.blade.php
#extends('layout')
#section('list')
<div class = 'listContainer'>
#unless(count($games) === 0)
#foreach($games as $game)
//doesn't work
<x-game-card :game = "$game"/>
#endforeach
#else
<p> 0 Games </p>
#endunless
</div>
#endsection
The variable $game is not passed in the component <x-game-card/>, i even tried to use short atribute syntax (<x-game-card :$game/>) but it still doesn't work.
If it matters, the file listing.blade.php is yielded at the file layout.blade.php, located in the same folder.
layout.blade.php
<body>
<!-- Header -->
#yield('list')
#yield('singlegame')
#include('partials._footer')
For any prop that you want to pass to your component, you need to register it on the component class. In this case, the class is probably app/View/Components/GameCard.php
On the class, you need to do something like:
class GameCard extends Component
{
public $game;
public function __construct($game)
{
$this->game = $game;
}
Source: https://laravel.com/docs/9.x/blade#passing-data-to-components
i found the root of the problem. I just can't believe that the solution is so simple. I am going to post it here so less people make the same mistake i did
First, create the class (i personally use the command php artisan make:component to do that) and update it just like Nico did.
Second, when you put the <x-component in the HTML, MAKE SURE TO NOT LEAVE ANY SPACES IN THE VARIABLE!!!
my mistake was using <x-game-card :game = "$game"/>
instead of <x-game-card :game="$game"/>
You may find me stupid but i am unable to understand on what basics we give url and name in our route file
Example:
Route::get('/order/getOrders', 'OrderController#getOrders')-
>name('order.getOrders')->middleware('auth');
can anyone please tell me.
and if we take url on the basics of where our file in view folder like( order->getorder blade file)
Then what if my path is layouts.site.topbar
In view instead of pages, my file is in layouts.
EDIT:
blade file
<a href="{{ route('sync.index') }}">
#if(isset($syncs))
#foreach ($syncs as $sync)
#endforeach
{{ $sync->session_date }}
#endif
</a>
controller file
class TopbarController extends Controller
{
public function index()
{ die('o');
$syncNames = Sync::select('session_date','session_time')->where('user_id',$user_id)->get();
return view('layouts.site.topbar', array(
'syncs' =>$syncNames
));
}
public function sync_finish_session() {
die('s');
$user_id = Auth::id();
$sync_date = date('M d ',strtotime("now"));
$sync_time = date('M d, Y H:i:s',strtotime("now"));
$sync = Sync::where('user_id',$user_id)->get();
if(count( $sync) > 0) {
Sync::where('user_id',$user_id)->update(['session_date'=>$sync_date,'session_time'=>$sync_time,'user_id'=>$user_id]);
}
else {
$dates = new Sync();
$dates->session_date = $sync_date;
$dates->session_time = $sync_time;
$dates->user_id = $user_id;
$dates->save();
}
return $sync;
}
}
web file
Route::post('/sync_finish_session', 'TopbarController#sync_finish_session')->name('sync_finish_session')->middleware('auth');
Route::get('/sync/index', 'TopbarController#index')->name('sync.index')->middleware('auth');
Now whats the problem its giving nothing even i put die but its not going in controller file.
I think this is more a personal preference thing than that there are rules.
The convention I use is name(<model>.<action>)
This way i can create routes like
Route::get('/users/{id}/view', 'UserController#view')->name('users.specific.view')->middleware('auth');
You just name route as you do want. There is no strict rules how to name route. You can change name('order.getOrders') to name("anyName") and use new name in templates.
As the Laravel documentaton about rounting says:
Named routes allow the convenient generation of URLs or redirects for specific routes.
So, you can use this name to generate URLs or redirects. For example:
You could put this in your web.php file:
Route::get('/image/index', 'API\SettingsController#index')->name('image.index');
And call that route like this in your view:
Le met see that index!
Where the {{ route('image.index') }} references the name you gave to it.
You can name your route(s) anything you want. If you wanted, you could call your above route "mySuperCoolRouteName":
Route::get('/order/getOrders', 'OrderController#getOrders')-
>name('mySuperCoolRouteName')->middleware('auth');
and later in a view file you can use this name as a "shorthand" to get/print the URL of that route:
To My Cool Route
will be rendered to
To My Cool Route
I have a simple controller function that fetch all records from db. but when i am trying to show all these records it show nothing. In fact it shows me hard coded foreach loop like this.
#foreach ($compactData as $value) {{ $value->Name }} #endforeach
this is my contoller function.
public function showallProducts()
{
$productstock = Product::all()->stocks;
$productoldprice = Product::all()->OldPrices;
$productcurrentprice = Product::all()->CurrentPrice;
$compactData=array('productstock', 'productoldprice', 'productcurrentprice');
return view('welcome', compact($compactData));
}
this is my view
<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Laravel
</div>
<div class="title m-b-md">
All products
</div>
<table>
<tbody>
#foreach ($compactData as $value)
{{ $value->Name }}
#endforeach
</tbody>
</table>
</div>
</div>
</body>
why it is behaving like this. any solution?? I am using phpstorm version 17. Is their any setting issue to run project because what ever project I ran it gives me the only page which i ran with only html?
My route is.
Route::get('/', function () {
$action = 'showallProducts';
return App::make('ProductController')->$action();
});
Have you checked your $compactData variable? Please dd($compactData) to see what it contains.
Problem 1
You are accessing a relational property as a property of Eloquent collection, like this:
Product::all()->stocks
which is not correct. Because the Collection object doesn't have the property stocks but yes the Product object might have a stocks property. Please read the Laravel documentation about Collection.
Problem 2
$compactData = array('productstock', 'productoldprice', 'productcurrentprice');
This line creating an array of 4 string, plain string not variable. So, your $compactData is containing an array of 4 string. If you want to have a variable with associative array then you need to do the following:
$compactData = compact('productstock', 'productoldprice', 'productcurrentprice');
Problem 3
return view('welcome', compact($compactData));
Here you are trying to pass the $compactDate to the welcome view but unfortunately compact() function doesn't accept variable but the string name of that variable as I have written in Problem 2. So, it should be:
return view('welcome', compact('compactData'));
Problem 4
Finally, in the blade you are accessing each element of the $compactData data variable and print them as string which might be an object.
You most likely have a problem with your web server.
Try to use Laravel Valet as development environnement.
Edit : I found this : Valet for Windows
I think you didn't mention the blade in the name of the view file by which it is saved. So change the name of the file by which it is save to something like:
filename.blade.php
and try again.
Explanation:
#foreach ($compactData as $value) this is the syntax of blade template engine, and to parse and excute it, you have to mention the blade extension in the name.
I have a page system in Laravel - where I pass data from controller to view.
$this->data['title'] = $row->title;
$this->data['breadcrumb'] = $row->bc;
Now I passed it as follows:
return View::make('Themes.Page', $this->data);
In the view file, I access the data as follows:
{{$breadcrumb}}
What I am trying to do now is to pass this data in nested views:
$this->layout->nest('content',$page, $this->data);
(Content is the {{content}} in the view which will be replaced with $page contents. I want to pass the $this->data just as before but now I get an error:
Variable breadcrumb not defined.
Note: Laravel Version 4.2 $this->layout is set in constructor to a
template file (Themes.Page)
Actually you don't need to pass any separate data to your partial page(breadcrumb)
controller page
$this->data['title'] = $row->title;
$this->data['breadcrumb'] = $row->bc;
return View::make('idea.show',array("data"=>$this->data));
main view page
<div>
<h1>here you can print data passed from controller {{$data['title']}}</h1>
#include('partials.breadcrumb')
</div>
your partial file
<div>
<h1>here also you can print data passed from controller {{$data['title']}}</h1>
<ul>
<li>....<li>
<li>....<li>
</ul>
</div>
for more information on this you can check following links http://laravel-recipes.com/recipes/90/including-a-blade-template-within-another-template or watch this video https://laracasts.com/series/laravel-5-fundamentals/episodes/13
You should pass data as follows
return View::make('Themes.Page')->with(array(
'data'=>$this->data));
or (since you're passing only 1 variable)
return View::make('Themes.Page')->with('data', $this->data);
and further you can pass it on to nested views as by referencing $data
$dataForNestedView = ['breadcrumb' => $row->bc];
return View::make('Themes.Page', $this->data)->nest('content', 'page.content', $dataForNestedView);
In the Themes.Page view render nested view:
<div>
{{ $content }} <!-- There will be nested view -->
</div>
And in the nested page.content view you can call:
<div>
{{ $breadcrumb }}
</div>
*div tag is only for better understanding.
Okay, after intense search, I figured out that there was a bug in the Laravel version 4.2 I was using.
Laravel 5 works.
For laravel 4.2, a better option would be to pass array of data objects using View::share('data',$objectarray) while passing the data from controller.
Thanks everyone for help
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.