this is a simple thing actually but since im new in laravel it trouble me, i have this function
class HomeController extends Controller {
public $layout = 'layouts.master';
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('landing-page')
->with('title','Landing Page')
->with('users',User::member()->get());
}
<!-- HOW TO CALL getDate Function in my view -->
public function getDate(){
$mytime = Carbon::now()->format('f');
$response = array
(
'content' =>$mytime,
'status' =>'success',
);
return Response::json($response)->view('landing-page');
}
}
how to call it in my laravel view? i search all over the internet but i not quite understand since programming is new for me i already tried something like this in my view using routes {{url('date')}}, {{$mytime}}, but none working, well i can call a function if there's certain event happen like clicking button or else but if no certain event it's quite confusing me
<p>Month :{{url('date')}}</p>
<p>Month :{{$mytime()}}</P>
above are some ways i tried to call the function
UPDATE WHAT I'VE TRIED BASED on #tptcat answer and work
create helpers.phplocated under files `app\helpers.php
<?php
use Carbon\Carbon;
if (! function_exists('myGetDate')) {
function myGetDate()
{
$mytime = Carbon::now()->format('F');
return $mytime
}
}
composer.json
"autoload": {
"files":[
"App/helpers.php"
],
calling function in my view
{{myGetDate()}}
This isn't a hard and fast rule, but part of using a framework is to somewhat buy into its conventions and use them to your advantages.
Generally speaking, your Controllers are for working with HTTP (GET, POST, PUT, etc.). They're not designed to be indiscriminate ways to call methods from your Views.
I would recommend doing something like this instead:
// app/Utilities.php
<?php
class Utilities
{
public static function getDate()
{
// your code
}
}
then in your view:
{{ Utilities::getDate() }}
or:
// app/helpers.php
<?php
if (! function_exists('myGetDate')) {
function myGetDate()
{
// your code
}
}
then in your view:
{{ myGetDate() }}
and then in composer.json autoload whichever file you create:
"autoload": {
"files": [
"app/Utilities.php"
]
}
or...
"autoload": {
"files": [
"app/helpers.php"
]
}
and then run composer dump-autoload.
Another way to approach this could be using Blade Service Injection (introduced in Laravel 5.1). This technically can be done with your controller:
// In your blade template
#inject('service', 'App\Http\Controllers\HomeController')
{{ $service->getDate() }}
But I'd still recommend not having a method in your controller in charge of returning this data if it's going to be called as a method from a Blade template. Using some type of service class would be more appropriate:
// app/Utilities.php
<?php
namespace App;
class Utilities
{
public function getDate()
{
// your code
}
}
// In your blade template
#inject('service', 'App\Utilities')
{{ $service->getDate() }}
and in this case you wouldn't need to add it to the files autoload array in composer.json.
For what it's worth, not knowing anything else about your project, I would choose one of the first two options, and more likely the helpers.php option.
Try this:
class HomeController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$title = 'Landing Page';
$users = \User::member() - > get();
$mytime = \Carbon::now()->format('f');
return view('layouts.master.landing-page', [
'title' => $title,
'users' => $users,
'mytime' => $mytime
]
);
}
}
And to display it within the landing-page view you would access them with:
{{ $title }}
{{ $users }}
{{ $mytime }}
Related
I want to load up the view then update the variable data to stop the page taking ages to load (lots of data to load up). Is this possible with Laravel livewire?
I'm trying to get livewire to render the view and then update the public variables after the page has been loaded. In my case, I'll be getting data from an api so I want the user to see the page and then I can add some loading spinners whilst fetching the data.
However, from my test and looking at the livewire lifecycle my test variable doesn't update.
Example Livewire Controller
class Example extends Component
{
public $test;
public function mount()
{
$this->test = 'hi';
}
public function render()
{
return view('livewire.example');
}
public function hydrate()
{
$this->test = 'TEST1';
}
public function hydrateTest()
{
$this->test = 'TEST2';
}
public function dehydrate()
{
$this->test = 'TEST3';
}
}
Example Livewire Blade
<div>
<p>Hello World</p>
<p>{{ $test }}</p>
</div>
The lifecycle hooks said that dehydrate runs after render(), which means $test should = 'TEST3
but it stays as 'hi', my initial state.
There seems to be javascript hooks as well, like when the component has been initalised. But I'm not sure how to call the livewire functions or variables from there.
Does anyone know how to update livewire variables after the view has been rendered?
You could initialize the data after the page has rendered for the first time, though the wire:init directive.
Your blade would look something like
<div wire:init="loadData">
<p>Hello World</p>
<p>{{ $test }}</p>
</div>
And you component would have a method loadData(), where you do your calls to the API.
class Example extends Component
{
public $test;
public function mount()
{
$this->test = 'hi';
}
public function loadData()
{
$this->test = 'Data loaded';
}
public function render()
{
return view('livewire.example');
}
}
See the official documentation on deferred loading for more examples.
Thanks For Reading.
I'm new in Laravel, i want to try to change the output of Database with #foreach blade, there is the example :
This is Route :
Route::get('/home', 'warnajati#index');
This is Controller :
public function index()
{
$post = DB::table('posts')->get();
return view('warnajati', ['posts'=>$post]);
}
This is Views :
#foreach ($posts as $post)
<div class="title"><h3>{{$post->title}}</h3></div>
#endforeach
with Output of $post->title is "This is The Looonger Title you ever know" ,
and i want to make the title is shorter with Wordlimit() function i have made :
function wordlimit($text, $limit=10)
{
if (strlen($text)>$limit) {
# code...
$word = mb_substr($text,0,$limit-3)."...";
}else{
$word =$text;
}
};
How and Where i must place that function in laravel Project ?? please help me..
Your function has no return value... Laravel already has this function: http://laravel.com/docs/5.3/helpers#method-str-limit
#foreach ($posts as $post)
<div class="title"><h3>{{ str_limit($post->title, 10) }}</h3></div>
#endforeach
You can use Laravel's Accessor for doing that like this inside a Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function getShortTitleAttribute($value)
{
// return shortened title here ...
}
}
and then you can use it in blade like this:
{{ $post->short_title }}
Hope this helps!
You can put your function in helpers.php file from libraries folder.
Just make sure that you have helpers.php file autoloaded in composer.json file:
"autoload": {
"files": [
"libraries/helpers.php"
],
},
If you had to add this to your composer.json you will also have to run composer dump-autoload command from terminal.
For more info check out Best practices for custom helpers on Laravel 5.
I want to define some methods which can be used in multiple place or multiple controllers. Basically these methods will be like libraries which will perform multiple queries.
My main aim is to avoid writing common logic multiple times by creating some libraries.
Please help me with it.
Thanks in advance :)
Depends what are you trying to do. Here are some options:
By default all your controllers extend App\Http\Controllers\Controller class. Just put all the shared logic between controllers there.
For complex queries to the database you can create a Repository and and inject in the controllers.
class UserRepository {
public function getActiveUsers() {
return Users::with('role')
->where('...')
->someQueryScopes()
->anotherQueryScope()
->yetAnotherScope();
}
}
class SomeController extends Controller {
public function index(UserRepository $repository) {
$users = $repository->getActiveUsers();
return view('users.index')->withUsers($users);
}
}
Yet another option is to create a Service classes for business logic and inject them in the constructor or relevant methods
class UserCreatorService {
public function create($email, $password){
$user = User::create(['email' => $email, 'password' => $password]);
$user->addRole('Subscriber');
Event::fire(new UserWasCreated($user));
return $user;
}
}
class RegisterController extends Controller {
public function store(Request $request, UserCreatorService $service) {
$user = $service->create($request->input('email'), $request->input('password'));
return view('home')->withUser($user);
}
}
it's simple, build your own library in your app folder then create new file MyLibrary.php
namespace App;
Class MyLibrary {
public static function sum($a, $b) {
return $a + $b;
}
}
then create alias in your config/app.php
'MyLibrary' => App\MyLibrary::class,
and finally you can call it in anywhere your controller
$result = MyLibrary::sum(4, 5); // your $result now have value of 9
You can make a folder named lib and inside that a functions.php file and in composer.json
...
"autoload": {
"files": [
"app/lib/functions.php"
],
...
and run composer dump-autoload
Use helper classes and create common functions in them.
Create a folder named helper in app folder and create a helper class in it. And then use that helper class's function in multiple controller or views as you want.
I have a problem with helpers , I create correctly the helper and I can call this helper that I created in view but when I need to access to property.
{{Text::showBanner()}};
The function of helperI created called showBanner
public static function showBanner() {
$banner= Banner::all();
return $banner;
}
How can I access to attribute id of $banner ?
UPDATED
When I use this
#foreach ( $banners as $item)
{{$item}}
#endforeach
I need to change this $banner for this helper
create a file app/helpers.php with your desired code:
function showBanner() {
$banner = Banner::all();
return $banner;
}
Autoload it with composer
{
"autoload": {
"files": [
"app/helpers.php"
]
}
}
use it {{ showBanner() }}
I have Laravel's built in auth working. Users can register and login.
What I'd like to do is set the $id parameter for the UserController's show() method with the value from Auth::user()->id;
My thoughts behind this is, to not have to use id's in the routes.
I'm pretty new to OOP, and php in general, so I'm not sure how to tackle this.
Thanks in advance for any tips or help!
1st method
You can have a route with an optional user id:
Route::get('user/show/{id?}', 'UsersController#show')
If the show method of your controller doesn't get an id, it can use Auth::user() instead:
class UsersController extends BaseController {
public function show($id = null)
{
return View::make('userProfile')->with('user', $this->getCurrentUser($id));
}
public function getCurrentUser($id)
{
$this->currentUser = $id ? User::find($id) : Auth::user();
}
}
Then in your view you will be able to always
{{ $user->name }}
2nd method
You could also have a BaseController which does that automatically for you using View::share():
class BaseController extends Controller {
public function __construct()
{
parent::__construct();
$this->shareUser();
}
public function shareUser($id = null)
{
View::share('user', $id ? User::find($id) : Auth::user());
}
}
Then in your controller you don't need to pass the user:
class UsersController extends BaseController {
public function show()
{
return View::make('userProfile');
}
public function thisIsAMethodOverridingIt($id)
{
$this->shareUser($id);
return View::make('userProfile');
}
}
It would even better to have this provided by a Service, but you'll have to read about Service Providers and Facades to make it happen.
And you are still able to do that:
{{ $user->name }}
Because View::share() will send that variable to all your views.
3rd method
If you just need your user everywhere, use a global View::composer():
View::composer('*', function($view)
{
$view->with('currentUserName', Auth::check() ? Auth::user()->firstname : '');
});
You can put this in your routes.php or, better create a file for this purpose, something like app/composers.php and load it in your app/start/global.php:
require app_path().'/composers.php';
As always, you can use it in your view, this way:
{{ $user->currentUserName }}
If you just need it for a couple of views, you can
View::composer(array('profile','dashboard'), function($view)
{
$view->with('currentUserName', Auth::check() ? Auth::user()->firstname : '');
});
This is actually a recent problem that I encountered while working on an API.
The way I handled it, was to introduce /me endpoints, so for example, you'd have:
Route::group(['before' => 'auth'], function() {
Route::get('/user/show/{id}', 'UsersController#show');
Route::get('/me', 'UsersController#show');
}
You'll notice that both routes point to the same code, but have different addresses. This means that you can simplify requests by using the /me convention, without having to duplicate code. You'll also notice that I enclosed these in a group which applies the auth filter. This basically just makes sure that the user is authed, and while it may not be required for the first one, it'd definitely be required for the second.
Then your show method would look like this:
public function show($id = false)
{
$user = $this->getUserOrMe($id);
return View::make('myview', ['user' => $user]);
}
This would require the below function:
private function getUserOrme($id)
{
return $id !== false ? User::find($id) : Auth::user();
}
A controllers methods should be accessed independently of each other, meaning that once the User object is returned, all the relevant code for the current request has access to it. Storing the User object in a class property would just over engineering.
Hope that helps.