Laravel error Column not found - php

Error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.id' in 'where clause' (SQL: select * from products where products.id = 1 limit 1)
I do have table 'products' with a 'product.id' field. Not sure why I am getting this error. I get this error when I
access /product/{{product_id}}
access /edit
Home Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('home')->with('products',$user->products);
}
}
ProductController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\product;
class productController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth',['except' => ['index','show']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$products = product::orderBy('created_at','desc')->paginate(10);
//$products = product::where('type','major')->get();
return view('products.index')->with('products',$products);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required',
]);
//create product
$product = new product;
$product->title = $request->input('title');
$product->venue = $request->input('venue');
$product->city = $request->input('city');
$product->country = $request->input('country');
$product->description = $request->input('description');
$product->date = $request->input('date');
$product->user_id = auth()->user()->id;
$product->save();
return redirect('/products')->with('success','product Created');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$product = product::find($id);
return view('products.show');
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = product::find($id);
return view('products.edit')->with('product',$product);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'title' => 'required'
]);
$product = product::find($id);
$product->title = $request->input('title');
$product->save();
return redirect('/products')->with('success','product updated');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$product = product::find($id);
$product->delete();
return redirect('/products')->with('success','product deleted');
}
}
Show.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<h1 class="centre">{{$product->title}}</h1>
<div class="well-xs">
#if(!Auth::guest())
#if(Auth::user()->id == $product->user_id)
Edit
{!!Form::open(['action' => ['productcontroller#destroy', $product->product_id], 'method' => 'POST'])!!}
{{Form::hidden('_method', 'DELETE')}}
{{Form::submit('Delete', ['class' => 'btn btn-danger'])}}
{!!Form::close()!!}
#endif
#endif
</div>
<div>
<div>
<h4>product Date: {{$product->date}}</h4>
<h4>product Venue: {{$product->venue}}</h4>
<h4>product Location:{{$product->city}}</h4>
<h4>product Description: </h4>
<p>{{$product->description}} </p>
</div>
</div>
<hr>
Written on
</hr>
</div>
#endsection
Products table schema: I added user_id manually in sql. migrate wasnt working when I tried making a separate migration to add_user_id_to_table
{
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('title',200);
$table->string('venue',200);
$table->text('city',200);
$table->text('country',200);
$table->string('description');
$table->date('date',200);
$table->timestamps();
});
}
user.php model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
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',
];
public function products(){
return $this->hasMany('App\Product');
}
}
Product.php model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//Table NAME
protected $table = 'products';
//PRIMARY KEY
public $primaryKey = 'id';
//Timestamps
public $timestamps =true;
public function user(){
return $this->belongsTo('App\User');
}
}

When you modify your migrations, you still need to update the database. So you should try
php artisan migrate:fresh
That will erase your database and migrate it again
Also, you don't need to query for the current user in your controller
Instead of this:
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('home')->with('products',$user->products);
}
You can simply use:
public function index()
{
return view('home')->with('products', auth()->user()->products);
}
EDIT:
Your products migration doesn't have a column called id defined but product_id instead.
Also, you're declaring a belongsTo relation in product to user while you don't have the id of the user on that table.
A relation belongsTo means that you have the id of the related model. For example
class User extends Model
{
public function posts()
{
return $this->hasMany(App\Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this-belongsTo(App\User::class);
}
}
This is possible because posts table has a field called user_id. Because a Post belongs to a user.
You don't need this code:
//Table NAME
protected $table = 'products';
//PRIMARY KEY
public $primaryKey = 'id';
//Timestamps
public $timestamps =true;
Laravel handle all of that automatically, you're defining the default values

Change in your User model
public function products(){
return $this->hasMany("App\Product","product_id","product_id");
//return $this->hasMany("App\Product","foreign_key","local_key");
}

Related

i want attach to tags but i get error Call to a member function attach() on null

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);

Column not found: 1054 Unknown column 'users.blog_id' :SQL: select * from `users` where `users`.`blog_id` = 1 and `users`.`blog_id` is not null

blogsIndex.blade.php
#extends('layouts.default')
#section('details')
<div class="container">
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
Hello <strong> {{auth()->user()->name}}</strong> !!! You can not find blogs from another Departments.
</div>
</div>
#endsection
#section('gotoLogins')
#if(count($blogs) > 0)
#foreach($blogs as $blog)
<div class="container-fluid">
<div class="card">
<div class="card-body ">
<div class="col-md-8 col-sm-8">
<h3><a style="color:#3e3d8c;" href="/blogs/{{$blog->id}}">{{$blog->title}}</a></h3>
<footer class ="blockquote-footer">
<small>Written on {{$blog->created_at}} by: {{$blog->user->name}}</small>
</footer>
</div>
</div>
</div>
</div>
#endforeach
#else
<p>No blogs found</p>
#endif
#endsection
blogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
class blogController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth', ['except' => ['index']]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$blog =Blog::orderBy('created_at','desc')->get();
return view('pages.blogsIndex')->with('blogs',$blog);
}
/**
* 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 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)
{
//
}
}
model : Blog.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
//table name
protected $table = 'students_blog';
//Primary key
public $primaryKey = 'id';
//Timestamp
public $timestamp = true;
public function user(){
return $this->hasMany('App\User');
}
}
Model: User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','roll',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function feeds(){
return $this->hasMany('App\Feed');
}
public function blogs(){
return $this->hasMany('App\Blog');
}
public function mentor(){
return $this->belongsTo('App\Mentor');
}
}
Route: Web.php
<?php
/*
|--------------------------------------------------------------------------
| 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('/', 'pagesController#index');
Route::post('/student', 'studentsFeedController#store')->name('student.feed.submit');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('blogs', 'blogController');
Route::prefix('mentor')->group(function(){
Route::get('/register', 'Auth\MentorLoginController#showSignupForm')->name('mentor.signup');
Route::post('/register', 'Auth\MentorLoginController#signupFormSubmit')->name('mentor.signup.submit');
Route::get('/login', 'Auth\MentorLoginController#showLoginForm')->name('mentor.login');
Route::post('/login', 'Auth\MentorLoginController#login')->name('mentor.login.submit');
Route::get('/', 'MentorController#index')->name('mentor.dashboard');
});
TABLE details: there is two table one is the usual "users" table. and "students_blog" has a column name 'student_id'. i can get the student_id in my view by {{$blog->student_id}} but i want name. written on ... after by: ??
please help me.
Change this relationship:
public function user(){
return $this->hasMany('App\User');
}
To:
public function user()
{
return $this->belongsTo('App\User', 'student_id');
}
Then to get blog owner's name:
$blog->user->name

how to access relationship and pass into a view in laravel

a beginner question here, how can i get the building_name column on my buildings table which has a relationship with information, i wanted to access it inside the show function and display in on the show.views? And i also wanted to know how can i call it inside the show view Please help.
<?php
namespace App\Http\Controllers;
use App\Information;
use App\Building;
use Illuminate\Http\Request;
use Session;
class InformationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$buildings = new Building();
$buildings::all();
return view('create', compact('buildings'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, array(
'building_information' => 'required',
'building_id' => 'required'
));
//store in the db
$information = new Information;
$information->building_information = $request->building_information;
$information->building_id = $request->building_id;
$information->save();
Session::flash('success', 'The information was successfully saved!');
//redirect to other page
return redirect()->route('information.show', $information->id);
}
/**
* Display the specified resource.
*
* #param \App\Information $information
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$information = Information::find($id);
return view('show')->with('information', $infomation);
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
public function information()
{
return $this->hasMany('App\Information');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Information extends Model
{
public function building()
{
return $this->belongsTo('App\Building');
}
}
Load the relationship too when getting the Information object:
$information = Information::with('building')->find($id);
If there are multiple buildings associated, you can loop through them in your blade view:
#foreach( $information->building as $building)
<li>{{ $building->building_name }}</li>
#endforeach
Just add relationship and pass it to the view
public function show($id)
{
$information = Information::with('building')->findOrFail($id);
return view('show')->with('information', $infomation);
}
In your view:
{{$information->building->building_name}}

HasMany Eloquent relation in laravel 5.4

I try to get the number of logged user posts count so it shows to logged user for example how many post or comment they published so far:
What I have so far is author_id column in posts table which will refer to user id
This is my Post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function author() {
return $this->belongsTo('App\User');
}
}
and this is my User model:
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'role_id',
'email',
'password',
'name',
'avatar',
'remember_token',
'created_at',
'updated_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany('Post', 'author_id');
}
}
This is my PostController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Auth;
use App\User;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(15);
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
return view('theme.index', compact('posts', 'countTodayOrders'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function single($slug) {
$post = Post::where('slug', '=', $slug)->first();
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
return view('theme.single', compact('post', 'countTodayOrders'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
}
Anyone knows what is my mistake and how to fix it?
Well i figure it out :)
i ignored all model roles and directly used controller inserted data from Database and compare it with user id if it's true (same) will return the number.
here is the code for you if you need it PostController:
public function index()
{
$posts = Post::orderBy('created_at', 'desc')->paginate(15);
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
$postscount = DB::table('posts')
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('users')
->whereRaw('author_id = id');
})
->get();
return view('theme.index', compact('posts', 'countTodayOrders', 'postscount'));
}

Why is saving many to many relationship in laravel only saving the first item of the collection?

Currently I am creating an API in laravel. The models are as follows:
Offer
Offer belongsToMany Days
Day
Day belongsToMany Offers
Type
BelongsTo Offer
Models for days and offers:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Offer extends Model
{
/**
* The database table used by the model.
*
* #var string
*/
use SoftDeletes;
protected $table = 'offers';
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $hidden = ['map_location', 'regular', 'name', 'distance_to_offer'];
protected $fillable = ['id','venue_id','type_id','day','venue_address','is_featured','repeater_days','image', 'venue_description', 'offer_headline','offer_subheader','offer_terms','venue_phone_number','venue_website', 'venue_name', 'venue_headline','venue_description','venue_latitude','venue_longitude','offer_when','offer_end_time','offer_start_time','offer_start_date','offer_end_date','featured_date','current_time','current_date'];
public static $rules = array(
'image' => 'image|mimes:jpeg,jpg,png,bmp,gif,svg'
);
protected $casts = [
'is_featured' => 'boolean',
'is_regular' => 'boolean',
'offer_when' => 'array'
];
/**
* Get the offers for the offer.
*/
public function days()
{
return $this->belongsToMany('App\Day','day_offer', 'offer_id', 'day_id');
}
public function types()
{
return $this->belongsToMany('App\Type', 'offer_type');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Day extends Model
{
/**
* Get the offer days for the offer.
*/
public function offers()
{
return $this->belongsToMany('App\Offer');
}
}
In the database we have days, offers and types. We have the following pivot tables for the relationships:
day_offer
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDayOfferPivotTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('day_offer', function (Blueprint $table) {
$table->integer('day_id')->unsigned()->index();
$table->foreign('day_id')->references('id')->on('days')->onDelete('cascade');
$table->integer('offer_id')->unsigned()->index();
$table->foreign('offer_id')->references('id')->on('offers')->onDelete('cascade');
$table->primary(['day_id', 'offer_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('day_offer');
}
}
offer_type:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOfferTypePivotTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('offer_type', function (Blueprint $table) {
$table->integer('offer_id')->unsigned()->index();
$table->foreign('offer_id')->references('id')->on('offers')->onDelete('cascade');
$table->integer('type_id')->unsigned()->index();
$table->foreign('type_id')->references('id')->on('types')->onDelete('cascade');
$table->primary(['offer_id', 'type_id']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('offer_type');
}
}
In my OffersController I have the standard methods of create, store, update etc and when in the create method I have got the days listed in a select dropdown with multiple select values allowed when saving to offer as follows:
_form.html.erb:
<div class="form-group">
{!! Form::select('days[]', $days, (isset($offer)) ? $offer->days->lists('id')->toArray() : null, ['class' => 'form-control', 'multiple' => true]); !!}
</div>
In the controller I use this in the create method:
public function store(Request $request, Offer $offer)
{
$offerId = $offer['id'];
$mytime = Carbon::now('Europe/London');
$currentTime = $mytime->format('h:ia');
$data = Input::except('image');
$validation = Validator::make($data, Offer::$rules);
if ($validation->fails()) {
return redirect('offers')->with('message', $validation->errors());
} else {
$offer = new Offer($request->input());
$day = Day::find($request->day);
$type = Type::find($request->type);
$file = Input::file('image');
$filename = date('Y-m-d-H')."-".$file->getClientOriginalName();
$path = public_path('images/offers/' . $filename);
Image::make($file->getRealPath())
->save($path);
$offer->save();
$offer->days()->sync( $request->get('days') );
$types = $offer->types()->save($type);
}
The issue I am having with this is its only saving one day out of what was selected in the select dropdown not all of them.
Can anyone tell mw where I might be going wrong with this?
Thanks,
Mark

Categories