Laravel spatie , assignrole() is not working when team_id is used? - laravel

this is modified seeder code
$user = User::where('id', 1)->get();
$role = Role::where('id', 1)->get();
echo $role;
$user->assignRole([$role->id]);
this is the output
[{"id":1,"team_id":2,"name":"Admin","guard_name":"web","created_at":"2023-01-10T06:40:56.000000Z","updated_at":"2023-01-10T06:40:56.000000Z"}]
Exception
Property [id] does not exist on this collection instance.
at vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php:969
965▕ */
966▕ public function __get($key)
967▕ {
968▕ if (! in_array($key, static::$proxies)) {
➜ 969▕ throw new Exception("Property [{$key}] does not exist on this collection instance.");
970▕ }
971▕
972▕ return new HigherOrderCollectionProxy($this, $key);
973▕ }
1 database/seeders/CreateAdminUserSeeder.php:32
Illuminate\Support\Collection::__get("id")
+22 vendor frames
24 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
you can see that the id is there on echo but I cant assign the role using its id
this only happed when teams set to trues in config file.
I am missing something or is it a bug?(highly doubt it )

$role = Role::where('id', 1)->get(); returns a collection of roles
Instead you can either do:
$role = Role::find(1);
or
$role = Role::where('id', 1)->first();
To clear the cache when adding new permissions/roles run the following artisan commands:
php artisan cache:clear
For reference you can run the following to clear everything cached:
php artisan cache:clear
php artisan view:clear
php artisan config:clear
php artisan route:clear

Related

Laravel Lumen function env() returns null sometimes

I am developing api with Lumen 6.2.0 which gets GET request with certain parameters and token. When it gets parameters it process it in a certain way and then encode with a secret key which is in my .env file and then compares result with the token which was provided with the request, if comparison result is true then user is authenticated else he is not. So the problem is sometimes env() function returns null. It doesn't happen pretty often, just like 1 request out of 15, but it's still a serious problem for me.
I googled a lot but found just few approaches. Firstly I found out that env() function should be only invoked in config file and since Lumen doesn't have a config directory and config files I have created it, but the issue remains the same. The second advice was for Laravel specifically - php artisan config:clear and php artisan config:cache but Lumen doesn't have such commands, although I ran the php artisan cache:clear command to no avail. So here is my code:
.env file
APP_NAME=Example
APP_ENV=local
APP_KEY=ApPkEyHeRe
APP_DEBUG=true
APP_URL=https://example.com
APP_TIMEZONE=UTC
LOG_CHANNEL=stack
LOG_SLACK_WEBHOOK_URL=
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpass
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
VK_APP_SECRET=SoMeFaNcYkEy
config/config.php
<?php
return [
'vk_app_secret' => env('VK_APP_SECRET'),
'events_per_page' => 16
];
And UsersController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
class UsersController extends Controller
{
public function check(Request $request) {
$query_params = $request->all();
$sign_params = [];
foreach ($query_params as $name => $value) {
if (strpos($name, 'vk_') !== 0) {
continue;
}
$sign_params[$name] = $value;
}
ksort($sign_params);
$sign_params_query = http_build_query($sign_params);
$secret = config('config.vk_app_secret');
$hash_hmac = hash_hmac('sha256', $sign_params_query, $secret, true);
$base_encode = base64_encode($hash_hmac);
$trim_chars = strtr($base_encode, '+/', '-_');
$sign = rtrim($trim_chars, '=');
$status = $sign === $query_params['sign'];
return json_encode($status);
}
}
I also logged every line of this algorithm, and noticed an interesting thing, the failing case contains [date] production.INFO: prefix before log's rows, and every successful case [date] local.INFO: So maybe it's affecting env() function somehow? I also don't get it why it sometimes logged as production when I have APP_ENV=local

Laravel 404 Not Found - But Route Exists

Hello im trying to get information about user on my view.
Here is my UserController
public function getUser(Request $request, $id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user' -> $user]);
}
here is my web.php
Route::get('admin/user/{id}', "UsersController#getUser");
and my user view
#extends('admin.layouts.app')
#section('contents')
<h1>User {{ $user }} </h1>
#endsection
I am trying to display user information in this view, like name etc, but im recives 404
Not Found page. What im doing wrong. Im using Laravel 6
404 error may refer to a User not being found, since you have a findOrFail() query. It may have nothing to do with your routes.
Just double check with:
php artisan route:list
just to make sure the route is being registered correctly.
I think you firstly use any prefix for this route.For this it will give you an error.To check route list.
php artisan route:list
it will give you all route.
And Here you don't need (Request $request) because here you just need the id.it not the problem..i give you just this suggestion
public function getUser($id)
{
$user = User::findOrFail($id);
return view('admin.user', ['user'=> $user]);
}
why you use '-> ' you should use '=>'

Method Illuminate\Auth\SessionGuard::users does not exist

I'm having a problem with Auth. I'm just learning about Laravel, I'm doing login. I don't know how to fix it it says:
Method Illuminate\Auth\SessionGuard::users does not exist.
this is my code in login function
public function getlogin(Request $request){
$this->validate($request, [
'email'=> 'required|max:32',
'password'=> 'required|max:32|min:8',
]);
if (Auth::attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}
return "ooopps something wrong";
}
and this is where the name from the database will be display
<div class="">
<h1>Welcome
#if(session('user'))
{{session('user')}}
#elseif(session('usersignin'))
{{ucwords(Auth::users()->fname)}}
#endif</h1>
</div>
You need to use user instead of users, user is provided with Auth and will get the current logged in user id.
$id = \Auth::user()->id;
Or you want to get the user
$user = \Auth::user();
I solved this error by running the below command
php artisan jwt:secret
php artisan cache:clear
php artisan config:cache
in your if statement just use it as below
if (auth()->attempt(['email'=>$request->email,'password'=>$request->password])) {
$user = users::where('email','=',$request->email)->first();
return redirect('/messenger')->with('usersignin');
}

Retrieving image stored in storage folder

Using laravel 5.3, I am trying to retrieve an image in a view. How I could do this?
folder structure: storage/app/avatard
Here is the code:
public function storeAvatar(Request $request, $username)
{
$user = User::where('name', $username)->first();
$avatar = $request->file('avatar')->store('avatars');
$avatar = explode('avatars/', $avatar);
$user->user_setting()->updateOrCreate(
['user_id' => $user->id],
['avatar' => $avatar[1]]
);
return back();
}
This is how the image path is saved in the database:
/users/avatar/default.png
Somewhat like this you can achieve as storage path is directly unavailable for public. you need to provide public url in route like this.
In view
<img src="{{route('avatar',$filename)}}" />
or
<img src="/avatars/{{$filename}}" />
In routes/web.php
Route::get('/avatars/{filename}', function ($filename)
{
$path = storage_path() . '/avatars/' . $filename;
if(!File::exists($path)) abort(404);
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
})->name('avatar');
First create a storage link by typing in
php artisan storage:link
and then
<img src={{ asset('storage/folder_name/image_name') }} />
If you store your files in the storage/app/public directory as per the Laravel documentation you can create a symbolic link on Unix/Linux systems that will allow you to reference the files as if they were in the public directory.
Create the symbolic link using the artisan command:
php artisan storage:link
In your views you are then able to reference the files using
{{ asset('storage/path/to/file.png') }}
Consider if you are using Homestead, you must create the symbolic link from the virtual machine;
In your terminal:
homestead ssh
go to your project folder:
cd Code/YOUR_PROJECT
now you can execute the command:
php artisan storage:link

laravel 5 urlgenerator with Form::open route with Route Annotations

I'm using Laravel 5 with Route Annotations. (The app\Http\route.php will be automaticaly deleted). For video about Route Annotations, you may have a look at https://www.youtube.com/watch?v=sOvgw40Dg4A
I build a ContactController.php with php artisan make:controller ContactController
And at store() function, I add return view('pages.contact'); to re-input another contact data.
When I give the script below on my pages\contact.blade.php :
{!! Form::open(['route'=>'contact.store']) !!}
It allways return error as below :
ErrorException in UrlGenerator.php line 237: Route [contact.store] not defined. (View: D:\www\mycontact\resources\views\pages\contact.blade.php)
which refer to :
public function route($name, $parameters = array(), $absolute = true)
{
if ( ! is_null($route = $this->routes->getByName($name)))
{
return $this->toRoute($route, $parameters, $absolute);
}
throw new InvalidArgumentException("Route [{$name}] not defined.");
}
But when I change into :
{!! Form::open(['url'=>'contact']) !!}
it works normally.
How to fix my laravel so I can use the route ?
Below are the things that I have done :
composer require illuminate/html
At config\app.php , I add : 'Form' => 'Illuminate\Html\FormFacade' so I can use the {!! Form:: !!}
Then I execute the following command :
composer update
composer dump-autoload
php artisan dump
php artisan clear-compiled
php artisan dump-autoload
php artisan optimize
php artisan route:clear
php artisan route:scan
php artisan route:list
So... How to fix my laravel so in my blade, I can use {!! Form::open(['route'=>'contact.store']) !!} instead {!! Form::open(['url'=>'contact']) !!} ?
PS:
I use XAMPP on Windows 7 Pro 64bit.
And I already read : http://laravel.io/forum/10-11-2014-forms-doesnt-work-in-laravel-5
For my steps on Route Annotations, at App\Providers\RouteServiceProvider.php , I add my controllers with in
protected $scan = [
'App\Http\Controllers\HomeController', // for http://localhost/myl5/
'App\Http\Controllers\ContactController', // for http://localhost/myl5/contact
];

Resources