Get data from database and display to blade template in laravel - php

I have a problem when I learning laravel. My views include master.blade.php and top.blade.php file.
In master.blade.php, I used #include('top') command to get content show UI. But now I don't know how to get and passing database to top.blade.php. I was used direct App\Article; to do this. can anyone help me? thanks.
Master.blade.php file
#include('top')
Top.blade.php file
<?php
use App\Article;
$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
?>
#foreach ($articles as $a)
{{ $a->title }}
#endforeach

You could do this:
<?php
$articles = \App\Article::orderBy(DB::raw('RAND()'))->take(1)->get();
?>
But it's better to keep data logic in a model or a controller and pass it to the views.

Juste use a Controller to pass database data in to your view, it should be
ArticlesController.php
$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
return view('master', compact('articles');
It's just an example, but now top.blade.php which is included in master, will contain $articles.

Related

Is it possible to create Laravel Blade tags that can access Controller actions?

I want to create a Blade tag which can output data like Posts.
At the moment I'm using a PageController which returns the show.blade.php view.
In this view are some self created Elements (Text, Images, ...) and now I have a Bloglist Element. For the reason that I'm already using a Controller and Route, I want to create a Blade Directive which can handle this.
For example:
#BlogList('$filter')
//foreach with $posts
#endBlogList
Between this tags should be a $posts variable available, which is returned by the BlogController. The $filter is also for the BlogController to filter the Posts.
try this:
#foreach($posts as $post)
<li>{{$post->title}}</li>
#endforeach
this assumes your controller is sending $posts to your view.
good luck!

How to Create Dynamic Menu bar in Laravel using Database

initially, I created the static navigation bar but now I want to improve navigation bar as Dynamically.
in there im try function inside the Controller but it was not success because that view manage only one route.i need to that view in every pages of my web.
SideMenuController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\admins;
use DB;
class SideMenuController extends Controller {
public function index(){
$details = DB::SELECT("SELECT Name FROM admins");
return view('layout', compact('details'));
}
}
web.php:
Route::get('/user/test','SideMenuController#index');
test.blade.php :
Order
#foreach($details as $value)
{{ $value->Name }}
#endforeach
Error Exception
(3/3) ErrorException Undefined variable: details (View:
C:\xampp\htdocs\ERP\ERP_LAR\resources\views\test.blade.php) (View:
C:\xampp\htdocs\ERP\ERP_LAR\resources\views\test.blade.php)
For first take a look at the blade engine that is in Laravel.
The idea is that you will create a value in an controller and past this to the view. Here you will extract the value and place the right value to the right place. With blade you can even make a separate navigation.php and yield them in every view you need it.
There are many ways to solve the problem.
You can make a separate php file in your project like "navbar.php" and include it in by <?php include('navbar.php'); ?>
you can also use classes but it is harder.

How do I use a controller for a "partial" view in Laravel?

Here is my situation. I have a layout.blade.php which most of my pages use. Within this file, I have some partial pieces that I include, like #include('partials.header'). I am trying to use a controller to send data to my header.blade.php file, but I'm confused as to exactly how this will work since it is included in every view that extends layout.blade.php.
What I am trying to do is retrieve a record in my database of any Game that has a date of today's date, if it exists, and display the details using blade within the header.
How can I make this work?
I think to define those Game as globally shared is way to go.
In your AppServiceProvider boot method
public function boot()
{
view()->composer('partials.header', function ($view) {
view()->share('todayGames', \App\Game::whereDay('created_at', date('d')->get());
});
// or event view()->composer('*', Closure) to share $todayGames accross whole blade
}
Render your blade as usual, partial.header blade
#foreach ($todayGames as $game)
// dostuffs
#endforeach
In Laravel you can create a service class method that acts like a controller and use #inject directive to access this in your partial view. This means you do not need to create global variables in boot(), or pass variables into every controller, or pass through the base view layout.blade.php.
resources/views/header.blade.php:
#inject('gamesToday', 'App\Services\GamesTodayService')
#foreach ($gamesToday->getTodayGames() as $game)
// display game details
#endforeach
While it's different value you retrieved belong of the game chosen, you can do something like that:
Controller
$data = Game::select('id', 'name', 'published_date')->first();
return view('game')->with(compact('data'));
layout.blade.php
<html><head></head><body>
{{ $date }}
</body></html>
game.blade.php
#extend('layout')
#section('date', $data->date)
#section('content')
#endsection
The better solution would be this
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))

How to access cookie from view in PHP Laravel 5

I can access cookie in controller then pass it to view
//HomeController.php
public function index(Request $request)
{
$name = Cookie::get('name');
return view('index', ['name'=> $name]);
}
But I want to write a small control (widget) that can fetch data from cookie without concern of parent controller. For example, header, footer widgets could fetch its own data without main page controller knowing which data is needed.
I can query the data from database by using View Composer. But, how can I access data from view in the request cookie ?
Using static function with defining namespace and etc is a not safe.
Cuz maybe in next versions of framework this namespace can change.
It's better to use helper functions.
{{ request()->cookie('laravel_session') }}
or
{{ cookie('laravel_session') }}
Tested on working app with Laravel 5.2
You can use {{ Cookie::get('laravel_session') }} to print out the cookie inside your view.
You can use
{{\Illuminate\Support\Facades\Cookie::get('laravel_session')}}
in a blade template
You can use:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expire));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expire);
return view('your_view');
I've used both of them.

Laravel - rendering inside layout (from controller or ...?)

I have setup a general layout for all my views - all fine.
Now, I would like to get some information from database to put in the header, which is part of the layout.
At the moment, the only way I can find out is something like:
// OneControler.php
static public function hello()
{
$data['hey'] = 'heeey';
return View::make('layouts.partial.nav', $data);
}
And from inside the layout:
// master.blade.php
...
{{ OneController::hello() }}
...
This works fine but... I think there must be another way? I don't think loading a controller from inside the view/layout is the best way to do this?
You can use View Composers to help you with this:
View::composer(array('your.first.view','your.second.view'), function($view)
{
$view->with('count', User::count());
});
Then in your view your.first.view or your.second.view, or even your layout you can just:
{{ $count }}
In the array of views, you put the name of the view:
View::composer(array('layouts.partial.nav') ...
or you can just set it to all views:
View::composer(array('*') ...
If you want to define a variable for all views you can also use share:
View::share('name', 'Steve');
In your view or layout:
{{ $name }}

Categories