Laravel 5.6 Model relation and Array - laravel

Contorller#edit
public function edit(Choice $choice){
$choice = Choice::find($choice->id);
return view('choices.edit',compact('choice'));
}
View
{!! Form::model($choice, ['method' => 'PATCH','route' => ['choices.update', $choice->id]]) !!}
<input class="form-control" step="1" min="0" value="{{ $choice->question_number }}" max="" type="number" name="number"></input><br/>
{!! Form::submit('Шинэчлэх', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
Model of Choice
protected $fillable = [
'user_id',
'time',
'topic_id',
'question_number'
];
public function topic(){
return $this->belongsTo('App\Topic');
}
Im trying to set MAX in view's input by that one(bottom of this one).
And here is it
$duplicates = Question::selectRaw("count('id') as total, topic_id")->with('topic', 'topic.choices')->groupBy('topic_id')->get()->toArray();
array:34 [▼
0 => array:3 [▼
"total" => 30 <<<<<<<< TRYING TO SET BY MAX
"topic_id" => 1
"topic" => array:6 [▶]
]

Related

User Model return null for the user name

I'm trying to display the users name using blade, but Its says null.
This is the controller
public function edit(Project $project)
{
//
$project = Project::findOrFail($project->id);
$assignees = User::with('roles')->get();
return view('projects.edit',['project'=>$project,'assignees'=>$assignees]);
}
When I dd($assignees) all the columns appears including the name column.
#attributes: array:10 [▼
"id" => 4
"name" => "Kitten Moose"
"email" => "kitten#karata.com"
"email_verified_at" => null
"password" => "$2y$10$iG4EZBq13ExGOVIrGNhEQeVvordWc3ibWfYgdaq6x0wqefetqXixe"
"remember_token" => null
"created_at" => "2020-07-03 05:11:56"
"updated_at" => "2020-07-11 09:37:49"
"team_id" => 3
"deleted_at" => null
]
On blade:
<div class="form-group">
<label for="exampleFormControlSelect1">Assignee</label>
<select name="assignee_id" class="js-example-basic-single">
<option value=" ">Select</option>
#foreach($assignees as $assignee)
<option value="{{$assignee->id}}">{{$assignee->name}}</option>
#endforeach
</select>
</div>
Using the blade above, I get {"id":1,"name":null} everything else displays correctly
I'm not sure if this could be caused by the model, but I have this in the user model:
public function assignee()
{
return $this->belongsTo(User::class);
}

Add date into table which is in relation with product in Laravel 6

I have product and auction table. I want to add auction deadline on a specific table using form. when I submit the form the product_id in auction table is not populated and deadline shows time on which form is submited.
Here what I am trying:
I want that the create form get the deadline and store in auction table with product id so I can access it in show method of product.
create.blade.php
#extends('layouts.app')
#section('content')
<div class="mt-3" style="margin-left: 50px;">
<h2>Add new product</h2>
{!! Form::open(['action' => 'ProductsController#store', 'method' => 'POST', 'enctype' =>
'multipart/form-data', 'class' => 'w-50 py-3']) !!}
<div class="form-group">
{{Form::label('name', 'Product Name')}}
{{Form::text('name', '', ['class' => 'form-control', 'placeholder' => 'Product Name'])}}
</div>
<div class="form-group">
{{Form::label('description', 'Product Description')}}
{{Form::textarea('description', '', ['class' => 'form-control', 'placeholder' => 'Product Description', 'rows' => '4'])}}
</div>
<div class="form-group">
{!! Form::Label('category', 'Category') !!}
<select class="form-control" name="category_id">
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
{{Form::label('price', 'Product Price')}}
{{Form::number('price', '', ['class' => 'form-control', 'placeholder' => 'Product Price'])}}
</div>
<div class="form-group">
{{Form::label('deadline', 'Auction Deadline')}}
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('image', 'Product Image')}}
{{Form::file('image', ['class' => '', 'placeholder' => 'Product Image'])}}
</div>
{{Form::submit('Upload Product', ['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
</div>
#endsection
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'price', 'description', 'image',
];
public function category()
{
return $this->belongsTo('App\Category');
}
public function auction()
{
return $this->hasOne('App\Auction');
}
}
ProductsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Product;
use App\Category;
use App\Auction;
class ProductsController extends Controller
{
public function index()
{
$categories = Category::all();
$products = Product::with('category')->latest()->paginate(3);
return view('products.index' ,compact('categories', 'products'));
}
public function create()
{
$categories = Category::all(['id', 'name']);
return view('products.create', compact('categories',$categories));
}
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$product->save();
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
return redirect('/products')->with('success', 'Product Created');
}
public function show($id)
{
$product = Product::find($id);
return view('products.show', compact('product'));
}
}
you are just creating auction, where is the relation? Delete $product->save(); line. After the $auction->save(); add this line:
$product->auction()->associate($auction);
$product->save();
Final Store method
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'category_id' => 'required',
'price' => 'required',
'image' => 'image|nullable',
]);
// Create Product
$product = new Product();
$product->name = request('name');
$product->description = request('description');
$product->category_id = request('category_id');
$product->price = request('price');
$product->image = $fileNameToStore;
$auction = new Auction();
$auction->deadline = request('deadline');
$auction->save();
$product->auction()->associate($auction);
$product->save();
return redirect('/products')->with('success', 'Product Created');
}
Update for Irrelevant Blade problem
This line is wrong:
{{Form::date('{{$auction->deadline}}', '', ['class' => 'form-control'])}}
You are using blade close string tag in blade string tag.
Should be:
{{Form::date('deadline', '', ['class' => 'form-control'])}}
If auction variable has been passing from controller this will work

How to upload excel file in Laravel using laravelcollective?

I have a problem when import data xlsx using package fast excel.
I wanna input excel files include the Id from different model like following below
app/http/clustercontroller :
public function Import($id)
{
$model = Cluster::findOrFail($id);
return view('components.Admin.import', compact('model'));
}
public function StoreImport($id, Request $request)
{
//VALIDASI
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx',
]);
if ($request->hasFile('file')) {
$file = $request->file('file'); //Get File
$collection = (new FastExcel)->import($file, function ($line) use ($id) {
return Soal::create([
'soal' => $line['Soal'],
'image' => $line['Image'],
'A' => $line['A'],
'B' => $line['B'],
'C' => $line['C'],
'D' => $line['D'],
'E' => $line['E'],
'kunci' => $line['Kunci'],
'cluster_id' => $id
]); //Import File
});
}
}
resource/admin/import.blade.php :
{!! Form::model($model, [
'route' => $model->exists ? ['cluster.soal.store', $model->id] : 'cluster.soal.create',
'method' => $model->exists ? 'POST' : 'POST',
'files' => true
]) !!}
<div class="form-group">
<label for="" class="control-label">Cluster</label>
{!! Form::text('cluster', null, ['class' => 'form-control', 'id' => 'cluster']) !!}
</div>
<div class="form-group">
<label for="" class="control-label">File .xlsx</label>
{!! Form::file('files') !!}
</div>
{!! Form::close() !!}
the code above displays the form, but when I click submit there is no response
You don't seem to return a response in your Controller method, so that's one reason I can think of. I assume your models are stored?
Things you could do to improve:
Return a view or, even better, redirection after finishing the import
Surround your code with try/catch blocks

Show popup after confirm form with upload information in Laravel

i have a web page in laravel 5.2, with a form where you must enter a video file to upload to my server.
This is the form:
#extends('layouts.app')
#section('content')
<link href='assets/vendor/parsleyjs/src/parsley.css' rel='stylesheet' />
#if (Auth::guest())
<script type="text/javascript">
window.location = "/";//here double curly bracket
</script>
#else
#if ((Auth::user()->tipo != "profesor") && (Auth::user()->tipo != "alumno"))
<script type="text/javascript">
window.location = "/";//here double curly bracket
</script>
#endif
#endif
<H3 style="margin-top: 0">Subir Video</H3>
{!! Form::open(['id' => 'newVideo', 'route' =>'upload.store', 'method'=>'POST', 'files'=> true, 'data-parsley-validate'=>'' ]) !!}
<div class = "form-group" style ="display: none;">
{!! Form::label('usuario_id', 'usuario_id:') !!}
{!! Form::text('usuario_id', Auth::user()->id) !!}
</div>
<div class = "form-group" style ="display: none;">
{!! Form::label('state', 'State:') !!}
#if (Auth::user()->tipo == "alumno")
{!! Form::text('state', 3) !!}
#else
{!! Form::text('state', 1) !!}
#endif
</div>
{!! Form::label('name', 'Nombre * :') !!}
{!! Form::text('name', null, ['class'=> 'form-control', 'required'=> '']) !!}
{!! Form::label('description', 'Descripción * :') !!}
{!! Form::textarea('description', null, ['class'=> 'form-control', 'required'=> '']) !!}
{!! Form::label('language', 'Idioma * :') !!}
{!! Form::select('language', Config::get('enums.languages'), ['required'=> '', 'data-parsley-mincheck'=> 1]) !!}
<div class = "form-group">
{!! Form::label('imageRef', 'Imagen Referencial de Video * :') !!}
{!! Form::file('imageRef', ['required'=> '']) !!}
</div>
<div class = "form-group">
{!! Form::label('url', 'Video * :') !!}
{!! Form::file('url', ['required'=> '']) !!}
</div>
<div class = "form-group">
{!! Form::label('subtitle', 'Subtitulos:') !!}
{!! Form::file('subtitle') !!}
</div>
<div class = "form-group">
{!! Form::label('trailer', 'Trailer * :') !!}
{!! Form::file('trailer', ['required'=> '']) !!}
</div>
{!! Form::submit('Registrar',['class' =>'btn btn-primary', 'value' =>'validate']) !!}
{!! Form::close() !!}
#endsection
The Route:
Route::resource('upload','MovieController');
The Controller function (MovieController):
public function store(Request $request)
{
/*$validator = Validator::make($request->all(), [$this->validationRules]);
if ($validator->fails()){
return redirect()->back()->withErrors($validator->errors());
}*/
$movie = Movie::create([
'usuario_id' => $request['usuario_id'],
'asignatura_id' => $request['asignatura_id'],
'name' => $request['name'],
'visit' => $request['visit'],
'language' => $request['language'],
'creation_date' => $request['creation_date'],
'description' => $request['description'],
'imageRef' => $request['imageRef'],
'url' => $request['url'],
'state' => $request['state'],
'production_year' => $request['production_year'],
'category' => $request['category'],
'category2' => $request['category2'],
'shooting_format' => $request['shooting_format'],
'direction' => $request['direction'],
'direction_assistant' => $request['direction_assistant'],
'casting' => $request['casting'],
'continuista' => $request['continuista'],
'script' => $request['script'],
'production' => $request['production'],
'production_assistant' => $request['production_assistant'],
'photografic_direction' => $request['photografic_direction'],
'camara' => $request['camara'],
'camara_assistant' => $request['camara_assistant'],
'art_direction' => $request['art_direction'],
'mounting' => $request['mounting'],
'image_postproduction' => $request['image_postproduction'],
'sound_postproduction' => $request['sound_postproduction'],
'catering' => $request['catering'],
'music' => $request['music'],
'actors' => $request['actors'],
]);
$movieId = $movie->id;
if($request['subtitle'] != null){
$sub = Subtitle::create([
'video_id' => $movieId,
'url' => $request['subtitle'],
]);
}
if($request['trailer'] != null){
$trailer = Trailer::create([
'video_id' => $movieId,
'url' => $request['trailer'],
]);
if($request['trailer_subtitle'] != null){
$trailerId = $trailer->id;
$subTrailer = Subtitle::create([
'trailer_id' => $trailerId,
'url' => $request['trailer_subtitle'],
]);
}
}
return "OK";
}
The Model:
class Movie extends Model
{
protected $table = "movies";
protected $fillable = ['usuario_id','asignatura_id','name','language','creation_date','description','imageRef','url','state','production_year','category','category2','shooting_format','direction','direction_assistant','casting','continuista','script','production','production_assistant','photografic_direction','camara','camara_assistant','art_direction','sonorous_register','mounting','image_postproduction','sound_postproduction','catering','music','actors'];
public function setImageRefAttribute($imageRef){
$this->attributes['imageRef'] = Carbon::now()->second.$imageRef->getClientOriginalName();
$name = Carbon::now()->second.$imageRef->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($imageRef));
}
public function setUrlAttribute($url){
$this->attributes['url'] = 'old/'.Carbon::now()->second.$url->getClientOriginalName();
$name = Carbon::now()->second.$url->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($url));
$file = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name,PATHINFO_EXTENSION);
$ffmpeg = \FFMpeg\FFMpeg::create([
'ffmpeg.binaries' => '/Applications/MAMP/htdocs/FFmpeg/ffmpeg',
'ffprobe.binaries' => '/Applications/MAMP/htdocs/FFmpeg/ffprobe',
'timeout' => 0, // The timeout for the underlying process
'ffmpeg.threads' => 12, // The number of threads that FFMpeg should use
]);
$video = $ffmpeg->open($url);
//$format = new CustomVideo();
$format = new FFMpeg\Format\Video\X264('libmp3lame', 'libx264');
$format->on('progress', function ($video, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
-> setKiloBitrate(1000)
-> setAudioChannels(2)
-> setAudioKiloBitrate(256);
$video
->save($format, 'files/convert/videos/'.$file.'.mp4');
$this->attributes['url'] = $file.'.mp4';
$ffmpeg_path = '/Applications/MAMP/htdocs/FFmpeg/ffmpeg'; //Path to your FFMPEG
$video_path = 'files/convert/videos/'.$file.'.mp4'; // Path to your Video
$command = $ffmpeg_path . ' -i "' . $video_path . '" -vstats 2>&1';
$output = shell_exec($command);
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
$hours = 0;
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$video_Length = $hours . ":" . $mins . ":" . $secs;
$this->attributes['duration'] = $video_Length;
}
/*->save(new FFMpeg\Format\Video\X264(), 'export-x264.mp4')
->save(new FFMpeg\Format\Video\WMV(), 'export-wmv.wmv')
->save(new FFMpeg\Format\Video\WebM(), 'export-webm.webm');*/
//audio
/* $ffmpeg = FFMpeg\FFMpeg::create();
$audio = $ffmpeg->open('track.mp3');
$format = new FFMpeg\Format\Audio\Flac();
$format->on('progress', function ($audio, $format, $percentage) {
echo "$percentage % transcoded";
});
$format
-> setAudioChannels(2)
-> setAudioKiloBitrate(256);
$audio->save($format, 'track.flac');*/
}
public static function Movies(){
return DB::table('movies')
->join('subjects','subjects.id','=','movies.asignatura_id')
->select('movies.*')
->get();
}
}
I need display a popup when the form is submitted with information of the video upload similar to xibo popup but much simpler.
I need something like this:
I failed to find the solution.

Laravel Multiple Inputs Search 4.2

I am making a multiple inputs search query and i need help cause i do not know how to exactly to do this i have read all the documentation and i did not understand it.Now i am stuck in the controller.....
Also i would really appreciate of how to call the informations that i want in in the show.blade ! Thank you for any help !
Index blade
<div class="panel-body">
<div class="form-group">
<div><h4></h4></div>
<div class="form-group col-md-4">
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
<div id="prefetch">
{{ Form::text('name', null, array('class' => 'typeahead form-group form-control', 'placeholder' => 'name...')) }}
{{ Form::text('lastname', null, array('class' => 'form-group form-control', 'placeholder' => 'lastname...')) }}
{{-- {{ Form::text('id', null, array('class' => 'form-group form-control', 'placeholder' => 'id...')) }}
{{ Form::text('user-seminars', null, array('class' => 'form-group form-control', 'placeholder' => 'Class tha is enrolled...')) }}
{{ Form::text('user-class', null, array('class' => 'form-group form-control', 'placeholder' => 'Class that belongs...')) }}
{{ Form::text('user-annex', null, array('class' => 'form-group form-control', 'placeholder' => 'Department that belongs...')) }}
{{ Form::text('type', null, array('class' => 'form-group form-control', 'placeholder' => 'User type...')) }}
{{ Form::text('date_created', null, array('class' => 'form-group form-control', 'placeholder' => 'date created account...')) }}
{{ Form::text('date_enrolled', null, array('class' => 'form-group form-control', 'placeholder' => 'date enrolled in class...')) }}
routes
Route::get('users/index', 'UserController#index');
Route::get('users/search', 'UserController#search');
Route::get('users/show', 'UserController#show');
UserContoller
public function index(){
return View::make('user.index');
}
public function search(){
return View::make('user.show');
}
public function show(){
return View::make('user.show');
}
USERS TABLE
id , firstname,last_name,etc etc etc
public function search(Request $request){
$users = App\User::where('firstname',$request->name)
->orWhere('lastname',$request->lastname)
->orWhere('id',$request->id)
// more orWhere Clause
->get();
return View::make('user.show',compact('users'));
}
public function show($id){
$user = App\User::find($id);
return View::make('user.show',compact('user'));
}
Why are you using return View::make('user.show') to render two different resources?
the first thing i see its the form action
your code
{{ Form::open(array('action' => array('UserController#search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
should be
{{ Form::open(array('action' => array('users/search'), 'class'=>'form width88', 'role'=>'search', 'method' => 'GET')) }}
the controller is the fun part. if you're looking for all the inputs to be required you should validate it first
//first we set the inputs rultes
$data = Input::all();
$rules = array(
'name' => 'required',
'lastname' => 'required',
//rest of the inputs that are required
);
//then we use the validator method
$val = Validator::make($data,$rules);
if($val->fails())
{
/*redirect to the form again, you can set errors with session
or ->withError($validator)*/
return Redirect::back();
}
then you make your query
$user = User::where('name','=',$data['name'])
->where('lastname','=',$data['lastname'])
//more where('field','=','value')
->get();
if the fields arent required you only make the query with
$user = User::where('name','=',$data['name'])
->orWhere('lastname','=',$data['lastname'])
//more orWhere('field','=','value')
->get();
and finally you return your result to the view like:
return View::make('user.show')->with('user',$user);

Resources