Calling model inside view or sharing with all views - laravel

I am wondering what are differences between this:
Make your own BaseController and extend laravel's controller. Then extend this one in every other controller and pass some data to all views.
class BaseController extends Controller {
public function __construct() {
$user = User::all();
View::share('user', $user);
}
}
Simply use this inside view
#php
$chats = App\Messages::all();
#endphp
I have an chat app where I display all conversations, but I am wondering is there a better solution to share Messages model to all views where it is used?
In my case I include file with chat html into all views and only in that file I call Messages model inside #foreach
UPDATE: Seems like I cant convert code into code block here :/
Try to edit it... I cant

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

Send A varriable from controller to blade

how can i inject a variable from controller to blade ,it is header
blade so it common for every page but no route url or controller
function is connected with it, please tell me a way to send the data
from Controller To header.blade.php Is there any possible way to
inject the variable?
You can share data with all views using your AppServiceProvider located in your app/Providers/AppServiceProvider.php
In the boot() method, use the view() helper and assign data.
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
view()->share('name', 'My Name');
}
}
You can use it like any other variable in your view like this :
{{ $name }}

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

Navigation bar with categories (and subcategories)

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.

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