Laravel share data to 404 page view - php

I have created a controller which extends BaseController and shares some data in all the views
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
public function __construct()
{
$this->middleware(function ($request, $next) {
if (Auth::check()) {
$id = Auth::id();
} else {
$id = Session::getId();
}
\Cart::session($id);
$cart = \Cart::getContent();
$total = \Cart::getTotal();
View::share('cart', $cart);
View::share('total', $total);
return $next($request);
});
}
}
The issue is, it doesn't get shared in error pages like 404.
I'm using Laravel 8.75

First you should publish all the error pages using this command:
php artisan vendor:publish --tag=laravel-errors
Then, hopefully it will work. If it didn't work then include this logic in AppServiceProvider's boot() function instead of base Controller.

After some trial and error the issue was that web middleware was not being executed in error pages.
Added to web.php
Route::fallback(function(){
return view('errors.404');
});
Also to appServiceProvider.php boot() (optional)
View()->composer(['layouts.main'], function($view) {
if (Auth::check()) {
$id = Auth::id();
} else {
$id = Session::getId();
}
\Cart::session($id);
$cart = \Cart::getContent();
$total = \Cart::getTotal();
$view->with([
'cart' => $cart,
'total' => $total
]);
});
The reason i put the auth checking inside the view composer callback is because middlewares have to be executed to be able to grab the user.

Related

deleting a user with query builder laravel

I'm trying to delete a user account using laravel query builder so I'm doing this
AuthRepository
class AuthRepository implements IAuthRepository
{
....
public function delete($user_id)
{
$res = User::where('id', $user_id->id)->delete();;
if ($res) {
return response('Success, user was deleted', 204);
} else {
return response()->json(error);
}
}
}
In controller
class AuthController extends Controller
{
protected $auth;
public function delete($user_id)
{
return $user_id->delete();
}
}
in api.php
Route::group(['prefix' => 'auth'], function () {
Route::group(['middleware' => 'auth:api'], function () {
// Delete user
Route::post('user/delete/{user_id}', 'AuthController#delete');
});
});
Passing user_id to ${API_URL}/auth/user/delete/{user_id} I'm facing
Call to a member function delete() in Controller on line return $user_id->delete();. Can someone please explain me why is this happening, thanks.
Take advantage of the route model binding and to this instead:
public function delete(User $user)
{
return $user->delete();
}
And your route:
Route::post('user/delete/{user}', 'AuthController#delete');
You cannot call delete() on an integer.
If you don't want to use the Route model binding as suggested by #nakov and insist on using id then you have to get the user first before deleting.
public function delete($user_id)
{
$user = User::findOrFail($user_id);
return $user->delete();
}

How to update email value in laravel

We know that laravel has an update () method that updates records using the http "put" method. But I do not know how to create an edpoint in which I will be able to modify the email.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserController extends Controller
{
public function index()
{
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
}
public function store(Request $request)
{
$user = new User();
$user->name = $request->get("name");
$user->email = $request->get("email");
$user->password = $request->get("password");
$user->save();
return response()->json($user->toArray(), 200);
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
And my route:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('v1/users/create', 'UserController#store');
RESTful APIs made by me tests in Postman. Help me somebody
Looking at your question, I think you need to create a route to link to update method in your controller same way you created a post for creating user.
Route::put('v1/users/client/{id}', 'UserController#update);
OR you can use laravel predefined code to create all CRUD routes.
Route::resource('v1/users/client', 'UserController').
To view all the routes created, use
php artisan route:list
Have a further study on this.

Laravel Dingo FindOrFail returns empty array

I have a table sites with list of sites with following columns ('id', 'path', 'site_link'). I've written in a Site model public $timestamps = false; so that it won't try to work with time what I don't need.
Also I have the following routes
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
$api->get('sites', 'App\Http\Controllers\SiteController#index');
$api->get('sites/{site}', 'App\Http\Controllers\SiteController#show');
});
The first one is working fine and returning all the data, however the second one is returning just [].
I have a controller which is below
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Use App\Site;
class SiteController extends Controller
{
public function index()
{
return Site::all();
}
public function show(Site $site)
{
return Site::findOrFail($site);
}
public function store(Request $request)
{
$site = Site::create($request->all());
return response()->json($site, 201);
}
public function update(Request $request, Site $site)
{
$site->update($request->all());
return response()->json($site, 200);
}
public function delete(Site $site)
{
$site->delete();
return response()->json(null, 204);
}
}
The show method in your SiteController is taking a Site object. However the route is set up to only take the siteId. The code below should work for you based on how you've set up your routes.
public function show($site)
{
return Site::findOrFail($site);
}
Apply same to all your other controller methods since you want pass the site id via the url to the controller methods.

Laravel 5.4 User Profile NotFoundHttpException

I am creating a user profile that allows him to modify his information here is the code
class ProfilesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('content.profil');
}
public function editProfile($id)
{
$user = User::find($id);
return view('content.edit', ['user' => $user]);
}
public function updateProfile(Request $request, $id)
{
$user = User::find($id);
$user->name = $request->input('name');
$user->nom = $request->input('nom');
$user->prenom = $request->input('prenom');
$user->adresse = $request->input('adresse');
$user->code_postal = $request->input('code_postal');
$user->ville = $request->input('ville');
$user->pays = $request->input('pays');
$user->num_tele = $request->input('num_tele');
$user->save();
return redirect('/profil');
}
}
Web.php
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content', 'ProfilesController#updateProfile')->name('profil.update');
});
the view folder tree looks like
view/content/profil.blade.php
view/content/edit.blade.php
the problem is that the routes are defined but it shows me this error message:
(1/1) NotFoundHttpException
I don't know where the problem exists exactly and
thanks in advance
Compared to your routes (web.php) and what you want, this is what your web.php file should be
Route::group(['middleware' =>'auth'], function(){
Route::get('/profil', 'ProfilesController#index')->name('profil');
Route::get('/content/{id}/editProfile', 'ProfilesController#editProfile')->name('profil.edit');
Route::post('/content/{id}', 'ProfilesController#updateProfile')->name('profil.update');
});
Correct your profil.edit route to /content/{id}/editProfile and profil.update in the same way.
And if you have named routes try to use route() helper instead of url() to generate url's, it's cleaner are more universal.

Issue accessing Auth() object data in Laravel class

I am seeing some behaviour. I can't explain when accessing user data via the Auth facade in Laravel class. Here's an extract of my code:
private $data;
private $userID;//Set property
function __construct()
{
$this->middleware('auth');//Call middleware
$this->userID = Auth::id();//Define property as user ID
}
public function index() {
return view('');
}
public function MyTestMethod() {
echo $this->userID;//This returns null
echo Auth::id();//This works & returns the current user ID
}
I am logged in and have included use Illuminate\Support\Facades\Auth; in the class thus the code works, but only when accessing Auth in methods - else it returns a null value.
Most odd, I can't work out what is causing this. Any thoughts much appreciated as ever. Thanks in advance!
In Laravel Laravel 5.3.4 or above, you can't access the session or authenticated user in your controller's constructor, since the middlware isn't runnig yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor.:
try this :
function __construct()
{
$this->middleware(function ($request, $next) {
if (!auth()->check()) {
return redirect('/login');
}
$this->userID = auth()->id(); // or auth()->user()->id
return $next($request);
});
}
another alternative solution go you your base controller class and add __get function like this :
class Controller
{
public function __get(string $name)
{
if($name === 'user'){
return Auth::user();
}
return null;
}
}
and now if your current controller you can use it like this $this->user:
class YourController extends Controller
{
public function MyTestMethod() {
echo $this->user;
}
}
You should try this :
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
OR
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userID = Auth::user()->id;
return $next($request);
});
}

Categories