Navigation bar with categories (and subcategories) - laravel

I need your help. I new in Laravel.
I want to get all categories and subcategories into my navigation bar so on every page. I have a Category model. How to get all categories? Can I just using something like
Category::all()->get() etc.
in my layout, is it right to call from the layout?

You should use view composers to pass a variable to all pages. First create a view composer in App\View\Composer;
namespace App\View\Composers;
use App\Category;
use Illuminate\View\View;
class InjectCategory
{
protected $categories;
public function __construct(Category $categories)
{
$this->categories= $categories;
}
public function compose(View $view)
{
$categories= $this->categories->all();
$view->with('categories',$categories);
}
}
Then you should add the view composer to the AppServiceProvider's boot method.
public function boot(Request $request)
{
$this->app['view']->composer(['includes.frontend.menu'], Composers\InjectCategory::class);
}
Now you can use the $categories values from your menu.blade.php and include it to top of any page you want to show navigation.

Some how when i was working on a Blog Project i also had the same issue which i solved by sharing the data with all views which is quite easy and simple way.
in your app/Provider/AppServiceProvider.php file in boot Method add below code:
public function boot()
{
$categories = Category::all();
view()->share('categories', $categories);
}
and now you can access $categories in every view for more detail info visit this link.

Related

Getting the database data to front view in laravel?

As it is quite easy to get data from database in admin panel,but the case is that how can i get/view those data to front view , front view contains the data from several table. Could you please help me ? How can i manage those front pages easily ?
There are a lot of ways, but this is what I normally do.
Use a separate controller method (say index() HomeController) for the frontpage, and create an array of all the variables with the data from database and pass it on to the page. Let's say our homepage has some slider images, some blog posts, and and our team section, then your HomeController would look something like this:
class HomeController extends Controller
{
public function index()
{
$data = []; //your empty array
$data['sliders'] = Slider::all(); //data from sliders table
$data['posts'] = Post::all(); //data from posts table
$data['teams'] = Team::all(); //data from teams table
return view('frontend.index',compact('data'));
}
Now you can access all these in your frontend blade (here index.blade.php) as such:
#foreach($data['teams'] as $key=> $value)
//your loop code
#endforeach
Hope this helps.
In the wonderfull world of laravel this is super easy. But first let me dive a into the structure of laravel a bit.
It all begins with the controller. In Laravel, Controllers a re meant to group assiociated request handling logic within a single class. A basic resource controller would look like this:
class DomainController extends Controller
{
public function index(){} // list domains
public function create(){} // show create form
public function store(Request $request){ } // handle the form POST
public function show($id){} // show a single domain
public function edit($id){} // show edit page
public function update(Request $request, $id){} // handle show edit page POST
public function destroy($id){} // delete a domain
}
Now how can you return the data to the view?
Let's say we want to generate a list of all users using the index function from the controller.
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
With this return statement we will get a view and in that view we will have the $users variable available because of the use of the comapct function.
Now if we want to show a simple list:
#foreach($users as $user)
<li>{{$user->name}}</li>
<li>{{$user->age}}</li>
#endforeach

How to transfer data to parent template without code duplication,

I have main layout which contains a header, nav, footer and ofc many blade templates with
inherited from him. My problem: i have categories which i need to connect in my navbar, also in many children templates, maybe it can be done somehow globally without duplication code.
It's my 'HomeContoller' return index template, but if i return my categories with $categories my main layout can't see this variable
public function index()
{
$posts = Post::paginate(10);
$popularPosts = Post::orderByViews()->take(6)->get();
return view('front.index', ['posts' => $posts, 'popularPosts' => $popularPosts]);
}
Now i return to layout.blade my $categories by this method.
#php
$categories = App\Category::all();
#endphp
For this particular case I would suggest the View Composer - especially, if you scroll a bit down on that page you'll see Attaching A Composer To Multiple Views - you could use:
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
You can register it under any of the existing providers for instance AppServiceProvider under the boot method:
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
}
}

Define a variable not explained

Sorry for the dumb question but can anyone please tell me how to define a variable in very simple terms? I have struggled for several months with "undefined variable" errors. Are variables stored in config? Or maybe in routes?
I have a database with a customers table. When I put this on my view home page {{$customers->name}} I get Undefined variable: customers.
Fine. So how and where do I define a variable. I would have thought it WAS defined given that the database table is literally called customers. Ugh!
My model file Customer.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $fillable = ['name', 'phone'];
public function address()
{
return $this->hasOne(CustomerAddress::class);
}
public function purchases()
{
return $this->hasMany(CustomerPurchase::class);
}
}
Undefined variable means the variable does not exist and the reasons for your case is, you did not pass it in the view.
Usually, to get the customers records from the database to your views, you can do it in several ways:
Query it prior to loading your view then pass it to your views:
//doing it in the controller
//create a controller: php artisan make:controller CustomerController
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use App\Customer; //Dont forget to import your Customer model
class CustomerController extends BaseController
{
public function index()
{
$customers = Customer::get(); //this will fetch the customer using your mdoel
return view('customer', ['customers' => $customers]); //this will pass the records to the view
}
}
//then in your routes/web.php:
Route::get('/customers', 'CustomerController#index'); //when you go to your application/customers in the browser, it will go to the controller and return the view with the records.
//OR you can skip the controllers and do it in the routes/web.php directly as what #jitesh jose mentioned.
Query straight into your view (Not really recommended, but sometimes you just need to make it work)
In your customer.blade.php
#php
$customers = \App\Customer::get();
#endphp
<ul>
#foreach($customers as $customer)
<li>{{$customer->name}}</li>
#endforeach
</ul>
My advice, try to watch a few basic Laravel videos so that you will understand the flow of the request and response.
If your model name is Customer,laravel automatically pick the table name as customers.Otherwise you have to use your desired table name in Model as follows.
protected $table = 'customers_table';
In your web.php
Route::get('/home',function () {
$customers = DB::table('customers_table')->get();
OR
$customers = Customer::get();
return view('welcome')->with('customers',$customers);
});
You can use$customers in welcome.blade.php as
#foreach($customers as $customer)
{{$customer->name}}
#endforeach

How to pass data to all views in Laravel 5.6?

I have two controllers. StudentController and TeacherController. I have a variable $chat which I want to pass in all the views of StudentController and TeacherController. The $chat will contain different data for both these controllers.
I searched and found ways, but I am getting empty data. I am doing it like this.
<?php
namespace App\Http\Controllers;
use View;
class StudentController extends Controller {
public function __construct()
{
$this->middleware('auth')->except(['home']);
$this->middleware('access')->except(['home']);
$chats = studentChat();
View::share('chats', $chats);
}
So, here I am printing and it is returning an empty array, but when I use the same in a function the array contains data. What is wrong here? Can anyone please help?
What I tried:
public function boot()
{
View::composer('*', function ($view) {
$chats = Cache::remember('chats', 60, function () {
if(Auth::user()->user_type() == config('constant.student'))
{
return studentChat();
}
else
{
return teacherChat();
}
});
$view->with('chats', $chats);
});
}
If you use View::share your share data to ALL your view, if you need to add data to few different views you may do this:
Create blade file(chat.blade.php for your case), and put your variables:
<? $chats = studentChat(); ?>
Include this file to the begining of your views where your need this 'global' varables:
//begin of your blade file
#include('chat')
//some code
{{ $chat->channel }}
Sharing Data With All Views
Occasionally, you may need to share a piece of data with all views that are rendered by your application. You may do so using the view facade's share method. Typically, you should place calls to share within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
$chats = studentChat();
View::share('chats', $chats);
}
public function register()
{
//
}
}
So, what I did was in the AppServiceProvider class, in the boot function I added this.
View::composer('*', function ($view) {
if(!\Auth::check())
{
return;
}
$userType = \Auth::user()->user_type ;
if($userType == config('constant.student'))
{
$chats = studentChat();
}
else if($userType == config('constant.teacher'))
{
$chats = teacherChat();
}
$view->with('chats', $chats);
});
You can pass data to the view Like.
return View::make('demo')->with('posts', $posts);
For more details visit article : Introduction to Routing in Laravel
write your query in boot method in appServiceProvider like,
View::composer('*', function ($view) {
$share_query = Cache::remember('share_query', 60,function () {
return App\User::all();
});
$view->with('share_query', $share_query);
});
Your final solution is ok, but not the cleanest possible.
Here is what i would do.
Define a class with a single function that contains your logic and return $chats, that way you will encapsulate your logic properly and keep your service provider boot method clean.
Then you have 2 options:
Inject your class in the boot() method of the service provider you use, then call its function and uses View::share. Should looks like :
public function boot(ChatResolver $chatResolver)
{
$chats = $chatResolver->getChats();
View::share(compact('chats));
}
If you only use $chats variable in a signe view or partial (like a part of layout), you can also inject the class you defined directly in the view.
Here is a link to Laravel doc regarding that.
In some cases it might be the easiest solution.

Passing the same data over different views in Laravel

I have for example this code in my HomeController:
public function index() {
$comments = Comment::get_recent();
$top = User::get_top_uploaders()->get();
$top_something = User::get_top_something_uploaders()->get();
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
return View::make('index') ->with('data', $data)
->with('comments', $comments)
->with('top', $top)
->with('top_something', $top_something);
}
It works great, but I need to make another couple of view with the same data not only for index but also for other pages like comments(), post()...
How to make this in HomeController that I don't need to make it copy and paste those variables in every controller?
Pass your data using share method:
// for single controller:
class SomeController extends BaseController {
public function __construct()
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
View::share('data', $data);
}
}
For all controllers you can put this code in BaseController's constructor
If the data is displayed using the same HTML each time you could put that piece of HTML into a partial and then use a View Composer.
Create a view and call it whatever you want and put in your HTML for the data.
In templates that need that partial include it #include('your.partial')
In either app/routes.php or even better app/composers.php (don't forget to autoload it)
View::Composer('your.partial', function($view)
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
$view->with('data', $data);
});
Now whenever that partial is included in one of your templates it will have access to your data

Resources