Run a command in Laravel on every page load - laravel

I want to load a command with Laravel on each page load;
$mail_count = mail::where('to_id', '=', Auth::user()->id)->where('read', '=', '0')->count('read');
What would be the best way to do this? This then needs to output the result in the master template for the page.

Use a view composer for master template, for example:
// app/providers/ComposerServiceProvider.php
public function boot()
{
view()->composer(
'layouts.master', 'App\Http\ViewComposers\MasterComposer'
);
}
Then create the Composer class:
namespace App\Http\ViewComposers;
use Auth;
use App\Mail;
use Illuminate\View\View;
class MasterComposer
{
public function compose(View $view)
{
$mail_count = Mail::where('to_id', Auth::user()->id)
->where('read', 0)
->count('read');
$view->with('mail_count', $mail_count);
}
}
Finally, you can use {{ $mail_count }} in your master view to print out the result. So, in this case, what it's doing is, whenever your views\layouts\master.blade.php will be rendered the compose method will be called and $mail_count will be attached into the view. Make sure to use the exact name for the view, I've used layouts.master (views/layouts/master.blade.php) for this example.

You can use it in a laravel provider
go to the AppServiceProvider.php inside the boot function paste variable
$mail_count = mail::where('to_id', '=', Auth::user()->id)->where('read', '=', '0')->count('read');
then you can do it with one of the options:
1.
view()->composer('*', function($view) use($mail_count){
$view->with('mail_count', $mail_count);
});
2.
view()->share('mail_count', $mail_count);

Related

overriding replationship column to show only users with specific role

I created BREAD for using voyager with relationship column to display all the users and i want this column to show only users with admin role.
I tried to override the view but I think its wrong choice any help?
#if($row->field == 'lead_belongsto_user_relationship')
#endif
I can reach the column in the view/add view but I don't know how to edit the array of results or how to override the query.
It is showing all the users I want to show only admin list.
I finally did it Using custom Controllers.
Steps:
First create new controller
php artisan make:controller LeadController
Extend Voyagers controller
<?php
namespace App\Http\Controllers;
class LeadController extends \TCG\Voyager\Http\Controllers\VoyagerBaseController
{
//...
}
?>
Finally you can override the relation function from VoyagerBaseController
if($request->type == "lead_belongsto_user_relationship"){
if ($search) {
$total_count = app($options->model)->where($options->label, 'LIKE', '%'.$search.'%')->count();
$relationshipOptions = app($options->model)->take($on_page)->skip($skip)
->where($options->label, 'LIKE', '%'.$search.'%')->where("role_id",3)
->get();
} else {
$total_count = app($options->model)->count();
$relationshipOptions = app($options->model)->take($on_page)->skip($skip)->where("role_id",3)->get();
}
}
Here i overrided it to select only users with role_id = 3 you can customize it as you need.
After that go to the BREAD-settings and fill in the Controller Name
with your fully-qualified class-name in my case it is
"\App\Http\Controllers\LeadController"

Conditional BREAD in Laravel / Voyager

Is there a way to apply certain conditions to the list of records displayed by Voyager's BREAD? For example, only display records where a certain column is blank (i.e. WHERE 'col_name' IS NULL)?
UPDATE (17/12/18):
You can override the controller and add the where clause. For example, if you need to override "Posts" list, then you should:
Make a custom PostController: php artisan make:controller PostController
Extend it from Voyager BREAD controller: class PostController extends \TCG\Voyager\Http\Controllers\VoyagerBaseController
Import Voyager's Facade: use TCG\Voyager\Facades\Voyager;
Copy the whole index function from VoyagerBaseController. You can find it in \vendor\tcg\Voyager\Http\Controllers\VoyagerBaseController
Override it to add any logic or filter you need, for example:
$dataType = Voyager::model('DataType')
->where('slug', '=', $slug)
->where('col_name', '=', NULL)
->first();
You can also set $orderBy = 'col_name' and $sortOrder = 'asc'/'desc' custom values in the same function. Here Voyager's docs.
OLD:
Yes, there is. You need to edit the view and apply a condition filter. Here is explained how to override views (and controllers if you want to filter it before sending the data to the view).
Just define a Scope in your model:
public function scopeMyScope($query)
{
return $query->where('col_name', null);
}
then go to Bread Form and select it form Scope drop down :)

Laravel 5.4 - route model binding condition

I have implemented route model binding as follows:
Route:
Route::get('property/{property}', 'PropertyController#view');
Controller:
public function view(Property $property)
{
$data = compact([
'property'
]);
return view('property.view', $data);
}
This works great. However I want to add a condition to the Property model to check that active = 1. How and where do I do this?
You can register an explicit binding. Add the code below to RouteServiceProvider. This will be applied to the model binding when the segment is property.
Route::bind('property', function ($id) {
return \App\Property::where('id', $id)
->where('active', 1)
->firstOrFail();
});
If you need this condition to be applied globally for every result then you can add a global scope instead. https://laravel.com/docs/5.4/eloquent#global-scopes

Why my where query is not executed in controller?

I'm trying to reach items table from CategoriesController.php, but I see in Laravel(5.3) Debugbar, that my query is not executed. Why? Here is my code:
# Http/Controllers/CategoriesController.php
use App\Category;
use App\Item;
use App\Http\Requests;
use App\Http\Controllers\Controller;
namespace App\Http\Controllers;
use Request;
class CategoriesController extends Controller {
public function show($id) {
$items = \App\Item::where('id', $id); # <- This is not executed!
$category = \App\Category::find($id);
return view('categories.show', compact('category', 'items'));
}
}
::where() is chaining off of the query builder, however you never execute the request.
::where('id', $id)->first(); //if you only want the first result
//shorthand would be ::find($id);
Alternatively if you want every match:
::where('id', $id)->get();
$items = \App\Item::where('id', $id);
This line is preparing a query for Eloquent to execute, but you never actually execute it.
Try running the following to execute the query and get all the results.
$items = \App\Item::where('id', $id)->get();
You need to use get() or first() or paginate or pluck() or find() etc to execute the query. In this case you want to use first() method:
\App\Item::where('id', $id)->first();
Or just:
\App\Item::find($id);

Laravel 4 - Getting database results into a view

Im having a bit of trouble learning to get my data into my view, and i was hoping someone could help me.
I have the following function in my model
public function getPrivateMessages()
{
$userId = Auth::user()->id;
$messages = DB::table('pm_conversations')
->where(function($query) use ($userId) {
$query->where('user_one', $userId)
->where('user_one_archived', 0);
})
->orWhere(function($query) use ($userId) {
$query->where('user_two', $userId)
->where('user_two_archived', 0)
})
->get();
}
How would i pass it to my controller, then into my view?
Im a bit lost.
Thanks
Assuming that this is your Conversation model, you need to return those messages you queried:
public function getPrivateMessages()
{
...
return $messages;
}
Use it in your controller to pass to your View:
class HomeController extends Controller
{
public function index()
{
$conversation = Conversation::find(1);
return View::make('index')->with('privateMessages', $conversation->getPrivateMessages());
}
}
And in your view show whatever you need to:
<html><body>
#foreach($privateMessages as $privateMessage)
{{$privateMessage->text}}
#endforeach
</body></html>
In your controller, you would call this in one of your actions:
$pms = MyModel->getPrivateMessages();
return View::make('layout')
->with('pms', $pms);
Note that MyModel should be replaced with the actual name of your model. The ->with('pms',$pms) bit says, pass the contents of the variable $pms to the 'layout' view and assign it to a variable named 'pms' in that view. Feel free to customize the name of the view to match whatever view you want to use and pick different variable names if you are so inclined.
Then, in your view you would use it like this:
#foreach($pms as $pm)
<p>From: {{ $pm->user_one}}</p>
<p>{{ $pm->message }}</p>
#endforeach
Here, we're just looping over each of the private messages and outputting a few fields (user_one and message, you'd want to use the names of whatever columns you have in the database).
For more info see these sections of the docs:
Views
Basic controllers
inside your view
<?php $var=DB::table('tablename')->get(); ?>
#foreach($var as $variable)
{{ $variable->tablefield }}
#endforeach
here we are accessing the table named 'tablename' from our database (abbrievated as DB) and then accessing all the columns of the table through get method. Then we are storing them in a random variable (say var so the that we can loop it easily). And then we are simply looping through to print our column data(as in the case above)

Resources