I want a system where I connect users with tasks and later I can assign tasks to different users from the amdin panel. My program doesn't work, it doesn't assign tasks to users. Later, I want to make sure that when a user logs in, they can only see their own tasks that an amdin has given them. Please help me what is the problem?!
Create user_task
Schema::create('user_task', function (Blueprint $table) {
$table->id();
$table->foreignId('task_id')->constrained()->onDelete('cascade');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
Create users
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar')->default('default.jpg');
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Create tasks
Schema::create('tasks', function (Blueprint $table) {
$table->id();
$table->string('alkalmazott');
$table->string('projekt')->default('-');
$table->string('feladat');
$table->date('hatarido');
$table->timestamps();
});
Task model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
use HasFactory;
protected $fillable = [
'alkalmazott', 'projekt' , 'feladat', 'hatarido'
];
public function projects(){
return $this->belongsToMany('App\Models\Project');
}
public function users()
{
return $this->belongsToMany('User', 'user_tasks');
}
}
User model
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Laravel\Sanctum\HasApiTokens;
use Tasks;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
//public function setPasswordAttribute($password) {
// $this->attributes['password'] = Hash::make($password);
//}
public function jogoks(){
return $this->belongsToMany('App\Models\Jogok');
}
public function tasks()
{
return $this->belongsToMany('Task', 'user_tasks');
}
/* Check if the user has a role
* #param string $role
* #return bool
*/
public function hasAnyRole(string $role){
return null !== $this->jogoks()->where('name', $role)->first();
}
/* Check if the user has any given role
* #param array $role
* #return bool
*/
public function hasAnyRoles(array $role){
return null !== $this->jogoks()->whereIn('name', $role)->first();
}
}
Task controller (here i want to upload tasks)
<?php
namespace App\Http\Controllers;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Http\Request;
class TasksController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$tasks = Task::latest()->paginate(10);
return view('admin.tasks.index',compact('tasks'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('admin.tasks.create', ['users' => User::all()], ['tasks' => Task::all()]);
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
Task::create($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function show(Task $Task)
{
return view('admin.tasks.show',compact('Task'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function edit(Task $Task)
{
return view('admin.tasks.edit',compact('Task'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Task $Task)
{
$request->validate([
'alkalmazott' => 'required',
'projekt' => 'required',
'feladat' => 'required',
'hatarido' => 'required',
]);
$Task->update($request->all());
return redirect()->route('admin.tasks.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Task $Task
* #return \Illuminate\Http\Response
*/
public function destroy(Task $Task)
{
$Task->delete();
return redirect()->route('admin.tasks.index')
->with('success','Product deleted successfully');
}
}
And after i run my upload form, on the phpmyadmin the task has uploaded done but in the user_task table not working. Because its not working i cant display tasks for the users. Thank you for your replies!
You can use attach(), detach() or sync() functions in controller.
For example:
public function store(Request $request){
// ...
$task = Task::create($request->all());
$task->users->attach($request->users); // or you can use sync(), according to your needs and project
// $request->users must be an array like [1,3,10,21,28] etc.
// ...
}
Related
I'm building a CRUD using Laravel and Angular technologies. However, as I am new to Laravel technology, I am not able to establish a relationship between two entities.
I have Group entity and Subgroup entity. A group has only its id and its name as attributes. A subgroup has its id, name and also a group id.
I would like to know how can I establish a relationship between group and subgroup. I want to store the id of a group in a subgroup record, but when performing queries with the HTTP verb I want the Group object to be returned and not its id, so that I can manipulate this object in the front-end.
Model Group:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
protected $table = 'groups';
}
Group Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Group Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('groups', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('groups');
}
};
Subgroup Resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group_id' => $this->group_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Subgroup Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subgroup extends Model
{
use HasFactory;
protected $fillable = [
'group_id'
];
protected $table = 'subgroups';
}
Subgroup Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('subgroups', function (Blueprint $table) {
$table->increments('id');
$table->foreignIdFor(Group::class);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subgroups');
}
};
Subgroup Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Subgroup;
class SubgroupController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Subgroup::all();
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
return Subgroup::create($request->all());
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
return Subgroup::find($id);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
if (Subgroup::where('id', $id)->exists()) {
$subgroup = Subgroup::find($id);
$subgroup->group_id = $request->group_id;
$subgroup->save();
return response()->json([
"message" => "Success"
], 200);
} else {
return response()->json([
"message" => "Error"
], 404);
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
if (Subgroup::where('id', $id)->exists()) {
$subgroup = Subgroup::find($id);
$subgroup->delete();
return response()->json([
"message" => "Successfully deleted"
], 202);
} else {
return response()->json([
"message" => "Not Found"
], 404);
}
}
}
I would like to know if I'm on the right path of establishing a relationship between the tables. Also, when retrieving a Subgroup I would like the group_id field not to return the id but a group object, how can I do that?
You have to use Relationships, it is a whole section on the documentation...
So, I think you want a 1-to-N (one to many), so one Group can have multiple Subgroups.
If that is the case, you should have:
Group model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
use HasFactory;
protected $fillable = [
'name'
];
public function subgroups()
{
return $this->hasMany(Subgroup::class);
}
}
Subgroup
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Subgroup extends Model
{
use HasFactory;
protected $fillable = [
'group_id'
];
public function group()
{
return $this->belongsTo(Group::class);
}
}
See that I have removed $table from both, as the framework will be able to define the same name as you defined there.
Now, if you want to return a name instead of a group_id on your Resource, you should have it like this (after applying the previous changes):
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group_name' => $this->group->name,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
If you read the documentation, you will see that, after defining a relationship (for example, group method), you can use $model->group and that will return the associated Group model if found, else null. You can also use $model->group() and that will return a Builder so you can do something on that resource (with a builder, not a model class).
In your specific case, you can directly return the object, as you wanted, by doing:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class SubgroupResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
return [
'id' => $this->id,
'group' => $this->group,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
I have a table called addresses, it has a column name user_ids which is an array of the users who have that same address.
When I request to /api/addresses what it returns is {id:1,name:"lorem", user_ids:[1,2]}. I want it to return the users instead of their ids
this is the addresses model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
use HasFactory;
protected $fillable = [
'coordinates',
'title',
'description',
'user_ids',
];
protected $appends = ['user_ids'];
protected $casts = [
'user_ids' => 'array',
];
public function users()
{
return $this->belongsToMany(User::class,"addresses");
}
}
this is the create_table_addresses
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->id();
$table->string('coordinates');
$table->string('title');
$table->string('description');
$table->json("user_ids");
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('addresses');
}
};
addresses controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreAddressRequest;
use App\Http\Requests\UpdateAddressRequest;
use App\Models\Address;
class AddressController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return Address::with('users')->get();
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \App\Http\Requests\StoreAddressRequest $request
* #return \Illuminate\Http\Response
*/
public function store(StoreAddressRequest $request)
{
$address = Address::create($request->validated());
return response()->json($address, 201);
}
/**
* Display the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function show(Address $address)
{
return $address;
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function edit(Address $address)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \App\Http\Requests\UpdateAddressRequest $request
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function update(UpdateAddressRequest $request, Address $address)
{
$address->update($request->validated());
return response()->json($address, 200);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Address $address
* #return \Illuminate\Http\Response
*/
public function destroy(Address $address)
{
$address->delete();
return response()->json(null, 204);
}
}
My suggestion would be to use the database for this (since you're already using the with('addresses')).
(Documentation for that relationship starts here)
Migration:
Schema::create('address_user', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('address_id')->unsigned()->index();
$table->foreign('address_id')->references('id')->on('addresses')->onDelete('cascade');
$table->primary(['user_id', 'address_id']);
});
User model:
use App\Models\User;
class Address extends Model {
public function users() {
return $this->belongsToMany(User::class);
}
}
Address model:
use App\Models\Address;
class User extends Model {
public function addresses() {
return $this->belongsToMany(Address::class);
}
}
Now you can use the relationship your application:
$address->users // Get all the users with that address
$user->addresses // Get all the addresses for the user
Address::with('users') // Get addresses with the users as an attribute
User::with('addresses') // Get users with the Address as an attribute
I am assuming that the response comes from a controller so then where you build you response, you need to append the user information.
Maybe something like
User::whereIn('id', [1,2])->get() ...
If you post the controller, then I can tell you exactly where to put this or how to do it better.
i want create tag to my blog project | laravel
in models i make Many To Many relation in models but when i want to attach i get this error:
to a member function attach() on null
it is my blog model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use User;
class Blog extends Model
{
use HasFactory;
protected $fillable = [
'name',
'body',
];
/**
* Get the blog that owns the user.
*/
public function user()
{
return $this->belongsTo(User::class);
}
public function tags()
{
$this->belongsToMany(Tag::class);
}
}
and it is my tag model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
use HasFactory;
public function blogs()
{
$this->belongsToMany(Blog::class);
}
}
and it is my tag and blog_tag table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Schema::create('blog_tag', function (Blueprint $table) {
$table->integer('blog_id')->unsigned()->index();
$table->foreign('blog_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
$table->integer('tag_id')->unsigned()->index();
$table->foreign('tag_id')->references('id')->on('blogs')->onUpdate('cascade')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tags');
Schema::dropIfExists('blog_tag');
}
};
and it is my blog table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->string('name');
$table->longText('body');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onUpdate('cascade')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
};
and it is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use function Ramsey\Uuid\v1;
use App\Models\User;
use App\Models\Blog;
use Illuminate\Support\Facades\Auth;
use DateTime;
class BlogController extends Controller
{
public function __construct() {
$this->middleware('auth')->only('create');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('welcome');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('blog.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, Blog $blog)
{
$validated = $request->validate([
'name' => 'required|max:100|min:3',
'body' => 'required|min:30',
]);
$name = $request->input('name');
$body = $request->input('body');
$blog->insert(['user_id' => Auth::id(),
'name' => $name,
'body' => $body,
'created_at' => new DateTime,
'updated_at' => new DateTime
]);
$blog->tags()->attach(1);
$request->session()->flash('sucsess', 'blog created succsessfully');
return back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($username, $blogName, User $user)
{
$user = $user->where('name', $username)->first();
$blog = $user->blogs->where('name', $blogName)->first();
// return $user->blogs->where('name', $blogName);
return view('blog.show', compact('user', 'blog'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($username, $blogName, User $user)
{
$user = $user->where('name', $username)->first();
$blog = $user->blogs->where('name', $blogName)->first();
$this->authorize('edit-blog', $user->id);
return view('blog.edit', compact('user', 'blog'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validated = $request->validate([
'body' => 'required|min:30',
]);
Blog::find($id)->update([
'body' => $request->input('body')
]);
$request->session()->flash('sucsess', 'blog created succsessfully');
return back();
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Request $request, $id)
{
Blog::find($id)->delete();
$request->session()->flash('sucsess', 'blog deleted succsessfully');
return redirect()->route('dashboard');
}
}
I saw questions similar to yours on stack overflow, but none answered my question
pleas help my
try:
$newBlog = $blog->insert(['user_id' => Auth::id(),
'name' => $name,
'body' => $body,
'created_at' => new DateTime,
'updated_at' => new DateTime
]);
$newBlog->tags()->attach(1);
I made a display of the plate on the page of the site and then the following error appeared (error screenshot below) error text:
Undefined variable: users (View: /home/vagrant/code/bacon/resources/views/users.blade.php)
My MainController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MainController extends Controller
{
public function welcome()
{
return view('/welcome');
}
public function users()
{
return view('users');
}
}
My web.php(routes):
<?php
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/welcome', 'App\Http\Controllers\MainController#welcome');
Route::get('/users', 'App\Http\Controllers\MainController#users');
Route::get('/business', 'App\Http\Controllers\BusinessController#index');
Route::post('/business', 'App\Http\Controllers\BusinessController#store');
Route::get('/projects', 'App\Http\Controllers\ProjectsController#index');
Route::post('/projects', 'App\Http\Controllers\ProjectsController#store');
Route::get('/projects/create', 'App\Http\Controllers\ProjectsController#create');
Route::get('/business/create', 'App\Http\Controllers\BusinessController#createbusiness');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
My Model User.php:
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My Controller UsersController.php:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class UsersController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function users()
{
$users = User::all();
return view('users' , ['users' => $users]) ;
}
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function show(Post $post)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function edit(Post $post)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Post $post)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Post $post
* #return \Illuminate\Http\Response
*/
public function destroy(Post $post)
{
//
}
}
My users_table.php:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
My users.blade.php (view page):
#extends('layouts.layout')
#section('title')Користувачі#endsection
#section ('main_content')
<h1>Користувачі</h1>
<p>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Mail</th>
<th scope="col">Business</th>
</tr>
</thead>
<tbody>
#foreach ($users as $singleUsers)
<tr>
<th scope="row">{{ $singleUsers->id}}</th>
<td>{{ $singleUsers->id}}</td>
<td>{{ $singleUsers->name}}</td>
<td>{{ $singleUsers->mail}}</td>
<td>{{ $singleUsers->business}}</td>
</tr>
#endforeach
</tbody>
</table>
</p>
#endsection
my error screenshot
You need to pass $user variable to your view
public function users()
{
$users = User::all();
return view('users' , compact('users')) ;
}
Or
public function users()
{
$users = User::all();
return view('users')->with(compact('users')) ;
}
Or
public function users()
{
$users = User::all();
return view('users' , ['users' => $users]) ;
}
Read more about passing data to views https://laravel.com/docs/8.x/views#passing-data-to-views
I am running into a weird problem of Laravel Nova not being able to persist any of my models. Trying to save a user on a fresh Nova install and using the default User resource created still fails. (Updating a user entry works though).
The error I am getting back when trying to create a new user is:
No query results for model [App\User].
Looking into Laravel Nova Core, the file responsible for this is: vendor/laravel/nova/src/Http/Controllers/ResourceStoreController.php
Inside this function, if I try to manually save a new model
dd((new User())->create(['name' => '', 'email' => '', etc]));
it successfully outputs the model but still doesn't have it saved in the database.
The same code when placed either in Tinker / any of the other web routes, successfully creates a new model and saves it in the DB.
My app\Nova\User.php:
<?php
namespace App\Nova;
use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Fields\Gravatar;
use Laravel\Nova\Fields\Password;
class User extends Resource
{
/**
* The model the resource corresponds to.
*
* #var string
*/
public static $model = 'App\\User';
/**
* The single value that should be used to represent the resource when being displayed.
*
* #var string
*/
public static $title = 'name';
/**
* The columns that should be searched.
*
* #var array
*/
public static $search = [
'id', 'name', 'email',
];
/**
* Get the fields displayed by the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Gravatar::make(),
Text::make('Name')
->sortable()
->rules('required', 'max:255'),
Text::make('Email')
->sortable()
->rules('required', 'email', 'max:254')
->creationRules('unique:users,email')
->updateRules('unique:users,email,{{resourceId}}'),
Password::make('Password')
->onlyOnForms()
->creationRules('required', 'string', 'min:8')
->updateRules('nullable', 'string', 'min:8'),
];
}
/**
* Get the cards available for the request.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function actions(Request $request)
{
return [];
}
}
User Model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My User table migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Any idea what might be tripping up a save operation this way? For additional info my setup is as follows:
Laravel (5.8)
Nova (2.5)
PHP 7.2
MySQL Ver 15.1 Distrib 10.4.6-MariaDB
Turned out the issue was with my MariaDB installation. Having recently upgraded it, I guess there may have been some configuration that caused mayhem. Moving away from MariaDB to MySQL 8 solved the issue.
Do not initialize a new Model class when using mass assignment, call the static method ::create()
\App\User::create(['name' => '', 'email' => '', etc]);
Also make sure that all properties are fillable in the User model
protected $fillable = [
'name', 'email', 'password', // Add the rest
];
or you can do what I do
protected $guarded = []; // yolo
Hope this helps