Migration nullable field causing issues - php

I have created a migration called 'create_modules_table' see code below.
public function up()
{
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('course_id')->nullable();
$table->foreign('course_id')->references('id')->on('courses');
$table->string('title');
$table->timestamps();
});
}
I have added a FK 'course_id'. Without 'nullable' i faced an error relating to 'course_id' not having a default value. So i added 'nullable'. However now it is throwing me further problems, when i create a new module and select the course to attach to the module, the field in the DB is null (despite selecting an existing course from my form). I have added an image for context. Can anyone tell me where i am going wrong? I'm not sure how to go about fixing this.
Module.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Module extends Model
{
protected $fillable = [
'title', 'course_id', 'created_at', 'updated_at',
];
public function course()
{
return $this->belongsTo(Course::class, 'course_id');
}
}
ModulesController;
<?php
namespace App\Http\Controllers\Admin;
use App\Module;
use App\Course;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ModulesController extends Controller
{
public function index(Request $request)
{
$modules = new module();
if ($request->input('course_id')) {
$modules = $modules->where('course_id', $request->input('course_id'));
}
$modules = $modules->all();
return view('admin.module.index', compact('modules'));
}
public function create()
{
$courses = Course::all()->pluck('title', 'id');
return view('admin.module.create', compact('courses'));
}
public function store(Request $request)
{
$module = Module::create($request->all());
return redirect()->route('admin.modules.index', ['course_id' => $request->id]); //redirects to correct route by adding course_id in parameter
}
}
create.blade.php;
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Module</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.modules.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Module Title</label>
<input class="form-control" type="text" name="title" id="id" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
{!! Form::label('Courses', 'Course', ['class' => 'control-label']) !!}
{!! Form::select('Course[]', $courses, Request::get('Course'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
index.blade.php;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<p>
<button type="button" class="btn btn-success">Create Module</button>
</p>
<div class="card">
<div class="card-header">Modules</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Module Title</th>
<th>Course Title</th>
<th>Instructor</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($modules as $key => $module)
<tr>
<th scope="row">{{ $module->id }}</th>
<td>{{ $module->title }}</td>
<td>{{ $module->course->title ?? ''}}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
I would like to add there is no error, the DB is simply not displaying an input.. for some reason. Any help is kindly appreciated.

In your form there is no field named course_id, instead you've a field with name Course[] which is a multi-select, so in your store method when you are using Module::create($request->all()); there is no field matching in your $fillable array in the Module model, so you need to map fields manually and also, since you are using an array (because multi-select produces array), you need to use single element from the array to create a relation.
So, one easy approach could be ():
Module::create([
'title' => $request->input('title'),
'course_id' => reset($request->input('course')) // get the first item from array
]);
I think your are missing something, you should not use a multi-select for a foreign key unless you've a many-to-many relation and in that case you'll create/attach multiple related entries in a pivot table.

Related

Laravel - Data not pulling through to form

I have a create form for creating courses, I have assigned users to these courses however for some reason it is not working anymore. I have been through my code umpteen times and I can't find anything that has changed - so i have come here for help.
To give some context below is my index.blade.php. As you can see I have previously assigned users to a course.
Create.blade.php;
#extends('layouts.app')
#section('content')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Create Course</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.courses.store') }}" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label class="required" for="name">Course Title</label>
<input class="form-control" type="text" name="title" id="id" value="{{ old('title', '') }}" required>
#if($errors->has('name'))
<div class="invalid-feedback">
{{ $errors->first('name') }}
</div>
#endif
</div>
<div class="form-group">
#can('create_courses')
{!! Form::label('Instructor', 'Instructor', ['class' => 'control-label']) !!}
{!! Form::select('Instructor[]', $instructors, Request::get('Instructor'), ['class' => 'form-control select2', 'multiple' => 'multiple']) !!}
#if($errors->has('Instructor'))
{{ $errors->first('Instructor') }}
#endif
#endcan
</div>
<div class="form-group">
<button class="btn btn-danger" type="submit">
Save
</button>
</div>
</div>
</form>
</div>
</div>
#endsection
Index.blade.php;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-10">
<p>
#can('create_courses')
<button type="button" class="btn btn-success">Create Course</button>
#endcan('create_courses')
</p>
<div class="card">
<div class="card-header">Courses</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Course Title</th>
<th>Instructor</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($course as $course)
<tr>
<th scope="row">{{ $course->id }}</th>
<td>{{ $course->title}}</td>
<td>{{ implode (', ', $course->instructors()->pluck('name')->toArray()) }}</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-secondary" href="{{ route('admin.modules.index', $course->id) }}">
Modules
</a>
#endcan
</td>
<td>
#can('edit_courses')
<a class="btn btn-xs btn-primary" href="{{ route('admin.courses.edit', $course->id) }}">
Edit
</a>
#endcan
</td>
<td>
#can('delete_courses')
<form action="{{ route('admin.courses.destroy', $course->id) }}" method="POST" onsubmit="return confirm('Confirm delete?');" style="display: inline-block;">
<input type="hidden" name="_method" value="DELETE">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-xs btn-danger" value="Delete">
</form>
#endcan
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- <div class="col-md-2 col-lg-2">
<div class="list-unstyled">
Courses
Modules
</div>
</div> -->
</div>
</div>
#endsection
CoursesController.php;
<?php
namespace App\Http\Controllers\Admin;
use Gate;
use App\User;
use App\Course;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;
class CoursesController extends Controller
{
public function __construct()
{
//calling auth middleware to check whether user is logged in, if no logged in user they will be redirected to login page
$this->middleware('auth');
}
public function index()
{
if(Gate::denies('manage_courses')){
return redirect(route('home'));
}
$courses = Course::all();
return view('admin.course.index')->with('course', $courses); //pass data down to view
}
public function create()
{
if(Gate::denies('create_courses')){
return redirect(route('home'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name'); //defining instructor variable to call in create.blade.php. Followed by specifying that only users with role_id:2 can be viewed in the select form by looping through the pivot table to check each role_id
return view('admin.course.create', compact('instructors')); //passing instructor to view
}
public function store(Request $request)
{
$course = Course::create($request->all()); //request all the data fields to store in DB
$course->instructors()->sync($request->input('instructors', [])); //input method retrieves all of the input values as an array
if($course->save()){
$request->session()->flash('success', 'The course ' . $course->title . ' has been created successfully.');
}else{
$request->session()->flash('error', 'There was an error creating the course');
}
return redirect()->route ('admin.courses.index');
}
public function destroy(Course $course)
{
if(Gate::denies('delete_courses'))
{
return redirect (route('admin.course.index'));
}
$course->delete();
return redirect()->route('admin.courses.index');
}
public function edit(Course $course)
{
if(Gate::denies('edit_courses'))
{
return redirect (route('admin.courses.index'));
}
$instructors = User::whereHas('role', function ($query) {
$query->where('role_id', 2); })->get()->pluck('name');
return view('admin.course.edit')->with([
'course' => $course
]);
}
public function update(Request $request, Course $course)
{
$course->update($request->all());
if ($course->save()){
$request->session()->flash('success', $course->title . ' has been updated successfully.');
}else{
$request->session()->flash('error', 'There was an error updating ' . $course->title);
}
return redirect()->route('admin.courses.index');
}
public function show(Course $course)
{
return view('admin.course.show', compact('course'));
}
}
I am new to laravel so I would appreciate any help.

How to display parent name in Laravel

I have a departments table in db with id,name, and parent.The parent is the id that corresponds to the parent root.Now i have displayed the id(parent id) but i want to show the name of the department that correspond with this id.I have tried the query at the departmentcontroller ,index function but it gives me this error
Illuminate\Database\QueryException
SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'departments' (SQL: select departments.id, departments.parent, departments.name from departments inner join departments on department.id = departments.parent where id = parent)
DepartmentController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Department;
use App\User;
use Illuminate\Support\Facades\DB;
class DepartmentController extends Controller
{
public function usersdep($id)
{
$department = Department::with('users')->find($id);
return view('admin.page-users')->with('users', $department->users);
}
public function treeView()
{
$departments = Department::with('childs')->where('parent', 0)->get();
return view('admin.page',compact('departments'));
}
public function index()
{
//$departments = \App\Department::all();
//return view('admin.department')->with('departments', $departments);
return $departments = DB::table('departments')
->join('departments', 'department.id', '=', 'departments.parent')
->select('departments.id','departments.parent','departments.name')->where('id','=','parent')->get();
}
department.blade.php
#extends ('layouts.master')
#section('title')
Department Management | Admin
#endsection
#section('content')
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New department</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
</div>
<form action="/save-department" method="POST">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group">
<label for="recipient-name" class="col-form-label">Name</label>
<input type="text" class="form-control" name="name" id="recipient-name">
</div>
<div class="form-group">
<label for="recipient-name" class="col-form-label">ID</label>
<input type="text" class="form-control" name="id" id="recipient-id">
</div>
<div class="form-group">
<label for="recipient-name exampleFormControlSelect2" class="col-form-label">Parent ID</label>
<input type="text" class="form-control" placeholder="Choose the department parent id"name="parent" id="recipient-parent">
<select multiple class="form-control" name="parent" id="recipient-parent">
#foreach($departments as $department)
<option>{{ $department->parent }}</option>
#endforeach
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="card-header">
<h4 class="card-title my-4 text-center font-weight-light"> Department Management </h4>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table">
<thead class=" text-primary">
<th>Department</th>
<button type="button" class="btn btn-primary float-right" data-toggle="modal" data-target="#exampleModal" >Add</button>
<thead class=" text-primary">
<th>ID</th>
<th>Name</th>
<th>Parent ID</th>
<th>Edit</th>
<th>Delete</th>
</thead>
</thead>
<tbody>
#foreach($departments as $department)
<tr>
<td>{{ $department->id }}</td>
<td>{{ $department->name }}</td>
<td>{{ $department->parent }}</td>
<td>
Edit
</td>
<td>
<form action="{{ url('department-delete/'.$department->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
See the Departments and Employees
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
#endsection
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
Route::get('/page-users/{id}', 'Admin\DepartmentController#usersdep');//show users
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
Department.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
protected $table = 'departments';
protected $fillable = [
'name',
];
protected $primaryKey = 'id';
public function users()
{
// return $this->belongsTo(User::class);
return $this->hasMany(User::class,'department','id');
}
//category has childs
public function childs() {
return $this->hasMany('App\Department','parent','id') ;
/*
childs() method with hasMany relationship.
hasMany relationship in Laravel tell us that they have multiple childs.
Here I am creating relationship based on parent and each category has their parent if parent id is 0 it means it is root category.*/
}
}
create_departments_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateDepartmentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('parent');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('departments');
}
}
Alternative answer
Model
A Department model might be associated with one parent. To define this relationship, place a parent method on the model. The parent method should call the hasOne method and return its result:
class Department extends Model
{
protected $fillable = [
'name',
'parent_id',
];
public function parent()
{
return $this->hasOne(Department::class, 'id', 'parent_id');
}
}
Migration
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedBigInteger('parent_id')->nullable();
$table->timestamps();
$table->foreign('parent_id')->references('id')->on('departments');
});
Usage
Once the relationship has been defined, you can retrieve the parent :
$departments = Department::get();
foreach ($departments as $department) {
if ($parent = $item->parent) {
dd($department->name, $parent->name);
}
else{
dd('This department is a parent')
}
}
You need to pass the correct department id.
public function index()
{
$departments = DB::table('departments')->select('departments.*')->get();
return view('admin.department', compact('departments'));
}
And view:
#foreach($departments as $department)
<tr>
<td>{{ $department->id }}</td>
<td>{{ $department->name }}</td>
#foreach($departments as $parent)
#if( $department->parent === $parent->id )
<td>{{ $department->name }}</td>
#endif
#endforeach
<tr>
#endforeach
Just define a relation in Department model
public function parentDepartment()
{
return $this->belongsTo(self::class, 'parent');
}
and in index method load it
public function index()
{
$departments = Department::with('parentDepartment')->get();
}

Laravel tasklist tutorial showing page not found

I am trying to learn laravel so I started by following the tasklist tutorial from the laravel website. The page shows fine but when I try to add a task it goes to a page that says: 'Not Found'.
My code:
task.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
//
}
Web.php (routes):
<?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!
|
*/
use App\Task;
use Illuminate\Http\Request;
// Display tasks
Route::get('/', function () {
$tasks = Task::orderBy('created_at', 'asc')->get();
return view('tasks', [
'tasks' => $tasks
]);
});
// Add new tasks
Route::post('/task', function (Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return redirect('/')
->withInput()
->withErrors($validator);
}
$task = new Task;
$task->name = $request->name;
$task->save();
return redirect('/');
});
//Remove tasks
Route::delete('/task{id}', function ($id) {
Task::findOrFail($id)->delete();
return redirect('/');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
And my tasks.blade.php :
#extends('layouts.app')
#section('content')
<!-- Bootstrap Boilerplate... -->
<div class="panel-body">
<!-- Display Validation Errors -->
#include('common.errors')
<!-- New Task Form -->
<form action="/task" method="POST" class="form-horizontal">
{{ csrf_field() }}
<!-- Task Name -->
<div class="form-group">
<label for="task" class="col-sm-3 control-label">Task</label>
<div class="col-sm-6">
<input type="text" name="name" id="task-name" class="form-control">
</div>
</div>
<!-- Add Task Button -->
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button type="submit" class="btn btn-default">
<i class="fa fa-plus"></i> Add Task
</button>
</div>
</div>
</form>
</div>
<!-- Current Tasks -->
#if (count($tasks) > 0)
<div class="panel panel-default">
<div class="panel-heading">
Current Tasks
</div>
<div class="panel-body">
<table class="table table-striped task-table">
<!-- Table Headings -->
<thead>
<th>Task</th>
<th> </th>
</thead>
<!-- Table Body -->
<tbody>
#foreach ($tasks as $task)
<tr>
<!-- Task Name -->
<td class="table-text">
<div>{{ $task->name }}</div>
</td>
<!-- Delete Button -->
<td>
<form action="/task/{{ $task->id }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button>Delete Task</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
#endif
#endsection
This is the page I see when clicking 'add task':
What am I doing wrong? I'm using Laravel 5.4

How store create time automatically to the table when we create new ID

In my group page i am creating new group ID, when i create the groupID automatically that time need to store into database, column creationTime. I am using laravel 5.2 framework for building my application. How can i take that creation time and store the same to the database when inserting groupID to the table.
my GroupController.php
public function groupInsert()
{
$postGeozone=Input::all();
//insert data into mysql table
$account = Account::select('accountID')->get();
foreach ($account as $acc) {
$abc = $acc->accountID;
}
$data = array(
"accountID" => $abc,
"groupID"=> $postGeozone['groupID']
);
//$data=array('groupID'=> $postGeozone['groupID']);
$ck=0;
$ck=DB::table('devicegroup')->insert($data);
$groups = DB::table('devicegroup')->simplePaginate(5);
return view('group.groupAdmin')->with('groups',$groups);
}
groupAdmin.blade.php is
#extends('app')
#section('content')
<div class="templatemo-content-wrapper">
<div class="templatemo-content">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Group information</li>
</ol>
<h1>View/Edit Group information</h1>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="example" class="table table-striped table-hover table-bordered">
<h3>Select a Group :</h3>
<thead>
<tr>
<th>Group ID</th>
<th>Group Name</th>
<th>Vehicle Count</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($groups as $grp)
<tr>
<td>{{ $grp->groupID }}</td>
<td>{{ $grp->description }}</td>
<td></td>
<td>
<div class="btn-group">
<button type="button" class="btn btn-info">Action</button>
<button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown">
<span class="caret"></span>
<span class="sr-only">Toggle Dropdown</span>
</button>
<ul class="dropdown-menu" role="menu">
{{--#if ($nam->isActive == 'Yes')--}}
<li data-toggle="modal" data-target="#acceptModal" data-bookingid="{{ $grp->groupID }}">View/ Edit
</li>
{{--#endif--}}
<li>Delete</li>
</ul>
</div>
</td>
</tr>
#endforeach
</tbody>
</table>
{{$groups->links()}}
</div>
</div>
</div>
</div>
</div>
</br>
{{--Creating new group--}}
{{--------------------------------------------------}}
<h4>Create a new Group</h4>
<form role="form" method="POST" action="{{ url('groupAdmin') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="row">
<div class="col-md-6 margin-bottom-15">
<input type="text" class="form-control" name="groupID" value="{{ old('groupID') }}" placeholder="Enter Group ID">
</div>
<div class="row templatemo-form-buttons">
<div class="submit-button">
<button type="submit" class="btn btn-primary">New</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
#endsection
routes.php
Route::any('groupAdmin', 'GroupController#getIndex');
Route::post('groupAdmin', 'GroupController#groupInsert');
model Group.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Group extends Model
{
protected $table = 'devicegroup';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'groupID', 'description',
];
protected $hidden = [
'password', 'remember_token',
];
}
Can anyone please tell how to do ,
replies are appreciable.
Use
Schema::table('devicegroup', function (Blueprint $table) {
$table->timestamps();
});
in your migration and Laravel will include inserted_at and updated_at for you and it will also take care of updating this columns for you when you use the model to insert data. You will not need to add any code to get the dates set.
Also you have a Group model, but you are not using it in your controller. Instead of DB::table('devicegroup')->insert($data); you could use Group::create($data); and similar for getting data.
Select Mysql Date type Timestamp Desfault value CURRENT_TIMESTAMP
example:
ALTER TABLE `tbl_name` ADD `cdate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;
if use model work is very simple and create and update time updated automatic.
1-create model with name Group and extend model
2-add to filed created_at and updated_at in database devicegroup table
3-for add new data to this use below code :
$group = new Group();
$group->accountID = $abc;
$group->groupID = $postGeozone['groupID'];
$group->save();
and created_at filed automaticly inserted.

Laravel 5.1 Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string

I have problem with my laravel 5.1 error Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string when i click delete
GalleryController.php
public function deleteGallery($id)
{
//load the gallery
$currentGallery = Gallery::findOrfail($id);
// check ownership
if ($currentGallery->created_by != Auth::user()->id) {
abort('403','You are not allowed to delete this gallery');
}
// get the images
$images = $currentGallery->images();
// delete the images
foreach ($currentGallery->$images as $image) {
unlink(public_path($image->file_path));
}
// delete the DB records
$currentGallery->images()->delete();
$currentGallery->delete();
return redirect()->back();
}
Route.php
Route::get('gallery/delete/{id}','GalleryController#deleteGallery');
Model Gallery.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Gallery extends Model
{
protected $table = 'gallery';
public function images()
{
return $this->hasMany('App\Image');
}
}
Model Image.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class image extends Model
{
protected $fillable = ['gallery_id', 'file_name', 'file_size', 'file_mime', 'file_path',
'created_by'];
public function gallery()
{
return $this->belongsTo('App\Gallery');
}
}
Views gallery.blade.php
#extends('master')
#section('content')
<div class="row">
<div class="col-md-12">
<h1>My Gallery</h1>
</div>
</div>
<div class="row">
<div class="col-md-8">
#if ($galleries->count() > 0)
<table class="table table-striped table-bordered table-responsive">
<thead>
<tr class="info">
<th>Name of the gallery</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($galleries as $gallery)
<tr>
<td>{{$gallery->name}}
<span class="pull-right">
{{ $gallery->images()->count() }}
</span>
</td>
<td>View /
Delete
</td>
</tr>
#endforeach
</tbody>
</table>
#endif
</div>
<div class="col-md-4">
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form class="form" method="POST" action="{{url('gallery/save')}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<input type="text" name="gallery_name"
id="gallery_name" placeholder="Name of the gallery"
class="form-control"
value="{{ old('gallery_name')}}" />
</div>
<button class="btn btn-primary">Save</button>
</form>
</div>
</div>
#endsection
In the gallery controller you don't need to get the images since you’re not using the variable anywhere else. Hence remove the lines
// get the images
$images = $currentGallery->images();
Just have the foreach be as
// delete the images
foreach ($currentGallery->images as $image) {
unlink(public_path($image->file_path));
}
please note use of $currentGallery->images
Change:
$images = $currentGallery->images();
To:
$images = $currentGallery->images;

Categories