Laravel - Notifications Controller can't use method user() - laravel

I'm trying to add notification system to my Laravel project. I' watched this video to understand the system : https://www.youtube.com/watch?v=iDDUxqpNgSc
Notification table, model et controller are created. Also, i have created the view with Vue.JS and Pusher. It's work well !
However, in the notification controller, when i try to user Auth::user() method it's return null. I read somewhere it's because the middleware 'auth' is not already load when the controller is.
This is my NotificationsController file :
<?php
namespace App\Http\Controllers;
use App\Notification;
use Illuminate\Http\Request;
use App\Idea;
use App\User;
use Illuminate\Support\Facades\Auth;
class NotificationsController extends Controller
{
public function __construct()
{
}
function get(){
$notification = Auth::user()->unreadNotifications()->get();
return $notification;
}
function read(Request $request){
Auth::user()->unreadNotifications()->find($request->id)->markAsRead();
}
}
Do you have any idea how to solve this ?
Thank's for your time !

The answer was not about the Auth::user (It's accessible). I just baldy defined the notifiable_type in my model. It was App\Idea, it should be App\User

Related

Issue with Laravel Notifications

I have a problem with Laravel notifications. I try to give a user notification about something, but Laravel cannot find notification class.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
class NotificationController extends Controller
{
public function getNot(Request $request)
{
$user = Auth::user();
$user->notify(new NewPost('a'));
}
}
I've also created a notification with the name NewPost.php, the problem is:
Class 'App\Http\Controllers\NewPost' not found
this one, so in the User model already included Notifications and notifiable.
Add use statement before class definition.
use Illuminate\Http\Request;
use Auth;
use App\Notifications\NewPost;
I assume that you create notification by artisan, if no, then keep in mind that namespace could be different.

Laravel sharing data with all views

I'm trying to run a user-related query to fetch data to appear in the top bar of my site on every view.
I've created a new BaseController according to the first answer here:
How to pass data to all views in Laravel 5?
and that's working for a simple test (just sharing a typed-out variable), but when I try and use Auth::user()->id in the __construct method of BaseController (which in my other controllers always returns the ID of the currently logged in user), I get Trying to get property 'id' of non-object.
I've tried adding use App\User at the top of BaseController (even though it isn't usually needed) and also tried adding in the bits for Spatie laravel-permission plugin, but neither has any effect.
I tried dd on Auth::user() and just get 'null'. My feeling is that the user details maybe haven't been loaded at this stage, but BaseController extends Controller same as MyWorkingController extends Controller so I'm not sure why Auth::user()->id doesn't work here when it does normally?
Create a Base Controller which has all the information that you want to share too all controllers/pages/views and let your others controllers extend it.
open file AppServiceProvider.php from folder Providers and write below code in boot function
view()->composer('*', function ($view)
{
$view->with('cartItem', $cart );
});
And now go to your view page and write :
{{ $cartItem }}
You cannot access Auth in constructors because middleware has not been run yet. You can use either View composer or give try this way though i haven't tested.
class BaseController extends Controller {
protected $userId;
public function __construct() {
$this->middleware(function ($request, $next) {
$this->userId= Auth::user()->id;
return $next($request);
});
}
}
Write this in AppServiceProvider.php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use DB;
use Auth;
use App\Cart;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Schema::defaultStringLength(191);
view()->composer('*', function ($view)
{
view()->composer('*', function($view)
{
if (Auth::check()) {
$cart = Cart::where('user_id', Auth::user()->user_id)->count();
$view->with('cartItem', $cart );
}else {
$view->with('cartItem', 0);
}
});
});
}
}
In you view simply write
{{ $cartItem }}
For anyone interested, I just encountered the same problem and I've solved it with ServiceProvider:
Define your custom ServiceProvider with the command
php artisan make:provider CustomServiceProvider
Add a reference to your service provider in the config\app.php file, specifically in the providers array, adding this item to it:
\App\Providers\CustomServiceProvider::class,
Declare the variables you want to share in your provider's boot() method and share them by using the view()->share method:
public function boot()
{
$shared_variable = "Hello";
view()->share('shared_variable', $shared_variable);
}
You can now reference your variable in your blade files with the standard notation:
{{ $shared_variable }}

Error on finding controller from Laravel API Router

I created a fresh Laravel framework.
I created a controller named PostsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Http\Controllers\Controller;
class PostsController extends Controller
{
public function index()
{
$posts = Post::get();
return response()->success(compact('posts'));
}
}
Then I created a route in the file api.php:
Route::get('posts', 'PostsController#index');
I ran the command
$ php artisan serve`
and I tested the URL
localhost:8000/api/posts
This error occurs:
BadMethodCallException
Method Illuminate\Routing\ResponseFactory::success does not exist.
file: vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php
line: 100
throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
I can't understand why this happened. Please help me.
There is no success method on the ResponseFactory. You can find the available methods here.
You are calling a macro function that is not registerd to the responseFactory.To use success method,Create your custom responseServiceProvider and write this inside boot()
Response::macro('success',function($data){
return Response::json([
'data'=>$data,
]) ;
});
And then register your ResponseServiceProvider to app.php by adding your Class name to the array called providers. This is how you add to the array
App\Providers\ResponseMacroServiceProvider::class

How can i get result from model in laravel 5

Good day, i'm trying to get the result from my model that called with Mainmodel through my controller, my controller is MainController.
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use app\Mainmodel;
class MainController extends Controller
{
function index(){
echo "Kok, direct akses sih?";
}
function get_menu(){
$menu = app\Mainmodel::request_menu();
dd($menu);
}
}
Here is my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mainmodel extends Model
{
function request_menu(){
$menu = DB::table('menu')
->orderBy('[order]', 'desc')
->get();
return $menu;
}
}
my routes
Route::get('menu','MainController#get_menu');
with my script above i get this
FatalErrorException in MainController.php line 17: Class
'App\Http\Controllers\app\Mainmodel' not found
how can i fix this ? thanks in advance.
Note: I'm bit confuse with laravel. I'm using codeigniter before. And i have a simple question. In laravel for request to database should i use model ? or can i just use my controller for my request to database.
sorry for my bad english.
I would imagine it's because your using app rather than App for the namespace.
Try changing:
app\Mainmodel
To:
App\Mainmodel
Alternatively, you can add a use statement to the top of the class and then just reference the class i.e.:
use App\Mainmodel;
Then you can just do something like:
Mainmodel::request_menu();
The way you're currently using you models is not the way Eloquent should be used. As I mentioned in my comment you should create a model for each table in your database (or at least for the majority of use cases).
To do this run:
php artisan make:model Menu
Then in the newly created Menu model add:
protected $table = 'menu';
This is because Laravel's default naming convention is singular for the class name and plural for the table name. Since your table name is menu and not menus you just need to tell Laravel to use a different table name.
Then your controller would look something like:
<?php
namespace App\Http\Controllers;
use App\Menu;
class MainController extends Controller
{
public function index()
{
echo "Kok, direct akses sih?";
}
public function get_menu()
{
$menu = Menu::orderBy('order', 'desc')->get();
dd($menu);
}
}
Hope this helps!
You can solve it by different solution. The solution is you don't have to call request_menu(); you can get it in your controller.
MainController
use use Illuminate\Support\Facades\DB;
public function get_menu(){
$menu = DB::table('menu')
->orderBy('Your_Field_Name', 'DESC')
->get();
dd($menu);
}

Routing in Laravel is not working

I am using laravel 5.0
I am trying to route the following. But it is not working
Route::post('accesscontrols/permissions', 'AccescontrolsController#permission');
I don't know what error in this.
It does not access permissions function in AccesscontrolsController
I have a function in AccesscontrolsController
public function permission()
{
$roles = DB::table('roles')->get();
$permissions = DB::table('permissions')->get();
return view('accesscontrols.permission', compact('roles', 'permissions'));
}
What I have did wrong?
Your route declaration should be made in app/Http/routes.php.
Also, make sure that your controller is within the App\Http\Controllers namespace and that it extends App\Http\Controllers\Controller.
Ex:
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function permission()
{
...
Also, if you whish to test it in the browser (by typing "accesscontrols/permissions" in the address bar), you route should answer to the GET verb. Try to declare it using Route::get( instead.
You are returning a view in your method and you are not working with any POST data, which is strange. Are you sure you want POST request and not GET?

Resources