How to return data with Laravel 5 - php

I have problem with method AjaxController::InsertComment($comment,$name); not return $id variable into my ajax.bade.php.
It insert data into database correctly but not return...
Here is my Ajax Controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('ajax.ajax');
}
public static function InsertComment($comment,$name){
$qv = DB::table('comments')->insert(
array(
'name' => $name,
'comments_text' => $comment
)
);
//$id = DB::table('comments')->insertGetId(array('name' => 'john#example.com', 'comments_text' => 'asdasdsa'));
$id = DB::getPdo()->lastInsertId();
return $id;
}
}

Ok, I think I got you now. Suppose we have the following:
Example: ajax.blade.php
<div>{{ "Hi" }} </div>
<script>
$.post('/ajax', {
'_token': $('meta[name=csrf-token]').attr('content'),
task: "comment_insert",
userID: _userID,
comment: _comment,
name: _name,
userName: _userName,
date: _date
}).done(function( data ) {
alert( "ID Loaded: " + data );
});
</script>
Your controller should read like:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class AjaxController extends Controller {
public function __construct()
{
$this->middleware('guest');
}
public function index()
{
return view('ajax.ajax');
}
public static function InsertComment($comment,$name)
{
$id = DB::table('comments')
->insertGetId(array(
'name' => $name,
'comments_text' => $comment
));
return $id;
}
}

Related

How to decode in laravel join

I have json resource collection like this
<?php
namespace App\Http\Resources;
use App\Models\Curriculum;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\DB;
class CurriculumDisplayResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title_section' => json_decode($this->title_section),
'learning_objective'=> json_decode($this->learning_objective),
'content_detail' =>
DB::table('curriculums')
->join('content_texts','curriculums.id','=','content_texts.curriculum_id')
->join('content_files','curriculums.id','=','content_files.curriculum_id')
->join('content_videos','curriculums.id','=','content_videos.curriculum_id')
->join('quizzes','curriculums.id','=','quizzes.curriculum_id')
->select('content_texts.title_text','content_texts.text_course',
'content_files.title_file','content_files.file_course','content_videos.title_video',
'content_videos.video_course','quizzes.title_quiz','quizzes.question','quizzes.answer','quizzes.right_answer')
->get(),
'parent_id' => $this->id,
];
}
}
Can I json decode the result of join quiz?, I just want to json decode the quizzes result. when I'm try display this json resource the result like this
this is the controller
<?php
namespace App\Http\Controllers\Course;
use App\Http\Controllers\Controller;
use App\Http\Resources\CurriculumResource;
use App\Models\Curriculum;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CurriculumController extends Controller
{
public function index()
{
return Curriculum::all();
}
public function store (Request $request)
{
$c = new Curriculum();
$c->title_section = json_encode($request->get('title_section'));
$c->learning_objective = json_encode($request->get('learning_objective'));
$c->user_id = Auth::id();
$c->course_id = $request->get('course_id');
$c->save();
return response(new CurriculumResource($c));
}
}
What's wrong with my code?, I've also made cast for title_quiz, question, answer and right_answer.
Hope this help your problem. It seems like you have double quotation mark
On your Model which has title_quiz, question, answer, and right_answer, add this line of code (depend on your Model):
Model.php
public function getTitleQuizAttribute($value){
return str_replace('\"','', $value);
}
public function getQuestionAttribute($value){
return str_replace('\"','', $value);
}
public function getRightAnswerAttribute($value){
return str_replace('\"','', $value);
}
public function title_quiz($value){
return str_replace('\"','', $value);
}
public function getAnswerAttribute($value){
return json_decode($value);
}
They will modify your string first then pass it to your response
Docs

How can I pass a parameter from the controller index function to the model's functions? LARAVEL

//------------------------------//
//below is the controller index function code //
//------------------------------//
public function index($from, $to,$id)
{
$data=Attendance::where('attendance_date','>=',$from)
->where('attendance_date','<=',$to)
->with('userAttendance')//--> **I need to pass the $id to this function in the model**
->with('admin')
->get()
//---------------------------------//
//below is the model code //
//----------------------------------//
class Attendance extends Model
{
protected $table = "attendances";
protected $fillable=[
'attendance_date',
'admin_id',
];
//---> **i need the $id passed to here**
public function userAttendance()
{
return $this->belongsToMany('App\User', 'user_attendances','attendance_id','user_id')
->withPivot(
'present_absent',
'excuse',
'attendance_key_amount',
'verified_date',
'comment',
);
}
}
just try this
Controller:
public function index()
{
$id = 50;
Product::getId(50);
}
Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public static function getId($id){
dd($id);
}
}

pass var from controller to mail class laravel

I am trying to send a mail with a attachment. Its based on a var from my controller. But I don't know how to pass the content of the variable from my controller to my mail class. My mail view has no problem with using the vars. I need the var in the build method to pick the right file from my directory I generated in my controller.
This returns the following
Missing argument 1 for App\Mail\Aanvraag::build()
Mail class
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\App;
use App\Http\Controllers\aanvragenController;
class Aanvraag extends Mailable
{
use Queueable, SerializesModels;
public $aanvraag;
public function __construct($aanvraag)
{
$this->aanvraag = $aanvraag;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->view('mails.aanvraag')->attach(url('/exports/'. $aanvraag->naam .'sheet.xls'));
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Aanvragen;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use App\Mail\Aanvraag;
class aanvragenController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index() {
if (Auth::id() == 1) {
$aanvragen = Aanvragen::all();
} else {
$userid = Auth::id();
$aanvragen = Aanvragen::where('user_id', $userid)
->orderBy('id')
->take(10)
->get();
}
return view('aanvragen.index', compact('aanvragen'));
}
public function create() {
return view('aanvragen.create');
}
public function store() {
/* $this->validate(request(), [
'studentnummer' => 'unique:aanvragen'
]);*/
$aanvraag = new Aanvragen;
$aanvraag->naam = request('naam');
$aanvraag->studentnummer = request('studentnummer');
$aanvraag->email = request('email');
$aanvraag->telefoonnummer = request('telefoonnummer');
$aanvraag->stagebedrijf = request('stagebedrijf');
$aanvraag->contactpersoon = request('contactpersoon');
$aanvraag->emailContact = request('emailContact');
$aanvraag->telefoonContact = request('telefoonContact');
$aanvraag->begindatum = request('begindatum');
$aanvraag->einddatum = request('einddatum');
$aanvraag->user_id = Auth::id();
$aanvraag->save();
$data = array (
array('Naam', 'Studentnummer', 'Email', 'Telefoonnummer', 'Stagebedrijf', 'Contactpersoon', 'Email contactpersoon'
, 'Telefoon contactpersoon', 'begindatum', 'einddatum'),
array($aanvraag->naam, $aanvraag->studentnummer, $aanvraag->email, $aanvraag->telefoonnummer, $aanvraag->stagebedrijf,
$aanvraag->contactpersoon, $aanvraag->emailContact, $aanvraag->telefoonContact, $aanvraag->begindatum, $aanvraag->einddatum
)
);
$attachment = $aanvraag->naam;
\Excel::create($aanvraag->naam.'sheet', function ($excel) use ($data) {
$excel->sheet('Sheet1', function ($sheet) use ($data) {
$sheet->fromArray($data);
});
})->save();
\Mail::to('johndoe#info.com')->send(new Aanvraag($aanvraag));
return redirect('/');
}
}

Fetching only the soft deleted records

i have created a method to fetch only the soft deleted lessons in my LessonsController
i'm not getting what should be the route my lessoncontroller
<?php
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
class LessonsController extends ApiController
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//delete a lesson by id
public function destroy($id)
{
$dlesson = Lesson::find(input::get('id'));
if(! $dlesson) {
return $this->respondNotFound();
}
$dlesson->delete();
return $this->respondDeleted('Lesson deleted successfully');
}
public function deletedLessons()
{
$deleted_lessons = Lesson::onlyTrashed()->get();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
}
i have tried with a deleted record like
http://localhost:8000/api/v1/lessons/11
Thank You
Make sure:
You've used softDeletes() method in migration and executed this migration
You're using SoftDeletes trait in the model
You've added deleted_at to $dates property in the model
https://laravel.com/docs/5.3/eloquent#soft-deleting
After doing all that your query will work just fine and will return only soft deleted lessons:
$deleted_lessons = Lesson::onlyTrashed()->get();

joinWith multiple tables yii 2

Hi is possible to join multiple table based on a column in yii 2? Right now I am using the concept of joinWith
Take a look at my code:
ActiveCurriculum.php
This is where I am joining the tables
public static function Addblock($group, $clientid){
$subjects = ActiveCurriculum::find()
->select(['scstock.*', 'schead.*', 'glhead.*', 'glfees.*'])
->joinWith('schead')
->joinWith('glhead')
->joinWith('glfees')
->where([
'scstock.sectiongroup' => $group
])
->asArray()
->all();
}
And these are the relations that I set:
Scstock
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Scstock extends ActiveRecord{
public static function tableName()
{
return '{{%scstock}}';
}
public function getSchead(){
return $this->hasOne(Schead::className(), ['TrNo' => 'TrNo']);
}
public function getGlhead(){
return $this->hasOne(Glhead::className(), ['TrNo' => 'TrNo']);
}
public function getGlfees(){
return $this->hasOne(Glfees::className(), ['TrNo' => 'TrNo']);
}
}?>
Schead
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Schead extends ActiveRecord{
public static function tableName()
{
return '{{%schead}}';
}
public function getScstock(){
return $this->hasOne(ActiveCurriculum::className(), ['TrNo' => 'TrNo']);
}
public function getGlhead(){
return $this->hasOne(Glhead::className(), ['TrNo' => 'TrNo']);
}
public function getGlfees(){
return $this->hasOne(Glfees::className(), ['TrNo' => 'TrNo']);
}
}?>
Glhead
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Glhead extends ActiveRecord{
public static function tableName()
{
return '{{%glhead}}';
}
public function getScstock(){
return $this->hasOne(ActiveCurriculum::className(), ['TrNo' => 'TrNo']);
}
public function getSchead(){
return $this->hasOne(Schead::className(), ['TrNo' => 'TrNo']);
}
public function getGlfees(){
return $this->hasOne(Glfees::className(), ['TrNo' => 'TrNo']);
}
}?>
Glfees
<?php
namespace app\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
class Glfees extends ActiveRecord{
public static function tableName()
{
return '{{%glfees}}';
}
public function getGlhead(){
return $this->hasOne(Glhead::className(), ['TrNo' => 'TrNo']);
}
public function getSchead(){
return $this->hasOne(Schead::className(), ['TrNo' => 'TrNo']);
}
public function getScstock(){
return $this->hasOne(ActiveCurriculum::className(), ['TrNo' => 'TrNo']);
}
}?>
But I am getting this error when the query executes
Invalid Parameter – yii\base\InvalidParamException
app\models\ActiveCurriculum has no relation named "glhead".
↵
Caused by: Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\models\ActiveCurriculum::getglhead()
in C:\xampp\htdocs\enrollment\vendor\yiisoft\yii2\base\Component.php at line 285
Am I doing something wrong with the relations or is it something else? Help would be greatly appreaciated. Thank you.
All these relations:
->joinWith('schead')
->joinWith('glhead')
->joinWith('glfees')
must be declared in ActiveCurriculum class. Consult relations in Yii2 documentation.

Categories