is this Laravel Relationship error undefined variable $task - php

I am developing project management app in Laravel 5.2. in My application I have one project many tasks and one task have many file attachments. this is My file attachment view file
#foreach($task->files as $file) //line 14
<div>
<div><i class="fa fa-check-square-o"></i>
<span>
{{ $file->file_name }}
</span>
</div>
</div>
and My FileController is this
use Cloudder;
use App\File as File;
use App\Task;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class FilesController extends Controller
{
public function uploadAttachments(Request $request,$id,$taskId)
{
$this->validate($request, [
'file_name' => 'required|mimes:jpeg,bmp,png,pdf|between:1,7000',
]);
$filename = $request->file('file_name')->getRealPath();
Cloudder::upload($filename, null);
list($width, $height) = getimagesize($filename);
$fileUrl = Cloudder::show(Cloudder::getPublicId(), ["width" => $width, "height" => $height]);
$this->saveUploads($request, $fileUrl, $id,$taskId);
and route is this
Route::post('projects/{projects}/tasks/{tasks}/', [
'uses' => 'FilesController#uploadAttachments',
'as' => 'projects.files',
'middleware' => ['auth']
]);
but got this error
ErrorException in ae0a86ab95cb7f092eb44a17fd000e94f21b305d.php line 14:
Undefined variable: task (View: C:\Users\13\Desktop\acxian\resources\views\files\form.blade.php)
how can fix this problem?
file Model
use Auth;
use App\Task;
use Illuminate\Database\Eloquent\Model;
class File extends Model
{
public function scopeProject($query, $id)
{
return $query->where('project_id', $id);
}
public function scopeTask($query, $taskId)
{
return $query->where('task_id', $taskId);
}
public function task(){
return $this->belongsTo(Task::class);
}

You have to pass the $task collection to your blade view as shown below
$task = Task::all() //collect task collection as per your logic
return view('files.form', compact('task'));

You have to pass $task data to your view (blade file) like this
return view('files.form', $task);

public function show($project_id,$task_id) {
$project = Project::find($project_id);
$task = Task::find($task_id);
return view('task.show', ['task' => $task,'project' => $project]);
}

Related

images do not display in Laravel 8

am trying to store images in storage folder in Laravel 8 and at the same time fetch that image and displays it in browser, unfortunately, the images get saved but do not display
here is my file
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class PostsController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function create(){
return view('posts.create');
}
public function store(){
$data = request()->validate([
'caption' => 'required',
'image' => ['required','image']
]);
$imagePath = request('image')->store('uploads','public');
$image = Image::make(public_path("{C:\xampp\htdocs\app\storage\app\public\uploads\
{$imagePath}"))->fit(1000,1000);
$image->save();
dd($imagePath);
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image'=>$imagePath,
]);
return redirect('/profile/'. auth()->user()->id);
}
public function show(\App\Models\Post $post){
return view('posts.show', compact('post'));
}
}
any help guys

Class 'App/Post' not found in laravel-5.6

While i was working on my laravel project i got this error and i am unable to solve it even after so much changes and effort. I hope i get some solution.
My ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError thrown with
message "Class 'App/Post' not found"
CommentsController.php
<?php
namespace App\Http\Controllers;
use \Auth;
use App\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Comment;
use Session;
use DB;
class CommentsController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required',
'comment' => 'required'
]);
$post = Post::find('id');
$comments = new Comment();
$comments->name = $request->name;
$comments->email = $request->email;
$comments->comment = $request->comment;
$comments->approved = true;
$comments->post()->associate($post);
$comments->save();
Session::flash('success', 'Comment was added');
return redirect()->route('posts.show', [$post->id]);
//return redirect('/posts')->with('success', 'Comment Created
Successfully');
}
}`
Post.php
`
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//Table Name
protected $table = 'posts';
//Primary Key
public $primaryKey = 'id';
//Timestamps
public $timestamps = true;
public function user(){
return $this->belongsTo('App\User');
}
public function comment(){
return $this->hasMany('App\Comment');
}
}
`
My Web.php (Route File)
`
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/contact', 'PagesController#contact');
Route::get('/services', 'PagesController#services');
// Post Pages
Route::resource('posts', 'PostsController');
// Login Authorization
Auth::routes();
// Dashboard
Route::get('/dashboard', 'DashboardController#index');
// Comments
Route::post('/posts/{post_id}', ['uses'=>'CommentsController#store' , 'as' => 'comments.store']);
`
Write this code top of the controller....
use App\Post;
or
Change this code...
$post = Post::find('id');
To
$post = \App\Post::find('id');
I think this is solved.
pay attention about file Post.php
use App\Post;
just A is Capital not all APP

How to save array of objects to mysql database in laravel?

I am using vue with laravel. I am trying to save array of objects but not able to do it though i am able to save single object. Here is my code
App.vue
// Not working
saveData(){
this.axios.post('/addperson', **this.rows**).then((response) => {
console.log("WOW");
})
}
//working
saveData(){
this.axios.post('/addperson', **this.rows[0]**).then((response) => {
console.log("WOW");
})
}
Here is controller code where i am getting error when i pass array.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\OrderPerson;
class PersonController extends Controller
{
public function create(Request $request){
$person = new Person([
'name' => $request->get('name'),
'age' => $request->get('age'),
'user_id' =>$request->get('user_id')''
]);
$person->save();
return response()->json('Successfully added');
}
}
Can any body help me to save the array?
First of all assign all the this.rows to a data set then push it to the axios call something like this:
saveData(){
const postData = {
data: this.rows
}
this.axios.post('/addperson', postData).then((response) => {
console.log("WOW");
})
}
Now in laravel controller you can use foreach to use this data set.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\OrderPerson;
class PersonController extends Controller
{
public function create(Request $request){
foreach($request->data as $data)
{
$container = new Person([
'name' => $data['name'],
'age' => $data['age'],
'user_id' => $data['user_id']
]);
$container->save();
}
return response()->json('Successfully added');
}
}
Hope this helps.

Laravel Undefined offset error

I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!

Passing multiple parameters to controller in Laravel 5

In my application, a user has the ability to remind another user about an event invitation. To do that, I need to pass both the IDs of the event, and of the user to be invited.
In my route file, I have:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
In my view, I have:
{!!link_to_route('remindHelper', 'Remind User', $parameters = array($eventid = $event->id, $userid = $invitee->id) )!!}
In my controller, I have:
public function remindHelper($eventid, $userid)
{
$event = Events::findOrFail($eventid);
$user = User::findOrFail($userid);
$invitees = $this->user->friendsOfMine;
$invited = $event->helpers;
$groups = $this->user->groupOwner()->get();
return view('events.invite_groups', compact('event', 'invitees', 'invited', 'groups'));
}
However, when I hit that route, I receive the following error:
Missing argument 2 for App\Http\Controllers\EventsController::remindHelper()
I'm sure I have a formatting error in my view, but I've been unable to diagnose it. Is there a more efficient way to pass multiple arguments to a controller?
When you define this route:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
You are saying that a single URI argument will be passed to the method.
Try passing the two arguments, like:
Route::get('events/{event}/remind/{user}', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
View:
route('remindHelper',['event'=>$eventId,'user'=>$userId]);
Route :
Route::get('warden/building/{buildingId}/employee/{employeeId}',[
'uses'=>'WardenController#deleteWarden',
'as'=>'delete-warden'
]);
View :
Controller:
public function deleteWarden($buildingId,$employeeId){
$building = Building::find($buildingId);
$building->employees()->detach($employeeId);
return redirect('warden/assign/'.$buildingId)->with('message','Warden Detached successfully');
}
This is how you do it:
Click Here
Go to your controller and write code like following:
public function passData()
{
$comboCoder=['Bappy','Sanjid','Rana','Tuhin'];
$ffi=['Faisal','Sanjid','Babul','Quiyum','Tusar','Fahim'];
$classRoom=['Sanjid','Tamanna','Liza'];
return view('hyper.passData',compact('comboCoder','ffi','classRoom'));
}
/*
Again, in View part use:
(passData.blade.php)
*/
<u>Combocoder:</u>
#foreach($comboCoder as $c)
{{$c}}<br>
#endforeach
<u>FFI</u>
#foreach($ffi as $f)
{{$f}}<br>
#endforeach
<u>Class Room </u>
#foreach($classRoom as $cr)
{{$cr}}<br>
#endforeach
Route::get('/details/{id}/{id1}/{id2}', 'HomeController#SearchDetails');
//pass data like the below code
<a href="{{url("/details/{$orga_list->dcode}/{$orga_list->dname}/{$GroupHead}")}}"
target="_blank" > Details </a>
//controller write like the below code
public function SearchDetails($id, $searchtext,$grp_searchtext)
{
// get data like the below code
$data['searchtext'] = $searchtext;
$data['grp_searchtext'] = $grp_searchtext;
$data['id_is'] = $id;
}
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('author/{author_name}/book/{title}', 'show')
->name('book.show');
});
Now update the controller like:
app/Http/Controllers/BookController.php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Author;
use Illuminate\Http\Request;
class BookController extends Controller
{
public function show(Request $request, Author $author, Book $book)
{
return view('show',[
'book' => $book->show($request)
]);
}
}
Now update the book model:
app\Models\Book.php
namespace App\Models;
use App\Common\HasPdf;
use App\Common\HasImage;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Book extends Model
{
use HasFactory;
protected $guarded = [];
public function author() : BelongsTo
{
return $this->belongsTo(Author::class);
}
public function url()
{
return URL::route('book.show', [
'author_name' => $this->author->author_name,
'title' => $this->title,
]);
}
}
<h3>{{ $item->title }}</h3>
Hope it can help you.

Categories