Lavarel 9 many to many relationship - php

I have three tables: Users, Videogames and videogames_users . How can I display the videogames selected by the users?
This is what I need to achieve (picture 1) but what I’m getting is this (picture 2)
Picture 1
Picture 2
Controller
public function users()
{
$videogamesBuilder = VideoGames::with(['plataforma', 'generos', 'categoria', 'numJugadores', 'users']);
$users = DB::table(users)->select('user_id', 'nombre', 'email','rol_usuario')->get();
$videogames = $videogamesBuilder->paginate(4)->withQueryString();
return view('admin.videojuegos.users', [
'videogames' => $videogames,
'users' => $users,
]);
}
Model
class User extends User
{
use HasApiTokens, Notifiable;
protected $table = 'users';
protected $primaryKey = 'user_id';
protected $fillable = [ 'email', 'nombre', 'password', 'rol_usuario'];
protected $hidden = ['password', 'remember_token'];
public const VALIDATE_RULES = [
'email' => 'required',
'nombre' => 'required|min:5',
'password' => 'required|numeric|min:0',
'rol_usuario' => 'required',
];
}
Migration Videogame
class CreateVideojuegosTable extends Migration
{
public function up()
{
Schema::create('videogames', function (Blueprint $table) {
$table->id('videogame_id');
$table->string('titulo', 300);
$table->text('subtitulo');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('videogames');
}
}
Migration Users
return new class extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id('user_id');
$table->string('email')->unique();
$table->string('nombre');
$table->string('password');
$table->string('rol_usuario');
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
};
Migration Videogames selected by users
return new class extends Migration
{
public function up()
{
Schema::create('videojuegos_tienen_usuarios', function (Blueprint $table) {
$table->foreignId('videogames_id')->constrained('videogames', 'videogames_id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('user_id')->on('users');
$table->primary(['videogames_id', 'user_id']);
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('videojuegos_tienen_usuarios');
}
};
Sedeer
class VideojuegosTienenUsuariosSeeder extends Seeder
{
public function run()
{
\DB::table('videojuegos_tienen_usuarios')->insert([
[
'videojgame_id' => 1,
'user_id' => 1,
'created_at' => now(),
'updated_at' => now(),
],
[
'videojgame_id' => 2,
'user_id' => 1,
'created_at' => now(),
'updated_at' => now(),
],
[
'videojgame_id' => 2,
'user_id' => 2,
'created_at' => now(),
'updated_at' => now(),
],
[
'videojgame_id' => 2,
'user_id' => 3,
'created_at' => now(),
'updated_at' => now(),
],
[
'videojgame_id' => 3,
'user_id' => 1,
'created_at' => now(),
'updated_at' => now(),
]
]);
}
}
view
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Nombre de usuario</th>
<th>Email Usuario</th>
<th>Rol del Usuario</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<td>{{ $user->user_id }}</td>
<td>{{ $user->nombre }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->rol_usuario }}</td>
#endforeach
</tr>
</tbody>
</table>

Your trying to implement a many-to-many relationship, please check: https://laravel.com/docs/9.x/eloquent-relationships#many-to-many
Just follow the table naming structure and add this method to your User model:
public function videogames()
{
return $this->belongsToMany(VideoGame::class);
}
Afterwards you can query the videogames of an user in your view for each user like:
#foreach($users as $user)
<tr>
<td>{{ $user->user_id }}</td>
<td>{{ $user->nombre }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->rol_usuario }}</td>
<td>
#foreach($user->videogames as $game)
{{ $game->titulo }},
#endforeach
</td>
#endforeach

Related

Data from database is not passed to the view.blade in laravel

I am pretty new to Laravel, and I am facing an issue.
I creating a website where users can upload products (modules) to the site and for their product they have to choose a category aswell as subcategory.
Now, I want to create a view.blade which automatically displays all the uploaded products with their corresponding subcategory. So on the roof page I want to display all the uploaded modules with subcategory roof.
However, the view page is loaded but no data is displayed...
I have created a ModulesController:
{ class ModulesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create()
{
return view('modules/create');
}
public function store()
{
$data = request()->validate([
'title' => ['required', 'string', 'max:50'],
'description' => ['required', 'string', 'max:255'],
'price' => ['required', 'string'],
'category' => ['required', 'string'],
'subcategory' => ['required', 'string'],
'image' => ['required', 'image'],
]);
#dd($data);
$imagePath = request('image')->store('uploads', 'public');
$image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
$image->save();
auth()->user()->modules()->create([
'title' => $data['title'],
'description' => $data['description'],
'price' => $data['price'],
'category' => $data['category'],
'subcategory' => $data['subcategory'],
'image' => $imagePath,
]);
return redirect('/profile/' . auth()->user()->id);
}
public function show(\App\Models\Module $module)
{
return view('modules.show', compact('module'));
A corresponding model:
class Module extends Model
{
protected $fillable =[
'title',
'description',
'price',
'category',
'subcategory',
'image',
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
A Module migration database:
class CreateModulesTable extends Migration
{
public function up()
{
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->text('description');
$table->string('price');
$table->string('category');
$table->string('subcategory');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
And I am trying to pass it to this view where I want to show all the images.
I have tried to use this loop but I can't make it work....
#section('content')
<div class="container">
<div class="flex justify-center pt-8 sm:justify-start
sm:pt-0">
<h1>All modules with corresponding subcategory</h1>
#if ( $module["subcategory"] == "dak" )
#foreach ($modules as $module)
<a href="/module/{{ $module->id }}">
<img src="/storage/{{$module->image}}"
class="w-100" alt=""/>
<a/>
#endforeach
#endif
</div>
</div>
#endsection
If anyone can help this would be much appreciated.
P.S. "dak" is a subcategory and means "roof".

Migration for creating join table

There's a table in my SQL DB called "projects" and it has a column in it "categories" which is a varchar(255) representation of a php array "['category_1', 'category_2', 'category_3']" and what i'd like to do is put these categories into a separate table which would be made of a unique integer id in addition to the name of the category and then use a join table to connect it to "projects" in a many-to-many relationship.
So it would be a migration that would perform the following:
Create a join table called "categories_projects"
Create a table called "categories" that would be comprised of just a unique id and the title of the category
Insert into the categories a row for each so "category_1", "category_2", "category_3"
Look for any existing rows in the "projects" table and based on the varchar(255) field "category" mentioned above, create a row in the join table that would connect it to its respective category.
What I have so far:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('parent_id')->nullable();
$table->string('title');
$table->timestamps();
$table->softDeletes();
});
DB::table('categories')->insert(
[
'title' => 'category_1'
], [
'title' => 'category_2'
], [
'title' => 'category_3'
], [
'title' => 'category_4'
], [
'title' => 'category_5'
]
);
Schema::create('categories_projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('category_id');
$table->timestamps();
$table->softDeletes();
});
// This doesn't work but it's a representation of what I'm trying to do
// $categories = DB::rawQuery('select * from categories');
// foreach ($categories as $category) {
// $projects = DB::rawQuery('select * from projects where projects.category like %$category['title']');
// foreach($projects as $project) {
// DB::table(categories_projects)->insert(['project_id' => $project['id'], 'category_id' => $category['id']]);
// }
//
// }
}
Try this one:
If both sides of your categories name in your main table are surrounded by single quotes (such as 'category_1')
$categories = DB::rawQuery("select * from categories");
foreach ($categories as $category) {
$projects = DB::rawQuery("select * from projects where category like '%''" . $category["title"] . "''%' ");
foreach($projects as $project) {
DB::table('categories_projects')->insert(['project_id' => $project['id'], 'category_id' => $category['id']]);
}
}
This is what I ended up going with, it seems like I answered my own question in the process of asking it but anyways:
public function up()
{
Schema::dropIfExists('categories');
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
$table->softDeletes();
});
DB::table('categories')->insert([
['title' => 'Addition'],
['title' => 'Bathrooms'],
['title' => 'Commercial'],
['title' => 'Community'],
['title' => 'Dental'],
['title' => 'Design & Construction'],
['title' => 'Facade'],
['title' => 'Home Design'],
['title' => 'Medical'],
['title' => 'Multi-Family'],
['title' => 'Office'],
['title' => 'Renovation'],
['title' => 'Residential'],
['title' => 'Restaurant'],
['title' => 'Retail'],
['title' => 'Student Housing']
]);
Schema::create('categories_projects', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('project_id');
$table->unsignedInteger('category_id');
$table->timestamps();
$table->softDeletes();
});
$categories = DB::table("categories")->get();
foreach ($categories as $category) {
$category_id = $category->id;
$projects = DB::table('projects')->where('categories', 'like', '%'.$category->title.'%')->get();
$category_proj = [];
foreach ($projects as $project) {
$project_id = $project->id;
$category_proj[] = ['project_id' => $project_id, 'category_id' => $category_id];
}
DB::table('categories_projects')->insert($category_proj);
}
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories_projects');
Schema::dropIfExists('categories');
}

Laravel Soft Deletes dosent work in one table

I am trying to make soft deletes in my DB tables but it fails in one table. I made same things with other tables but only in one it dosen't work. When i click delete in view it deletes row in data base. I will show code of soft delete for this table and have hope that you will help me.
This is my migration for it:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->string('name')->nullable();
$table->string('PKWIU')->nullable();
$table->string('quantity')->nullable();
$table->string('unit')->nullable();
$table->string('netunit')->nullable();
$table->string('nettotal')->nullable();
$table->string('VATrate')->nullable();
$table->string('grossunit')->nullable();
$table->string('grosstotal')->nullable();
$table->timestamps();
$table->time('deleted_at')->nullable();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('form_id')
->references('id')
->on('forms')
->onDelete('cascade');
$table->foreign('currency_id')
->references('id')
->on('currencys')
->onDelete('cascade');
$table->foreign('proform_id')
->references('id')
->on('proforms')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
This is model for invoice. Invoice.php
<?php
namespace App;
use Kyslik\ColumnSortable\Sortable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Invoice extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
use SoftDeletes;
use Sortable;
protected $table = 'invoices';
protected $fillable = [
'invoicenumber', 'invoicedate', 'id', 'selldate', 'user_id', 'paymentmethod',
'paymentdate', 'status', 'comments', 'city', 'paid', 'autonumber', 'automonth', 'autoyear', 'name',
'PKWIU', 'quantity', 'unit', 'netunit', 'nettotal',
'VATrate', 'grossunit', 'grosstotal', 'form_id', 'currency_id',
];
public $sortable = [ 'invoicenumber', 'invoicedate', 'id', 'selldate',
'user_id', 'paymentmethod', 'paymentdate', 'status', 'comments', 'grosstotal', 'nettotal', 'form_id', 'currency_id',];
protected $dates = ['deleted_at'];
public $primaryKey = 'id';
public function user()
{
return $this->belongsTo('App\User');
}
public function form()
{
return $this->hasOne('App\Form');
}
public function currency()
{
return $this->hasOne('App\Currency');
}
public function proform()
{
return $this->belongsTo('App\Proform');
}
}
InvoiceController.php
<?php
namespace App\Http\Controllers;
use Kyslik\ColumnSortable\Sortable;
use App\Invoice;
use Illuminate\Http\Request;
use App\User;
use App\Proform;
use App\Form;
use App\Currency;
use DB;
class InvoiceController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
function __construct()
{
$this->middleware('permission:product-list|product-create|product-edit|product-delete', ['only' => ['index','show']]);
$this->middleware('permission:product-create', ['only' => ['create','store']]);
$this->middleware('permission:product-edit', ['only' => ['edit','update']]);
$this->middleware('permission:product-delete', ['only' => ['destroy']]);
}
public function search4(Request $request)
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
$query = DB::table('users')
->join('invoices', 'users.id', '=', 'invoices.user_id');
$search = $request->get('search');
$requestData = ['showname'];
/* $query = Proform::query(); */
foreach ($requestData as $field){
$query->orWhere($field, 'like', '%'.$search.'%');
}
$data2=$query->paginate(5);
return view('invoices.index', ['invoices' => $data2, 'user'=> $user])->with('i', ($request->input('page', 1) - 1) * 5);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user = User::all('showname','id');
$invoices = Invoice::sortable()->paginate(5);
return view('invoices.index',compact('invoices', 'user'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{ $users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.create')->with('users', $users, 'forms', 'currencys');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
Invoice::create($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice created successfully.');
}
/**
* Display the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function show(Invoice $invoice)
{
return view('invoices.show',compact('invoice'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function edit(Invoice $invoice)
{
$users = User::all('showname','id');
$forms = Form::all('id', 'form');
$currencys = Currency::all('id', 'currency', 'course');
return view('invoices.edit',compact('invoice', 'users', 'forms', 'currencys'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Invoice $invoice)
{
request()->validate([
'invoicedate' => 'required',
'user_id' => 'required',
'selldate' => 'required',
'paymentdate' => 'required',
'paymentmethod' => 'required',
'status' => 'required',
'comments' => 'nullable',
'city' => 'nullable',
'paid' => 'nullable',
'name' => 'required',
'PKWIU' => 'nullable',
'quantity' => 'required',
'unit' => 'required',
'netunit' => 'required',
'nettotal' => 'required',
'VATrate' => 'required',
'grossunit' => 'required',
'grosstotal' => 'required',
]);
$invoice->update($request->all());
return redirect()->route('invoices.index')
->with('success','Invoice updated successfully');
}
/**
* Remove the specified resource from storage.
*
* #param \App\Product $product
* #return \Illuminate\Http\Response
*/
public function destroy(Invoice $invoice)
{
$invoice->delete();
return redirect()->route('invoices.index')
->with('success','Invoice deleted successfully');
}
}
Routes:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function(){
return view('welcome');
});
Route::get('home');
/*
|--------------------------------------------------------------------------
| 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!
|
*/
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth']], function () {
Route::get('/search', 'UserController#search');
Route::get('/search2', 'ProductController#search2');
Route::get('/search3', 'ProformController#search3');
Route::get('/search4', 'InvoiceController#search4');
Route::post('/duplicate', 'ProformController#duplicate')->name('proforms.duplicate');
Route::get('data', 'UserController#index');
Route::get('posts', 'PostController#index');
Route::get('/prodview', 'TestController#prodfunct');
Route::resource('roles', 'RoleController');
Route::resource('users', 'UserController');
Route::resource('permissions', 'PermissionController');
Route::resource('products', 'ProductController');
Route::resource('invoices', 'InvoiceController');
Route::resource('category', 'CategoryController');
Route::resource('invoices', 'InvoiceController');
Route::resource('proforms', 'ProformController');
});
View:
#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Zarządzanie fakturami</h2>
</div>
<div class="col-md-4">
<form action="/search4" method="get">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-prepend">
<button type="submit" class="btn btn-primary">Wyszukaj</button>
</span>
</div>
</form>
</div>
<div class="pull-right">
#can('product-create')
<a class="btn btn-success" href="{{ route('invoices.create') }}"> Utwórz nową fakturę</a>
#endcan
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th scope="col">#sortablelink('id', 'Numer')</th>
<th scope="col">#sortablelink('invoicnumber', 'Numer faktury')</th>
<th scope="col">#sortablelink('invoicedate', 'Data wystawienia')</th>
<th scope="col">#sortablelink('user_id', 'Kontrachent')</th>
<th scope="col">#sortablelink('selldate', 'Data sprzedaży')</th>
<th scope="col">#sortablelink('paymentdate', 'Termin płatności')</th>
<th scope="col">#sortablelink('status', 'Status')</th>
<th scope="col">#sortablelink('nettotal', 'Netto razem')</th>
<th scope="col">#sortablelink('grosstotal', 'Brutto razem')</th>
<th width="280px">Akcja</th>
</tr>
#foreach ($invoices as $invoice)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $invoice->invoicenumber }}</td>
<td>{{ $invoice->invoicedate }}</td>
<td>{{ $invoice->user->showname ?? $invoice->showname }}</td>
<td>{{ $invoice->selldate }}</td>
<td>{{ $invoice->paymentdate }}</td>
<td>{{ $invoice->status }}</td>
<td>{{ $invoice->nettotal }}</td>
<td>{{ $invoice->grosstotal }}</td>
<td>
<form action="{{ route('invoices.destroy',$invoice->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('invoices.show',$invoice->id) }}">Więcej</a>
#can('product-edit')
<a class="btn btn-primary" href="{{ route('invoices.edit',$invoice->id) }}">Edytuj</a>
#endcan
#csrf
#method('DELETE')
#can('product-delete')
<button type="submit" class="btn btn-danger">Usuń</button>
#endcan
</form>
</td>
</tr>
#endforeach
</table>
{!! $invoices ?? ''->appends(request()->except('page'))->render() !!}
<p class="text-center text-primary"><small>ARTplus 2020</small></p>
#endsection
You must to use $table->softDeletes(); instead of $table->time('deleted_at')->nullable();.
softDeletes() method used timestamp instead of time format date. Maybe it will solve your problem;

Laravel: Integrity constraint violation

I'm studying some Laravel and at some point I had to re-migrate the database because I had to change a table. I'm using postman to do testing, and one of the api methods give me the error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: events.user_id (SQL: insert into "events" ("sport", "title", "players", "when", "description", "location", "updated_at", "created_at") values (Hockey, Grass Hockey, 12, 30/09/2018, Come join us, Fairview park, 2018-11-08 22:19:45, 2018-11-08 22:19:45))
so it seems to be a problem with the events.user_id which I changed on a table called Events to have a relationship with the Users table. Some examples I found by researching is on table fields that were not ids, so I don't how to figure this one out, maybe some of you can help me!
here are the migrations for Events and Users:
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->string('sport');
$table->string('title');
$table->decimal('players', 8, 2);
$table->date('when');
$table->mediumText('description');
$table->string('location');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Here are the models:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location'
];
public function user()
{
return $this->belongsTo('App\User');
}
class User extends Authenticatable
{
use HasApiTokens, 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',
];
public function events()
{
return $this->hasMany('App\Event');
}
}
And below is the api method that is giving me the error:
Route::post('/admin/create-event', function (Request $request) {
$data = $request->all();
$event = Event::create(
[
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
Thanks guys!
Edit:
Route::middleware('auth:api')->post('/admin/create-event', function (Request $request) {
$user = $request->user();
$data = $request->all();
$event = Event::create(
[
'user_id' => \Auth::user()->id,
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
I think you have to add 'user_id' to $fillable of Event class:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
You need to pass the user_id:
'user_id' => \Auth::user()->id
The example above requires an authenticated user in the session, but if you are making the request using postman you probably don’t have one.
Anyway, you need to provide the user_id that will be stored in the database.
EDIT
Eloquent's method create will copy to the model only the attributes defined as fillable. So you have two options:
Add user_id to $fillable
Use newInstance instead of create, manually set the user_id with $event->user_id = ..., and manually save the $event model with $event->save();

Laravel 5.1 - Get data from 2 relations table

i'm doing a ecommerce, i created a resource controller for ORDERS. But i have some problem to get information about the products. i would like show all items orders with information about the products buyed, like name, price, category. Each order item have a "product_id" relation.
i have this tables migration:
Orders
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->increments('id');
$table->decimal('subtotal', 5, 2);
$table->decimal('shipping', 5,2);
$table->text('method');
$table->text('status');
$table->text('order_code');
$table->text('fullname_ship');
$table->text('address_ship');
$table->text('app_ship');
$table->text('province_ship');
$table->text('country_ship');
$table->text('email_ship');
$table->text('phone_ship');
$table->text('fullname_bill');
$table->text('address_bill');
$table->text('app_bill');
$table->text('province_bill');
$table->text('country_bill');
$table->text('email_bill');
$table->text('phone_bill');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('orders');
}
}
Orders items
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrderItemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders_items', function (Blueprint $table) {
$table->increments('id');
$table->decimal('price', 5, 2);
$table->integer('quantity')->unsigned();
$table->integer('product_id')->unsigned();
$table->foreign('product_id')
->references('id')
->on('products')
->onDelete('cascade');
$table->integer('order_id')->unsigned();
$table->foreign('order_id')
->references('id')
->on('orders')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('order_items');
}
}
Products table
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
//Up creare table
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 255);
$table->string('slug');
$table->text('description');
$table->string('extract', 300);
$table->decimal('price', 5, 2);
$table->string('image', 300);
$table->boolean('visible');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->integer('category_id')->unsigned();
// relazioni
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
//crea // Ogni prodotto ha un autore( artista)
// ----//
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
//eliminare table
public function down()
{
Schema::drop('products');
}
}
My OrderController.php
<?php
namespace dixard\Http\Controllers\Admin;
use Illuminate\Http\Request;
use dixard\Http\Requests;
use dixard\Http\Controllers\Controller;
use dixard\Order;
use dixard\OrderItem;
use dixard\Product;
use dixard\Category;
use Validator;
class OrderController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$orders = Order::orderBy('id')->paginate(15);
return view('admin.order.index', compact('orders'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view ('admin.order.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$rules = [
'status' => 'required',
'method' => 'required',
'order_code' => 'required',
'fullname_ship' => 'required',
'address_ship' => 'required',
'app_ship' => 'required',
'province_ship' => 'required',
'country_ship' => 'required',
'email_ship' => 'required',
'phone_ship' => 'required',
];
$messages = [
'status.required' => 'Status ordine richiesto',
'method.required' => 'Metodo di pagamento richiesto',
'order_code.required' => 'Codice ordine richiesto',
'fullname_ship.required' => 'Nome e cognome richiesto',
'address_ship.required' => 'Indirizzo spedizione richiesto',
'app_ship.required' => 'App/Interno richiesto',
'province_ship.required' => 'Città/Provincia di spedizione richiesto',
'country_ship.required' => 'Paese di spedizione richiesto',
'email_ship.required' => 'Email campo richiesto',
'phone_ship.required' => 'Cellulare/spedizione richiesto',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect('admin/order/create')->withErrors($validator);
}else {
$data = [
'status' => $request->get('status'),
'method' => $request->get('method'),
'order_code' => $request->get('order_code'),
'shipping' => $request->get('shipping'),
'subtotal' => $request->get('subtotal'),
'fullname_ship' => $request->get('fullname_ship'),
'address_ship' => $request->get('address_ship'),
'app_ship' => $request->get('app_ship'),
'province_ship' => $request->get('province_ship'),
'country_ship' => $request->get('country_ship'),
'email_ship' => $request->get('email_ship'),
'phone_ship' => $request->get('phone_ship'),
'fullname_bill' => $request->get('fullname_bill'),
'address_bill' => $request->get('address_bill'),
'app_bill' => $request->get('app_bill'),
'province_bill' => $request->get('province_bill'),
'country_bill' => $request->get('country_bill'),
'email_bill' => $request->get('email_bill'),
'phone_bill' => $request->get('phone_bill'),
];
$order = Order::create($data);
return redirect('admin/order')->with('message', 'Ordine creato!');
}
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show(Order $order)
{
$items = OrderItem::orderBy('id', 'desc')->paginate(20);
$items_product_id = $items->product_id;
$items_products=Product::with('items_product_id')->get();
//$products = Product::where('id', $items->product_id)->orderBy('id', 'desc');
return view('admin.order.show', compact('items','items_products'));
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit(Order $order)
{
return View('admin.order.edit', compact('order'));
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Order $order)
{
$id= $order->id;
$rules = [
'status' => 'required',
'order_code' => 'required',
'shipping' => 'required',
'subtotal' => 'required',
'fullname_ship' => 'required',
'address_ship' => 'required',
'app_ship' => 'required',
'province_ship' => 'required',
'country_ship' => 'required',
'email_ship' => 'required',
'phone_ship' => 'required',
];
$messages = [
'status.required' => 'Status ordine richiesto',
'order_code.required' => 'Codice ordine richiesto',
'shipping.required' => 'Costo spedizione richiesto',
'subtotal.required' => 'Totale costo prodotti - SUBTOTAL richiesto',
'fullname_ship.required' => 'Nome e cognome richiesto',
'address_ship.required' => 'Indirizzo spedizione richiesto',
'app_ship.required' => 'App/Interno richiesto',
'province_ship.required' => 'Città/Provincia di spedizione richiesto',
'country_ship.required' => 'Paese di spedizione richiesto',
'email_ship.required' => 'Email campo richiesto',
'phone_ship.required' => 'Cellulare/spedizione richiesto',
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()){
return redirect()->route('admin.order.edit', $id)->withErrors($validator)->withInput();
}
// if there is not any error go to update
else{
// if email id different by input, so if email input update also email
$s = new Order;
$data = array(
'status' => $request->get('status'),
'method' => $request->get('method'),
'order_code' => $request->get('order_code'),
'shipping' => $request->get('shipping'),
'subtotal' => $request->get('subtotal'),
'fullname_ship' => $request->get('fullname_ship'),
'address_ship' => $request->get('address_ship'),
'app_ship' => $request->get('app_ship'),
'province_ship' => $request->get('province_ship'),
'country_ship' => $request->get('country_ship'),
'email_ship' => $request->get('email_ship'),
'phone_ship' => $request->get('phone_ship'),
'fullname_bill' => $request->get('fullname_bill'),
'address_bill' => $request->get('address_bill'),
'app_bill' => $request->get('app_bill'),
'province_bill' => $request->get('province_bill'),
'country_bill' => $request->get('country_bill'),
'email_bill' => $request->get('email_bill'),
'phone_bill' => $request->get('phone_bill'),
);
$s->where('id', '=', $request->get('id'))->update($data);
return redirect('admin/order')->with('message', 'Ordine aggiornato con successo!');
}
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy(Order $order)
{
$deleted=$order->delete();
if(isset($deleted))
{
return redirect('admin/order')->with('message', 'Ordine eliminato con successo!');
} else {
return redirect('admin/order')->with('message-error', 'Ordine non eliminato');
}
}
}
I created the view show.blade.php to show all items ordered, i would like show all items with information about the products, like name, price, category. Each order item have a "product_id" relation.
i'm trying so in show.blade.php:
#foreach($items as $item)
<tr class="even pointer">
<td class=" ">{{ $item->id }}</td>
<td class=" ">{{ $item->product_id }}</td>
<td class=" ">{{ $item->quantity }}</td>
<td class=" ">€{{ $item->order_id }}</td>
</td>
</td>
</tr>
#endforeach
#foreach($items_products as $items_product)
<tr class="even pointer">
<td class=" ">{{ $items_product->id }}</td>
<td class=" ">{{ $items_product->name }}</td>
<td class=" ">{{ $items_product->price }}</td>
<td class=" ">€{{ $items_product->description }}</td>
</td>
</td>
</tr>
#endforeach
But it doesnt work. Thank you for your help! if you need models:
Product MODEL
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\User;
use dixard\Category;
use dixard\OrderItem;
class Product extends Model
{
protected $table = 'products';
protected $fillable =
[
'name',
'slug',
'description',
'extract',
'image',
'visible',
'price',
'category_id',
'user_id'
];
public function user() {
return $this->belongsTo('dixard\User');
}
public function category() {
return $this->belongsTo('dixard\Category');
}
public function OrderItem() {
return $this->belongsTo('dixard\OrderItem');
}
}
Order items MODEL
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
use dixard\Product;
class OrderItem extends Model
{
// DIrgli che ci lascia scrivere
protected $table = 'orders_items';
protected $fillable = [
'price',
'quantity',
'product_id',
'order_id'
];
public $timestamps = false;
public function product()
{
return $this->hasMany('dixard\Product');
}
}
Order MODEL
<?php
namespace dixard;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
// DIrgli che ci lascia scrivere
protected $table = 'orders';
// gli dico che voglio scrivere questo campi
protected $fillable = [
'subtotal',
'shipping',
'method',
'status',
'order_code',
'fullname_ship',
'address_ship',
'app_ship',
'province_ship',
'country_ship',
'email_ship',
'phone_ship',
'fullname_bill',
'address_bill',
'app_bill',
'province_bill',
'country_bill',
'email_bill',
'phone_bill',
];
}

Categories