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.
Related
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 want to create many to many relationships between user and schedule
This is my user model
<?php
namespace App\Models;
use App\Models\Major;
use App\Models\Score;
use App\Models\Schedule;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $guarded=['id'];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function getRouteKeyName()
{
return 'name';
}
public function score(){
return $this->hasMany(Score::class);
}
public function major(){
return $this->hasOne(Major::class,'id','major_id');
}
public function schedule(){
return $this->belongsToMany(Schedule::class,'schedule_user','user_id','schedule_id');
// 'schedule_user','user_id','schedule_id'
}
protected function type(): Attribute
{
return new Attribute(
get: fn ($value) => ["mahasiswa", "dosen","admin"][$value],
);
}
}
this is my schedule model
<?php
namespace App\Models;
use App\Models\User;
use App\Models\Course;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Schedule extends Model
{
use HasFactory;
protected $guarded=['id'];
public function course(){
return $this->belongsTo(Course::class);
}
public function user(){
return $this->belongsToMany(User::class,'schedule_user','schedule_id','user_id');
}
}
create_users_table
<?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->unsignedBigInteger('major_id');
$table->foreignId('major_id')->constrained('majors');
// $table->foreign('major_id')->references('id')->on('majors');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password')->default('password123');
$table->bigInteger('nrp');
$table->string('address');
$table->integer('generation');
$table->integer('type')->default(0);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
create_schedules_table
<!-- create_schedules_table -->
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSchedulesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedules', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users')->nullable();
$table->foreignId('course_id')->constrained('courses')->nullable();
$table->timestamps();
$table->string('Hari');
$table->string('Jam');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('schedules');
}
}
create_schecule_user_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateScheduleUserTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('schedule_user', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->foreignId('user_id')->constrained('users')->nullable();
$table->foreignId('schedule_id')->constrained('schedules')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('schedule_user');
}
}
here is my controller.. i try to show the user schedule where user's id=1
<?php
namespace App\Http\Controllers;
use App\Models\Schedule;
use App\Models\User;
use Illuminate\Http\Request;
class ScheduleController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
$user=User::find(1);
return view('schedule.index',[
'title'=>'Jadwal Kuliah',
'schedules'=>$user->schedule
]);
}
/**
* 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\Schedule $schedule
* #return \Illuminate\Http\Response
*/
public function show(Schedule $schedule)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Schedule $schedule
* #return \Illuminate\Http\Response
*/
public function edit(Schedule $schedule)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Schedule $schedule
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Schedule $schedule)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Schedule $schedule
* #return \Illuminate\Http\Response
*/
public function destroy(Schedule $schedule)
{
//
}
}
and here's the schedule.index
#extends('dashboard.layouts.main')
#section('container')
<h3>schedule Kuliah {{auth()->user()->name}}</h3>
<table class="table align-items-center justify-content-center mb-0">
<thead>
<tr>
<th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Mata Kuliah</th>
<th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Hari</th>
<th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Jam</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($schedules as $schedule)
<tr>
<td>
<div class="d-flex px-2">
<div class="my-auto">
<h6 class="mb-0 text-sm">{{$schedule->course->nama_mata_kuliah}}</h6>
</div>
</div>
</td>
<td>
<p class="text-sm font-weight-bold mb-0">{{ $jadwak->hari }}</p>
</td>
<td>
<span class="text-xs font-weight-bold">{{ $schedule->jam }}</span>
</td>
</tr>
#endforeach
</tbody>
</table>
#endsection
the view not displaying any user's schedule. When i check in the terminal using php artisan tinker, the Schedule::first()->user returned: all:[]
If it is many to many relationships, I think this won't work
$schedule->course->nama_mata_kuliah
Because $schedule will return an array of the related objects not a single object even if we have only one schedule related to the user.
You have to use the loop on
foreach($user->schedule as $sch) {
//do something.
}
One suggestion if you have a many-to-many relationship, is advised to give a plural name to your relation function.
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.
// ...
}
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 trying to run php artisan migrate:fresh to publish a modification to my seeder. It partially worked, it removed all of the tables in the database but it won't recreate them because Table 'database.themes' does not exist. I have included my Themes.php model, my ThemesController.php and any other resources requiring Themes below to hopefully make sense of this.
2020_11_14_125914_create_themes_table (Migration)
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateThemesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('themes', function (Blueprint $table) {
$table->id('theme_id');
$table->string('theme_title')->default('Main');
$table->string('theme_slug')->default('main')->unique();
$table->text('theme_description')->nullable();
$table->string('theme_uri')->default('laravel.cmsbase.com')->nullable();
$table->string('theme_version')->default('1.0.0')->nullable();
$table->string('theme_license')->default('The MIT License (MIT)')->nullable();
$table->string('theme_tags')->nullable();
$table->string('theme_type')->default('web');
$table->string('author_name')->default('Spencer K Media');
$table->string('author_uri')->nullable();
$table->boolean('is_theme')->default(1)->nullable();
$table->timestamps();
});
DB::table('themes')->insert([
'theme_id' => '1',
'theme_title' => 'Core theme',
'theme_slug' => 'main',
'theme_description' => 'Default theme for the theme package',
'theme_uri' => 'https://laravel.cmsbase.com',
'theme_version' => '1.0.0',
'theme_license' => 'The MIT License (MIT)',
'theme_tags' => 'default, simple, base',
'theme_type' => 'web',
'author_name' => 'Spencer K Media',
'author_uri' => 'https://spencerkmedia.com',
'is_theme' => 1,
]);
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('themes');
}
}
Themes.php (Model)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Themes extends Model
{
use HasFactory;
protected $fillable = ['theme_title', 'theme_slug', 'theme_uri', 'theme_version', 'theme_license', 'theme_tags', 'theme_type', 'author_name', 'author_uri', 'is_theme'];
}
ThemesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Themes;
use Carbon\Carbon;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
class ThemeSettingsController extends Controller
{
public $themes;
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$themes = Themes::get();
return view('admin.settings.theme', compact('themes'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function activate()
{
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request, $theme, $json)
{
// Get the path of theme.json
$path = glob("/resources/views/themes/{,*/}theme.json", GLOB_BRACE);
// Parse the json file into array with $json
$json = json_decode(file_get_contents($path), true);
var_dump($json);
$this->validate($request, [
'is_theme' => 'accepted'
]);
$theme = new Themes();
$theme->theme_title = $json->theme_title;
$theme->theme_slug = strtolower($json->theme_title);
$theme->theme_description = $json->theme_description;
$theme->theme_uri = $json->theme_uri;
$theme->theme_version = $json->theme_version;
$theme->theme_license = $json->theme_license;
$theme->theme_tags = $json->theme_tags;
$theme->theme_type = $json->theme_type;
$theme->author_name = $json->author_name;
$theme->author_uri = $json->author_uri;
$theme->is_theme = $request->is_theme;
$theme->save();
notify()->success('Theme successfully enabled :)', 'Success');
return redirect()->back();
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($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)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
RouteServiceProvider
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use App\Models\Themes;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* #var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$settings = Themes::get();
$this->configureRateLimiting();
$this->routes(function () use ($settings) {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes\api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes\web.php'));
foreach ($settings as $key => $setting) {
Route::middleware('web')
->group(base_path('resources/views/themes/' . $setting->theme_slug . '/route.php'));
}
});
}
/**
* Configure the rate limiters for the application.
*
* #return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60);
});
}
}
Web.php (Route File)
Route::prefix('settings')->name('settings.')->group(function () {
Route::get('/home', function () {
return view('admin.settings.index');
})->name('index');
Route::get('/general', function () {
return view('admin.settings.general');
})->name('general');
Route::get('/site', function () {
return view('admin.settings.site');
})->name('site');
Route::get('/theme', function () {
return view('admin.settings.theme');
})->name('theme');
});
Any help is appreciated and thank you in advance!
Laravel runs Providers before the command on artisan commands, so its trying to $settings = Themes::get(); on RouteServiceProvider and failing, thus the error. For a temporary fix remove that code and then run the migrate command.
For a more permanent fix, you can check if the model/table exists before running the query:
public function boot()
{
if($settings = Themes::get()){
$this->configureRateLimiting();
$this->routes(function () use ($settings) {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes\api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes\web.php'));
foreach ($settings as $key => $setting) {
Route::middleware('web')
->group(base_path('resources/views/themes/' . $setting->theme_slug . '/route.php'));
}
});
}
}