How to Create Dynamic Menu bar in Laravel using Database - php

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.

Related

Diaplay data from MySQL to sub folder views in Laravel 9

I have created pages in view directory as views/mech/class
I want to display database data to 'views/mech/class.blade.php' page and using controller App/Controllers/mechplace.php
App/Controllers/mechplace.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Placements;
class mechplace extends Controller
{
public function rating1()
{
$users = "ram";
return view('mech.class')->with('users', $users);
}
}
views/mech/class.blade.php
{{$users}}
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\mechplace;
// Route::get('mech.mechanical-engineering-placement', 'mechplacement#rating1');
// Route::get('skills-development',[App\Http\Controllers\deptPlacements::class,'rating1']);
// Route::resource('skills-development', deptPlacements::class);
// Route::get('mech.mechanical-engineering-placement',App\Http\Controllers\deptPlacements#rating1');
Route::get('mech.class-dept', 'App\Http\Controllers\mechplace#rating1');
But I am getting error on /mech/class page in my website
Undefined variable $users
How to display the MysSQL database content to sub folders in under views folders ?
It's with pages under views folder but not working for sub folders in views in Laravel 9
I have taken out index and .htaccess from public folder and website is working from laravel main directory for eg . localhost/name/public to localhost/name/
I have given routing as mech/class-dept.php in web.php :
Route::get('mech/class-dept.php',function(){
return view('mech/class-dept');})->name('class');
URL will be localhost/mech/class-dept.php
First thing first , see your route, I think you call a wrong controller.
before
Route::get('mech.class', 'App\Http\Controllers\deptPlacements#rating1');
after
Route::get('mech.class', [App\Http\Controllers\ mechplacements::class, 'rating1');
And than inside your controller.
public function rating1()
{
// you can put what ever query here
$users = User::where('status', true)->get();
return view('mech.class')->with('users', $users);
}
note you can also use compact()
return view('mech.class', compact('users'));
And inside your views/mech/class.blade.php
#foreach ($users as $user)
<p>{{ $user->name }}</p>
#endforeach
You can do display how you want.
Some notes:
First related to Controller naming convention, best to follow this standard = https://webdevetc.com/blog/laravel-naming-conventions/#section_naming-controllers
So you might consider to write your controller file name to MechPlacementController
And call it like this inside routes/web.php = App\Http\Controllers\ MechPlacementController::class
Another thing to point out
You have to differentiate between route path and route name.
Do you really mean to this page is accessible from http://localhost:8000/mech.class ?
Probably better if you use "-" sign or "/" , for example
Route::get('mech/class', 'App\Http\Controllers\deptPlacements#rating1')->name('mech.class');
Than you can access this path in http://localhost:8000/mech/class.
And if you want to use some where inside blade , you can use route('mech.class') which will generate route path /mech/class.

Random images in laravel

I have a database table called random_img. Inside are 10 rows for 10 images.
I will be pulling the images from public/images/random
I want to use the database so I can set the loop to Random take(1). I want to use in my hero images. (New image on every page refresh)
Where would I put my database query so I can use it Globally? Or how can I use my RandomImgsController so it is being used globally?
I created a route file, so I can use it as an include where needed.
Route:
Route::post('/layouts/inc/random-img','RandomImgsController#randomimg')->name('random-img');
Include:
#include('layouts.inc.random-img')
Inside Include:
#foreach ($randomimg as $rand)
<span class="hero-image">
<img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
</span>
#endforeach
RandomImgsController: (Where should this go so I can use globally)
public function randomimg()
{
$randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get();
return view('random-img',compact('randomimg'));
}}
This is what I want to achieve on every page of my website:
#php
$randomimg = DB::table('randomimg')->orderBy(DB::raw('RAND()'))->get()->take(1);
#endphp
#foreach ($randomimg as $rand)
<span class="hero-image">
<img src="/images/random/{{$rand->file_name}}" class="img--max--hero blur-img">
</span>
#endforeach
What would be a cleaner way to do this?
Update:
I can access the images DB in all views now, but I have an issue.
In my App\Http\ViewComposer\ImageComposer.php file I have this:
public function compose(View $view)
{
$view->with('foo', Image::inRandomOrder()->get()->take(1));
}
In any view I can use {{$foo}} to get a random row from my images table, but the data comes in a string like this:
[{"id":10,"alt":"Image Alt Tag","title":"Image Title","file_name":"10.jpg"}]
When I try to only grab individual columns like this {{$foo->file_name}}
I get the error:
Property [file_name] does not exist on this collection instance.
How can I grab individual columns like this: {{$foo->alt}} , {{$foo->title}} and {{$foo->file_name}} then cleanly output them in my view? Example, I need {{$foo->file_name}} to render like this: 5.jpg.
Update 2:
I figured it out. Have to use #foreach since I'm using the get() method.
#foreach($foo as $f)
{{$f->file_name}}
#endforeach
Would still like to know if there is a way to do it without the get() method. This will work though.
First of all you can't #include a route in a blade template. What you would actually do is send an AJAX request from your blade template to the route you created to retrieve the random images. However...
It sounds like a controller is the wrong place for the logic in this situation.
Assuming you have an associated Eloquent model for your table, a simple option could be to define a method on your RandomImage model (could probably just be called Image).
This way, you can just use your Image model to generate and pass a random image to any view you would like. Then there is also no need to query for every image on each page reload. You would only ever be querying for one image per request.
Imagine if the code in your view could look like this:
<span class="hero-image">
<img
src="{{ $image->url() }}"
class="img--max--hero blur-img" />
</span>
And maybe this belongs in a home page for example, which is what it sounds like you're trying to do. So maybe you have a route like this:
Route::get('/', function () {
$image = App\Image::random();
return view('home', compact('image');
});
You could achieve this using a Query Scope on your Image model:
public function scopeRandom($query)
{
return $query->inRandomOrder()->first();
}
Edit
If you want this to be used across many, or even all views in your website you can use a View Composer: https://laravel.com/docs/5.6/views#view-composers
Your compose method would look like this:
public function compose(View $view)
{
$view->with('image', Image::random());
}
And the View Composer would be registered either in your AppServiceProvider or in a new provider such as ComposerServiceProvider. Inside of the boot method you need:
public function boot()
{
// Using class based composers...
View::composer(
'*', 'App\Http\ViewComposers\ImageComposer'
);
}
Where the * says that you want this composer to be applied to all views.

How create dynamic generated dropdown in Laravel Blade

I have a table statuses (columns id, statusename) and want display a "select" list based by this table dynamically.
My model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Statuses extends Model
{
protected $table = "CaseStatus";
}
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Statuses;
class StatusesList extends Controller
{
public function getstatuseslist() {
$list = Statuses::all();
return view('forms.statuses')->with('data', $list);
}
}
statuses.blade.php:
<select name="Statuses">
#foreach ($data as $page)
<option value="{{ $page->ID }}">{{ $page->StatuseName }}</option>
#endforeach
</select>
Route:
Route::any('/list/statuses','StatusesList#getstatuseslist');
If i'm open url http://myproject/list/statuses - it work fine, i see the dropdown list.
But if I include my statuses.blade.php in a form in another template:
#include('forms.statuses')
I get the error
"Undefined variable data".
How to include it correctly?
My Laravel version is 5.4.
first of all models are meant to get raw's and not tables if you have table statuses your model name should be status.
the issue of your function not working in another blade is because your another blade controller does not connected to your model so it doesn't know where to get info that you asking for. to solve that issue it's easy, just add your model codes this->
public function getstatuseslist() {
$list = Statuses::all();
return view('your_other_view')->with('data', $list);
}
into that page controller.
don't forget to call your model in your second controller as well.
use App\Statuses;
after that will work just fine in your second blade also.
I think your $data is passed to your 'forms.statuses' view only, when it's pass from that controller method you defined.
If you want to use this data for other "parent" views that include 'forms.statuses', you have to pass it again in the controller that returns that 'parent' view.
There's a way you can make it persist in many views. See 'view composer' for details. Here's the link to view composers at Laravel doc: https://laravel.com/docs/5.4/views#view-composers

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'))

Get data from database and display to blade template in laravel

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.

Categories